Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JSP-Servlet user validation
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


akshaya ramkumar
user validation
2 Answer(s)      3 years and 11 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("<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;");
}*/
  }

 }

Advertisement
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  validation
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
validation  we are doing payroll system project in java.So pls provide the complete validation code for employee master form
Validation
); JLabel label=new JLabel("JTable validation Example",JLabel.CENTER); JPanel panel=new JPanel(); panel.add(scroll); JFrame frame=new JFrame("JTable validation
validation
validation  please help me to check validation for <form> <table class="form"> <tr> <td class="col1"> <label>Sno:</label> </td> <td
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
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
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
NSURL Validation
NSURL Validation  How to validate a NSURL string using special character validation
form validation
form validation  how the form validation is done in jsf form using javaScript
validation query
validation query  where I should kept properties file inside struts Web application
Validation - Struts
Validation  what is the best way to use validation in Struts?either "validation.xml" or JavaScript
email validation
email validation  during email validation.... after domain name which it means if example example@gmail.co .... 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 example@gmail.co .... this address allowed by any validation program .... but i want to show invalid email address because domain name com
Date Validation
Date Validation  Hi, I need Date Validation using java in spring framework. Please Anyone help me... Thanks in advance
comboBox validation
comboBox validation  dear sir. i want to know . how to validate radio button in struts using xml validation. thanks
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
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
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
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 - Struts
Validation  How can i use validation framework i don't understand am...; Hi friend, Phone validation using javaScript function... return true; } Phone Validation
Advertisements
 

 

 

DMCA.com