Home Answers Viewqa JSP-Servlet user validation

 
 


akshaya ramkumar
user validation
2 Answer(s)      2 years and 5 months ago
Posted in : JSP-Servlet

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("
Login again
");

session.setAttribute("UserName", request.getParameter("UserName"));
out.println("Welcome " + session.getAttribute( "UserName" ));
if (session.getAttribute("UserName").equals(""))
{
out.println("<a href="login.jsp"><b>Login </b></a>");
}
else{
out.println("<a href="logout.jsp"><b>Logout</b></a>");
}*/
  }

}

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 Pages:
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...(request.getParameter("user")) && passwrd.equals(request.getParameter("pass
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  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
;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
; <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
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
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
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
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 <
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
Time validation
. If the user enters the time in wrong format, it displays the error message. <
dob validation
dob validation  hi i am entering date, month and year in corresponding three drop down list. how to validate the date.....?   // validate that the user made a selection other than default function isChosen(select
String Validation
password from the user and change the password. 1)change.jsp <html> <
String Validation
password from the user and change the password. 1)change.jsp <html> <
Password validation
, New password and conform password from the user and change the password. 1
Password validation
, New password and conform password from the user and change the password. 1
Password validation
, New password and conform password from the user and change the password. 1
Password validation
, New password and conform password from the user and change the password. 1
Password validation
the user and change the password. 1)change.jsp <html> <script>
String Validation
and conform password from the user and change the password. 1)change.jsp <html>
validation
validation  validation
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
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
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>
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
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
Struts2 Validation Problem - Struts
Struts2 Validation Problem  Hi, How to validate field...("Roseindia"))){ addActionMessage("Valid User!"); return SUCCESS...) { addActionMessage("Valid User!"); return SUCCESS; } For more
validation problem in struts - Struts
validation problem in struts  hi friends... m working on one project using struts framework. so i made a user login form for user authentication. nd i write d code for sql connection and user athunetication in d action class
validation
validation  we are doing payroll system project in java.So pls provide the complete validation code for employee master form
jsp-oracle validation - JDBC
jsp-oracle validation  Dear friends, my validation not takes place... the solution. Thanks in advance! Krishna login.html User Name..., Implement validation code. Insert into database function
Struts 2 Validation (Int Validator)
Struts 2 Validation (Int Validator)       Struts 2 Framework provides in-built validation functions to validate user... are stored. Struts 2 validation framework validates user input against the defined rules
Login validation doubt
Login validation doubt  Hi, 1)login.jsp: <%@page import="java.sql.*"%> Username: Password: 2)check.jsp: <% String user=request.getParameter("user"); String pass=request.getParameter("pass"); if(user.equals
Javascript validation - Java Beginners
for the validation of Zip code,the problem is, when user enters the valid zip code... want that if user enters the valid zip code in first attempt then text box's background color should't change,if user enters invalid sip code then then text box's
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
validation - Java Beginners
JavaScript validation file 'validation.js': function emailcheck(str...: Enter First Name: Enter Last Name: Enter User Name: Enter Password
Javascript validation - Java Beginners
having a input type="file" text box in which the user can browse the required file.. If that file is a gif file, I have to allow user for further procession else not.. How to check whether that file name selected by the user is a gif
IP Address validation
...(ie) the user shld enter the IP address in JTxt and when he hit the 'Submit' button the actionlistener shld check its valid or not...like if user have
jQuery email validation
jQuery email validation  Hi, I am using jQuery in my PHP based web application. I have to validate the email address entered by user on the form. I... message to user if email address is not valid. See jQuery to validate Email Address
JavaScript Email Validation
JavaScript Email Validation...; In this section we are going to check email Validation using JavaScript. JavaScript allows to perform a client side validation of email Ids in several forms
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
Validation
); JLabel label=new JLabel("JTable validation Example",JLabel.CENTER); JPanel panel=new JPanel(); panel.add(scroll); JFrame frame=new JFrame("JTable validation
validation - Swing AWT
validate a registration form through swings..fields like user,password,email... JLabel(); label1.setText("User Name:"); text1 = new JTextField(20...)){ JOptionPane.showMessageDialog(null,"Invalid User Name"); } else if((f2==false)||(value2.length
validation
validation  please help me to check validation for <form> <table class="form"> <tr> <td class="col1"> <label>Sno:</label> </td> <td
JSP data base validation
= "jdbc:mysql://localhost:3306/record"; String user = "root"; String password... = DriverManager.getConnection(url, user, password); ps1
validation - Development process
== ""){ alert ( "Please enter user name." ); document.form.uname.focus
validation - JSP-Servlet
(); return false; } This will restrict the user to enter the marks between 1

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.