user validation

user validation

i hv just started with my lessons in jsp n also doin my final yr project in jsp.i m doin the login page & m stuck with a problem in validating the user.the code i hv written below doesnt redirect to the login page if username & password is invalid but it does redirect only if the username is valid and password invalid.i want know wer i am going wrong in this:

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login2 extends HttpServlet{

private ServletConfig config;

public void init(ServletConfig config)
    throws ServletException{
     this.config=config;
     }
  public void doPost(HttpServletRequest request, HttpServletResponse response) 
              throws ServletException,IOException{
    String userlog = request.getParameter("textfield"); 
    String passlog = request.getParameter("textfield2"); 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String connectionURL = "jdbc:postgresql:rohan";
    Connection connection=null;
    PreparedStatement ps=null;
    ResultSet rs=null;

try {

Class.forName("org.postgresql.Driver");
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
try{
connection = DriverManager.getConnection(connectionURL, "postgres", "postgres");
String sql = "select * from pass where username = ?";
  ps = connection.prepareStatement(sql);
ps.setString(1,userlog);
 rs =  ps.executeQuery();
String dbuser=null;
String dbpass=null; 
while (rs.next()){

dbuser = rs.getString(1);
out.println(dbuser); 
dbpass = rs.getString(2);
out.println(dbpass);
        }
if(dbuser.equals(userlog) && dbpass.equals(passlog))
{
response.sendRedirect("http://localhost:8080/LoginAuthentication/servlets/xx.jsp");

}else
response.sendRedirect("http://localhost:8080/LoginAuthentication/servlets/log2.jsp");

 }catch(Exception e){
    out.println(e);
    out.println("Invalid");         
  }
finally{
try{
if(rs!=null)        
rs.close(); 
if(ps!=null)
ps.close(); 
if(connection!=null)        
connection.close();
}catch(SQLException se){
se.printStackTrace();
}
}
/* if(userName.equals(request.getParameter("user")) 
             && passwrd.equals(request.getParameter("pass"))){
        out.println("WELCOME "+userName);
      }
      else{
        out.println("Please enter correct username and password");
        out.println("<a href='/LoginAuthentication/servlets/log.jsp'><br>Login again</a>");
session.setAttribute("UserName", request.getParameter("UserName"));
out.println("Welcome " + session.getAttribute( "UserName" ));
if (session.getAttribute("UserName").equals(""))
{
out.println("&lt;a href="login.jsp"&gt;&lt;b&gt;Login &lt;/b&gt;&lt;/a&gt;");
}
else{
out.println("&lt;a href="logout.jsp"&gt;&lt;b&gt;Logout&lt;/b&gt;&lt;/a&gt;");
}*/
  }

 }
View Answers

January 5, 2011 at 10:53 AM

Hi Friend,

Try the following code:

1)login.jsp:

<html>
<script>
function validate(){
var username=document.form.user.value;
var password=document.form.pass.value;
if(username==""){
  alert("Enter Username!");
  return false;
}
if(password==""){
  alert("Enter Password!");
  return false;
}
return true;
}
</script>
<form name="form" method="post" action="../Login1" onsubmit="javascript:return validate();">
<table>
<tr><td>Username:</td><td><input type="text" name="user"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</html>

2)Login1.java:

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login1 extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String user=request.getParameter("user");
        String pass=request.getParameter("pass") ;
        Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
         Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from login where username='"+user+"' and password='"+pass+"'");
          int count=0;
          while(rs.next())
          {

                   count++;
          }

                    if(count>0)
          {
            out.println("welcome "+user);
          }
          else
          {
                       response.sendRedirect("./jsp/login.jsp");
          }
    }catch (Exception e) {
    e.printStackTrace();
    }
}
}

Thanks


January 5, 2011 at 10:53 AM

Hi Friend,

Try the following code:

1)login.jsp:

<html>
<script>
function validate(){
var username=document.form.user.value;
var password=document.form.pass.value;
if(username==""){
  alert("Enter Username!");
  return false;
}
if(password==""){
  alert("Enter Password!");
  return false;
}
return true;
}
</script>
<form name="form" method="post" action="../Login1" onsubmit="javascript:return validate();">
<table>
<tr><td>Username:</td><td><input type="text" name="user"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</html>

2)Login1.java:

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login1 extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try{
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String user=request.getParameter("user");
        String pass=request.getParameter("pass") ;
        Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
         Statement st=con.createStatement();
           ResultSet rs=st.executeQuery("select * from login where username='"+user+"' and password='"+pass+"'");
          int count=0;
          while(rs.next())
          {

                   count++;
          }

                    if(count>0)
          {
            out.println("welcome "+user);
          }
          else
          {
                       response.sendRedirect("./jsp/login.jsp");
          }
    }catch (Exception e) {
    e.printStackTrace();
    }
}
}

Thanks









Related Tutorials/Questions & Answers:
user validation
user validation  i hv just started with my lessons in jsp n also doin...(); } } /* if(userName.equals(request.getParameter("user")) &amp;&...;tr><td>Username:</td><td><input type="text" name="user">
Java User Validation
Java User Validation  Dear Deepak thanks for your help with my previous problem. I am looking to write a program that allows a user of a web application to create new user account. what steps do i need to take for adding the new
Advertisements
validation.....
validation.....  hi.......... thanks for ur reply for validation code. but i want a very simple code in java swings where user is allowed to enter only numerical values in textbox , if he enters string values then it should
validation
validation  validation
validation
validation  if user select yes radio button then user should upload file.if user not upload should send error(i created folder when user upload file... Validation method valid the in put. otherwise call the javascript onsubmit to check
validation
validation  we are doing payroll system project in java.So pls provide the complete validation code for employee master form
validation
;td>User Name :</td> <td><form:input path="name" />...:forEach items="${userList}" var="user" varStatus="status"> <tr... interface UserDAO { public void saveUser(User user) ; public List<User>
validation
validation  when user enter course to follow,should have pre requirements. This is my code if(document.application1.courseCode1.value ==1) { frmvalidator.addValidation("subject1","shouldselchk=biology","Should
Validation
); JLabel label=new JLabel("JTable validation Example",JLabel.CENTER); JPanel panel=new JPanel(); panel.add(scroll); JFrame frame=new JFrame("JTable validation
Validation
; <b>User ID</b> :<input type="text" name="userid">...; <li> <b>User Name</b> :<input
Validation
; <b>User ID</b> :<input type="text" name="userid">...; <li> <b>User Name</b> :<input
validation
validation  please help me to check validation for <form> <table class="form"> <tr> <td class="col1"> <label>Sno:</label> </td> <td
Struts 2 Validation (Int Validator)
Struts 2 Validation (Int Validator)       Struts 2 Framework provides in-built validation functions to validate user... inputs are stored. Struts 2 validation framework validates user input against
Validation of datepicker
Validation of datepicker  I have a datepicker in my JSp...the seleted dates are put in a text box. I want the alert the user from selecting future dates in the startDate and enddate textbox.So that the user will be alerted wen
iPhone Text Field Validation
iPhone Text Field Validation In any user based application "... data from user. In this tutorial we are going to limiting the text field input...;. We have also take a Text field on the view to take the input from user
Excel User Define Error Message
Excel User Define Error Message In this section, you will learn , while cell value validation,  how to show user defined error message using Apache POI... dataValidation = new HSSFDataValidation(addressList, dvConstraint); // USER DEFINE
validation files
validation files  If I place validation files in the folder where the action classes are present,will there any error arise
javascript validation
javascript validation  validation of comparing dropdownlist and textbox in javascript
Validation.... - JSP-Servlet
Validation....  in registration page. if i entered an Logine name , which all ready in the data base. how i can get the appropiate msg like "User all ready in the data base" in my data base User ID is the primary key and Login
login form validation - JSP-Servlet
login form validation  hi, how to validate the login form that contains user name and password using post method . the validation should not allow user to login in the address bar thanks regards, anand
form validation
form validation  how the form validation is done in jsf form using javaScript
Validation - Struts
Validation  what is the best way to use validation in Struts?either "validation.xml" or JavaScript
validation query
validation query  where I should kept properties file inside struts Web application
NSURL Validation
NSURL Validation  How to validate a NSURL string using special character validation
email validation
email validation  during email validation.... after domain name which it means if example [email protected] .... this address allowed by any validation program .... but i want to show invalid email address because domain name com
email validation
email validation  during email validation.... after domain name which it means if example [email protected] .... this address allowed by any validation program .... but i want to show invalid email address because domain name com
Form Validation
Form Validation  Java script validation for checking special characters and white spaces and give an alert.Please help me urgent Thanks in advance
comboBox validation
comboBox validation  dear sir. i want to know . how to validate radio button in struts using xml validation. thanks
Date Validation
Date Validation  Hi, I need Date Validation using java in spring framework. Please Anyone help me... Thanks in advance
HTML Form Validation example
HTML Form Validation example  Can anyone guide me how to validate the user name and password field in HTML using simple or JavaScript Validation. Thanks in advance!   <form method="post" onsubmit="return
validation - Framework
validation  how to validate the action forms in struts? could you please explain how cross validation is done for date?  You go the following url: http://www.roseindia.net/struts/struts-login-form.shtml
date validation
date validation  sir, pls provide date validation code in javascript..we want to include it into our master form..   Please visit the following link: http://www.roseindia.net/mysql/datevalidation.shtml
Struts validation
Struts validation  I want to put validation rules on my project.But after following all the rules I can't find the result. I have extended... validation rules,put the plugins inside strutsconfig.xml, put the html:errors tag
validation - JSP-Servlet
, Please visit the following link to have an example of user validation...validation  hello this is Aman and i try to develop intranet based automated resume builder application can u tell me how can validate user and how
String Validation
String Validation changing password  Hi. I have a HTML coding in that I have to check whether the value given in the 2 password fields are same... password and conform password from the user and change the password. 1)change.jsp <
Validation - Struts
Validation  How can i use validation framework i don't understand am...; Hi friend, Phone validation using javaScript function... return true; } Phone Validation
data validation by maker and checker
data validation by maker and checker  My requirment is like ,an user...-"validate and cancel".If the user clicks on validate button,records of the next... of the previous records has to be updated in the table.If user clicks on cancel button
user in mysql
user in mysql  how to create user in mysql?   Please visit the following link: http://www.roseindia.net/mysql/mysql5/mysql-creating-account.shtml (adsbygoogle = window.adsbygoogle || []).push
simple javascript validation for numbers
simple javascript validation for numbers  simple javascript validation for register number   Here is a html code that accepts number from the user and check whether the entered value is valid. <html> <head>
joptionpane validation
){ int category_user = 0; boolean aa = false; do{ String...()) { category_user = Integer.parseInt(input); } }while (!aa || category_user < 1 || category_user>4); } \ hello!!please
Validation doubt
Validation doubt  hi..... thanks for the other validation code. I have got that and implemented in my code but i have a doubt in that. As we try to put string values its not allowing to do tht it gives us message its right
user registration
user registration  hi frnds...am working on a project in JSP.i want to create a user registration form with username,password,mail id and check box option for community selection.once the details are registered i want to save
Server side validation vs client side validation
Server side validation vs client side validation  Can any one tell me the difference between these two different ways of Validation? Also features of Server side validation vs client side validation.   The client side
User Module
User Module The user first need to make registration on the website for appearing in the online examination. After the making successful registration he.... User does the following task Login to the application ADS_TO_REPLACE_1
Form validation
Form validation  Hi Everyone Can someone assist me with a complete code to validate a form. e.g where the user must insert an ID number it should check if the user entered the correct data and within a valid range. This must
Struts2 validation Procedure
Struts2 validation Procedure  In struts2 Which one is best XML Validation or Programatic validation? and which one is used in real world application
Struts2 validation Procedure
Struts2 validation Procedure  In struts2 Which one is best XML Validation or Programatic validation? and which one is used in real world application
Struts2 validation Procedure
Struts2 validation Procedure  In struts2 Which one is best XML Validation or Programatic validation? and which one is used in real world application
validation
Validation

Ads