Condition for redirecting to different page? - java

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.

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>

How to delete data from database using JDBC

I am trying to make a form where sellers can insert new items, new category and delete items. Now I have problem with DELETE.
This is my code and if somebody know how to fix it please help.
String id = "42";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
System.out.println("Deleted");
}
else
{
System.out.println("Can't delete");
}
} catch (Exception ex) {
System.out.println(ex);
}
Try this:
String id = request.getParameter("id");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/projekat","root","");
PreparedStatement prepared_statement = null;
String strQuery = "DELETE FROM artikli WHERE id= ?";
prepared_statement = connection.prepareStatement(strQuery);
prepared_statement.setString(1, id);
int result_set = prepared_statement.executeUpdate();
if (result_set > 0)
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp");
}
else
{
// System.out.println(result_set);
response.sendRedirect("Prodaja2.jsp?error=Can'tDelete");
}
} catch (Exception ex) {
out.print(ex);
} finally {
try {
stmtProd.close();
connection.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
In your code the semicolon after the query may be conflicting. And also don't forget to close the connections in the finally block created because it may lead to resource leak and connection will remain active even if the user logs out.
One error is here, that is in your syntax
Change the code
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ? ;");
to
PreparedStatement prepared_statement = connection.prepareStatement("DELETE FROM artikli WHERE id= ?");
If there is no other errors, Check value in id, there is a chance of null value.

how to read object from servlet in android

I am developing a android application that has to talk with the servlet to access the database. I want to pass the object from servlet to my android application.
This my servlet code to send object.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text");
String id = request.getParameter("id");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
java.sql.Connection con= DriverManager.getConnection("jdbc:odbc:Database");
Statement statement = con.createStatement();
PrintWriter p = response.getWriter();
ResultSet rs = statement.executeQuery("select * from employee where PS="+id);
while(rs.next()){
Employee e = new Employee();
e.setId(rs.getString("ID"));
e.setPs(String.valueOf(rs.getDouble("PS")));
e.setName(rs.getString("Emp_name"));
e.setDept(rs.getString("Dept"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(e);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How should i read the object in my android application.
Thanks.
Well you can do various things to solve this problem
a)Use DAO practice here Read it to understand it basically it divides the implementation of your code into different segments and classes for your ease.
But if you dont want to go through all that trouble You can do some thing like.
a.) Create a separate java class where you write all the methods to deal with the Db like insert,select etc..
e.g if your loggin in the user.. than the method would be like this..
public int AuthenticateUser(String un, String pw, String phn) {
System.out.println("I m in this method");
Connection conn = (Connection) DBConnection.getInstance().getConnection();
Statement pstmt = null;
ResultSet rs = null;
if (conn == null) {
System.out.println("Connection error");
check = -1;
}
try {
String authenticatequery = "SELECT * FROM users WHERE uname = '"+un+"' && password = '"+pw+"' && phoneno = '"+phn+"'";
System.out.println(authenticatequery);
pstmt = conn.createStatement();
rs = pstmt.executeQuery(authenticatequery);
System.out.println("I m in above try catch");
// pstmt = conn.prepareStatement(authenticatequery);
// rs = pstmt.executeQuery(authenticatequery);
if (rs.next()) {
System.out.println("I am in rs method");
UserInfo info = new UserInfo();
rs.getString(1);
rs.getString(2);
rs.getString(3);
//info.setUsername(rs.getString(un));
System.out.println("i have the username" + un);
//info.setPassword(rs.getString(un));
System.out.println("I have got the password " + pw);
System.out.println("I have got the password " + phn);
System.out.println("User Exist");
check = 1;
} else {
System.out.println("No user found");
check = 0;
}
// rs.close();
// pstmt.close();
// conn.close();
} catch (SQLException e) {
// TODO: handle exception
System.out.println("Exception-internal error");
} finally {
if (conn != null) {
try {
conn.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return check;
}
Notice the int variable "check" if the method runs correctly it will return '1' else '0'.. Now u can use this check for your advantage and send it to your android app via servlet like this..
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//String username = request.getParameter("username");
// String password = request.getParameter("password");
//UserInfo uinfo = new UserInfo();
// uinfo.setUsername(username);
// uinfo.setPassword(password);
System.out.println("I am in process");
PrintWriter out = response.getWriter();
String un, pw,phn;
un = request.getParameter("Usrnm");
System.out.println(un);
pw = request.getParameter("pwd");
System.out.println(pw);
phn = request.getParameter("phn");
System.out.println(phn);
Authenticate auth = new Authenticate();
int check = auth.AuthenticateUser(un, pw,phn);
System.out.println("My result is" + check);
if (check==1){
out.print(1);
} else{
out.print(0);
}
}
}
In your android app you can call the the response object using the code below, do add custom http client class for the comunitcation.
response = CustomHttpClient.executeHttpPost("http://192.1..11../HelloWorldServlet/LoginDriverServlet", postParameters);
Now you can play with the response object and mould it to suit your needs
if (res.equals("1")) {
Log.e("CHeck4 response","i m here");
Log.e("CHeck response", res);
//error.setText("Correct Username or Password");
Intent intent = new Intent(getApplicationContext(), SetStatus.class);
startActivity(intent);
setContentView(R.layout.activity_set_status);
Toast.makeText(getApplicationContext(), "Loggin In", Toast.LENGTH_LONG).show();
} else if(res.equals("0")) {
//error.setText("Sorry!! Incorrect Username or Password");
Log.e("CHeck3 response", "i m here");
Toast.makeText(getApplicationContext(), "Sorry!! Incorrect Username or Password", Toast.LENGTH_LONG).show();
Intent intent = new Intent();
//Username or Password",Toast.LENGTH_LONG).show();
}
Hope you get it..otherwise coments are welcomed :)

Categories