Java Error can't find the symbol - java

Hi I am trying to get a login information through the JSP's. I got an error Can't find symbol : Login while compiling LoginServlet.java
Here is my code, can you please tell the solution of that problem?
Login.java
public class Login
{
public static boolean validate(String name, String pass)
{
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String driver = "oracle.jdbc.driver.OracleDriver";
String userName = "system";
String password = "dad";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName, password);
pst = conn.prepareStatement("select * from login where user=? and password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
}
LoginServlet.java
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void do Post(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
session.setAttribute("pass", p);
if(Login.validate(n,p))
{
Request Dispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else
{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
Request Dispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}

You need to import you Login class in your Servlet.
It might be due to your Login class and LoginServlet both are in different packages. So you need to import Login class in your LoginServlet, before using it.
You need to add something like,
import yourpackage.Login; in the beginning of the LoginServlet

import the Login class in to the LoginServlet.java .
If both are in same package then you have to add it into class path.
it may be helpful for you.
thanks

Related

too many clients already in postgres

I was working on a java project and it was working just fine. I was able to make connections. I closed all the connections properly in finally block. Now I am not able to make connections or even open psql in my terminal. How can I make it work as before. Much much appreciated
import java.sql.Connection;
import com.mchange.v2.c3p0.*;
public class MyConnection {
public static Connection getConnection(){
ComboPooledDataSource cpds1 = new ComboPooledDataSource();
String dbDriver = "org.postgresql.Driver";
String dbName = "jdbc:postgresql://localhost/postgres";
cpds1.setJdbcUrl(dbName);
String userName = "user_1";
cpds1.setUser(userName);
String password = "mypass";
cpds1.setPassword(password);
cpds1.setMaxStatements( 180 );
try
{
cpds1.setDriverClass(dbDriver);
return cpds1.getConnection();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
This is where I'm calling it
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter writer = response.getWriter();
JSONObject jo = new JSONObject();
JSONObject jObj;
Statement stmt = null;
Connection con = null;
PreparedStatement ps;
ResultSet rs = null;
try
{
jObj = UtilityClass.getJSON(request);
String uname = ((String) jObj.get("uname"));
String pass = ((String) jObj.get("pass"));
String sql = "SELECT * FROM users WHERE username = ?";
try
{
con = MyConnection.getConnection();
System.out.println("Got Connection");
stmt = con.createStatement();
ps = con.prepareStatement(sql);
ps.setString(1, uname);
rs = ps.executeQuery();
if(rs.next())
{
if(BCrypt.checkpw(pass,rs.getString("password")))
{
HttpSession session = request.getSession();
session.setAttribute("uname", uname);
if(session.isNew())
{
System.out.println("new");
}
if(uname.equals("admin"))
{
session.setAttribute("role", "admin");
jo.put("status", "admin");
}
else
{
session.setAttribute("role", "user");
jo.put("status", "authenticate");
}
}
}
writer.print(jo);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Not Connected");
}
finally
{
if(rs != null)
{
rs.close();
}
if(stmt != null)
{
stmt.close();
}
if(con != null)
{
con.close();
}
}
}
catch(Exception e)
{
System.out.print("JSON Exception");
}
}
Usually, DB Admins are using pooling technologies on Databases. For PostgreSQL one of the more popularly is a PGBOUNCER. We used PGBOUNCER in our large project, the result is excellent. I recommend it to you. To get more information about the pooling system you can read this link. For About Pooling

CRUD with login Servlet ,JSPand Mysql login implmentation

i am learning CRUD and login.i am having problems login part. i can not get it to working on the servlet side, i have interface userDao :
public interface UsersDao {
public boolean validate(String UserName, String Password);
}
UsersDaoImplementation class:
#Override
public boolean validate(String UserName, String Password) {
boolean status = false;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
String query = "SELECT * FROM Users WHERE UserName=? and Password=?";
preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, UserName);
preparedStatement.setString(2, Password);
resultSet = preparedStatement.executeQuery();
status=resultSet.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
for the servlet this what i have
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String UserName=request.getParameter("UserName");
String Password=request.getParameter("Password");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("UserName", UserName);
if (UsersDaoImplementation.validate(UserName, Password))
{
RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/views/jupiter/jupiter.jsp");
rd.forward(request,response);
}
else
{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/views/system/index.html");
rd.include(request,response);
}
out.close();
}
What is the right way do reslove this? and what am i not doing right?
First, here you take UserName and Password values from request, probably from a html page.
String UserName=request.getParameter("UserName");
String Password=request.getParameter("Password");
Then you compare these values you get with themselves
if (UserName.equals(UserName)
&& Password.equals(Password))
So it will always return true.
Second, inside your if statement you call your validate function, but you don't use its return, you just call it.
dao.validate(UserName,Password);
So, you most likely want to do something like this
if (dao.validate(UserName, Password) {
// user found
}
These line:
if (UserName.equals(UserName) && Password.equals(Password))
make no sense because the comparisons doesn't have function. You compared the variable Username with himself.
1 - RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/views/jupiter/jupiter.jsp");
2 - rd.forward(request,response);
3 - dao.validate(UserName,Password);
At first step you redirect, (line 2), after, in next step, you validate (line 3).
I think that you should change the lines 2 and 3.
1 - RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/views/jupiter/jupiter.jsp");
2 - dao.validate(UserName,Password);
3 - rd.forward(request,response);

Connection pooling ,error-500,NullPointer Exception occured in jboss for mysql

I am unable to get a connection from a datasource and it returns an error-500 The server encountered an internal error () that prevented it from fulfilling this request.
public class Student extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = null;
String pass = null;
Authenticate a=new Authenticate();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
id = request.getParameter("name");
pass = request.getParameter("password");
String result=a.validate(id, pass);
out.println(result);
out.close();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
public class Authenticate extends HttpServlet {
DataSource datasource = null;
String query = "SELECT COUNT(*) FROM studentlogin WHERE name=? and password=?";
public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = new InitialContext();
datasource = (DataSource) envCtx.lookup("java:/apalya");
System.out.println("\t datasooource :: " + datasource);
//datasource = (DataSource) ctx.lookup("apalya");
}
catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public String validate(String name1, String password1) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
int count = 0;
try {
connection = getConnection();
statement = connection.prepareStatement(query);
statement.setString(1, name1);
statement.setString(2, password1);
resultset = statement.executeQuery();
if (resultset.next()) {
count = resultset.getInt(1);
}
if (count == 0) {
return "Invalid Credentials";
} else {
return "Successfully Loggedin";
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
return "Internal Problem";
}
finally {
if (resultset != null) {
try {
resultset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I get a NullPointerException at the getConnection method and error 500 is shown in the browser. I gave the same name of the lookup in the datasource xml file.
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>com.apalya.records.Student</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/stu</url-pattern>
</servlet-mapping>
</web-app>

servlet page shows blank when accessed later

I have a strange issue with servlet page. I have simple web application which contains just a servlet.I deployed it in Tomcat 7. When user enters url, the servlet should get directly executed, get the data from the database and print the output. But it shows blank page after some time. When I undeploy and deploy, it shows data. After some time when I access the page, it shows blank page. Then again when I redeploy, it shows data. Can someone please let me know how to resolve this? I have no clue why it happens. Below is my code.
I am using mysql database.mysql-connector-java-5.1.29-bin.jar added in lib folder and added to buildpath.
public class Homeservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String mysqldblink = "************";
static final String mysqlUsername = "username";
static final String mysqlPassword = "pw";
Connection connection =null;
Statement stmt = null;
/**
* #see HttpServlet#HttpServlet()
*/
public Homeservlet() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(mysqldblink,
mysqlUsername, mysqlPassword);
stmt = connection.createStatement();
}
catch(Exception E)
{
E.printStackTrace();
}
}
#Override
public void service(ServletRequest request, ServletResponse response)
{
PrintWriter pw = null;
try {
String query = "querytogetdata";
pw = response.getWriter();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
pw.println(rs.getString(1));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}finally{
try{
pw.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void destroy( ) {
// Close the connection
try {
if (connection != null)
connection.close( );
if(stmt != null)
stmt.close();
} catch (SQLException ignore) { }
}
}

Condition for redirecting to different page?

I wrote a servlet whose purpose is to login into the application only if the query executes...now what is the condition to be used for invalid username and id...I'm unable to write the condition..pls help me out...the servlet is...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl ","scott","tiger");
System.out.println("cnnection est");
int Id = Integer.parseInt(request.getParameter("id"));
String Name=request.getParameter("firstname");
boolean b=true;
//Connection con =JdbcConnectionUtil.getConnection();
PreparedStatement pst = con.prepareStatement("select * from login where id=? and firstname=?");
pst.setInt(1, Id);
pst.setString(2, Name);
ResultSet rs = pst.executeQuery();
if(rs!=null && rs.next())
{
//while(rs.next()){
PrintWriter pw = response.getWriter();
System.out.println("here");
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
}
//}
else
{
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
}
//
}
catch(Exception ex){
ex.printStackTrace();
}
}
Using rd.forward will solve the problem I think.
How to forward requests from Servlet to JSP
First you check for the correct parameters and then you do the logic. Also do not forget to close statements and connections to avoid memory leaks.
Here is refactored code:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get parameters from request
try {
String idParam = request.getParameter("id");
String name = request.getParameter("firstname");
//check if request contains such parameters
if (idParam == null || name == null) {
throw new IllegalArgumentException(
"Id and Name parameters must not be null.");
}
//try casting idParam to int
Integer id = null;
try {
id = Integer.parseInt(idParam);
} catch (NumberFormatException nfe) {
throw nfe;
}
PreparedStatement pst = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl ", "scott", "tiger");
pst = con.prepareStatement(
"select * from login where id=? and firstname=?");
pst.setInt(1, id);
pst.setString(2, name);
//check if result returned any data
ResultSet rs = pst.executeQuery();
if (!rs.next()) {
throw new Exception(
"No such user for id: " + id + " and name: " + name);
}
PrintWriter pw = response.getWriter();
pw.println("hello");
pw.println(rs.getInt(1));
pw.println(rs.getString(2));
pw.println(rs.getString(3));
} catch (Exception ex) {
throw ex;
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException sqle) {
throw sqle;
}
}
} catch (Exception ex) {
ex.printStackTrace();
RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
rd.forward(request, response);
}
}
Something like that would be appropriate I think.

Categories