Thursday, October 13, 2011

Username and Password Validation in JSP using Postgresql

Index.jsp


<h2><font color="#0000FF"><b>Validation&nbsp;</b></font></h2>
<form name="frm" action="Validation" method="Post" >
Name:<input type="text" name="username" value=""/><br>
<b>
Password:</b><input type="password" name="password" value=""/>
<input type="submit" value="Check" />
</form>


Web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<display-name>Welcome to Tomcat</display-name>
<description>Welcome to Tomcat</description>

<servlet>
<servlet-name>Validation</servlet-name>
<servlet-class>User.Validation</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Validation</servlet-name>
<url-pattern>/Validation</url-pattern>
</servlet-mapping>

</web-app>

User.Validation.java


package User;

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

public class Validation extends HttpServlet{

private static final long serialVersionUID = 1L;
private ServletConfig config;

public void init(ServletConfig config)
 throws ServletException{
this.config=config;
  }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{

PrintWriter out = response.getWriter();
String connectionURL = "jdbc:postgresql://localhost/test";
Connection connection=null;
ResultSet rs;
String userName = null;
String passwrd  = null;
response.setContentType("text/html");
String jspun = request.getParameter("user");
String jsppd = request.getParameter("pass");
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(connectionURL, "postgres", "postgres");
String sql = "select user_nm, passwd from user_pass where user_nm='"+jspun+"' and passwd='"+jsppd+"'";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
userName = rs.getString("user_nm");
passwrd  = rs.getString("passwd");
}
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
}

if(userName.equals(jspun) && passwrd.equals(jsppd)){
out.println("User is Valid");
}
else{
out.println("You are not a Valid User");
}
}
}


Sql

create database test;

create table user_pass (
user_nm character varying(30) NOT NULL,
  passwd character varying(128)
);


No comments:

Post a Comment