404 not found error for servlet - java

I have embedded department.jsp in create.jsp. My department.jsp has a table in which i submit data, the action is on a servlet but on submitting it is giving a 404 error for servlet.
create.jsp in body-
<header>
<img style="text-align:left" src="images.png" width="200" height="100" alt="NSIC-logo1"/>
<h1>File Tracking System</h1>
<form style="float:right;" action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<br>
</header>
Create
<iframe style="height:530px;width:1340px " src="department.jsp" name="frame2">
<p>Your browser does not support iframes.</p>
</iframe>
department.jsp in body-
<form action="DepartmentServlet" method="post">
<center>
<table id="depart">
<thead>
<tr>
<th colspan="2">Create Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
</center>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
DepartmentServlet.java
public class DepartmentServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getRequestDispatcher("link.html").include(request, response);
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String admin=(String)session.getAttribute("admin");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=dcheck.value(department);
boolean checkc=checkchar.value(company);
boolean checkp=checkchar.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("insert.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsert.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}

Related

How to preserve values of fields on jsp page when jsp is calling servlet and redirecting back to same jsp

I have a one welcome.jsp page where I am collecting few information and with the help of HTML FORM sending this request and response object to servlet to insert data into DB, so after this operation I want to go back to the same Welcome.jsp, but when I tried to use the
RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);
I lost all the populated values on the same Welcome.jsp,
So please suggest is there a way where I can send the existing request and response object with new request and response to the servlet and will send back old request and response object from servlet to JSP.
So below is code from "Welcome.jsp"
<!DOCTYPE html>
<%#page import="***********"%>
<%#page import="java.io.Console"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.util.ArrayList"%>
<html>
<head>
<title>Treatment Dashboard</title>
<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- <script type="text/javascript">
function noBack()
{
window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function(evt) { if (evt.persisted) noBack() }
window.onunload = function() { void (0) }
</script> -->
</head>
<body>
<%
HttpSession sessions = request.getSession();
String lanId = (String)sessions.getAttribute("lanid");
System.out.println("session Lanid:- " + lanId);
%>
<!-- Codrops top bar -->
<div class="codrops-top">
<a>
<strong> VALUES </strong>
</a>
<span class="right">
<strong> VALUE </strong>
</span>
<div class="menu-area">
<div id="dl-menu" class="dl-menuwrapper">
<button class="dl-trigger">Open Menu</button>
<ul class="dl-menu">
<li>Profile</li>
<li>Weekends Shift</li>
<li>Comp Off</li>
<li>Log Off</li>
</ul>
</div>
</div>
<!-- intro area -->
<div id="intro">
<div class="intro-text">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<div class="brand">
<%
String fname = (String) request.getAttribute("fname");
String lname = (String) request.getAttribute("lname");
String emailid = (String) request.getAttribute("emailid");
String ext = (String) request.getAttribute("ext");
String rmlanid = (String) request.getAttribute("rmlanid");
String role = (String) request.getAttribute("role");
String ipadd = (String) request.getAttribute("ipadd");
String wcounts = (String) request.getAttribute("weekendsCount");
String acocounts = (String) request.getAttribute("appliedCompOff");
String rcocounts = (String) request.getAttribute("remainingCompOff");
String pacocounts = (String) request.getAttribute("appliedCompOffPendingApprovalcount");
%>
<table style="width:100%" >
<tr>
<td>
<label for="userName" class="uname" data-icon="u"> Name :- </label>
</td>
<td>
<label for="userName" class="uname" data-icon="u"><%=fname%> <%=lname%></label>
</td>
</tr>
<tr>
<td>
<label for="userEmail" class="email" data-icon="u"> Email :- </label>
</td>
<td>
<label for="userEmail" class="email" data-icon="u"><%=emailid%> </label>
</td>
</tr>
<tr>
<td>
<label for="userExt" class="ext" data-icon="u"> EXT :- </label>
</td>
<td>
<label for="userExt" class="ext" data-icon="u"><%=ext%> </label>
</td>
</tr>
<tr>
<td>
<label for="userRmlanid" class="rmlanid" data-icon="u"> RM Lan-Id :- </label>
</td>
<td>
<label for="userRmlanid" class="rmlanid" data-icon="u"><%=rmlanid%> </label>
</td>
</tr>
<tr>
<td>
<label for="userIpadd" class="ipadd" data-icon="u"> TechM Machine IP :- </label>
</td>
<td>
<label for="userIpadd" class="ipadd" data-icon="u"><%=ipadd%> </label>
</td>
</tr>
<tr>
<td>
<label for="userWeekendsNumber" class="weekends" data-icon="WND"> Worked ON Weekends :- </label>
</td>
<td>
<label for="userWeekendsNumber" class="weekends" data-icon="WND"> <%=wcounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffApplied" class="compoff" data-icon="u"> Applied Comp Off :- </label>
</td>
<td>
<label for="userCompOffApplied" class="compoff" data-icon="u"> <%=acocounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffAvailed" class="compoff" data-icon="u"> Remaining Comp Off :- </label>
</td>
<td>
<label for="userCompOffAvailed" class="compoff" data-icon="u"> <%=rcocounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffPendingApproval" class="compoff" data-icon="u"> CompOff Pending For Approval :- </label>
</td>
<td>
<label for="userCompOffPendingApproval" class="compoff" data-icon="u"> <%=pacocounts%> </label>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Update"/>
<!-- <input type="submit" value="Cancel"/> -->
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Weekend Shift -->
<section id="WeekendsShift" class="home-section bg-white">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<form method = "post" action="AddWeekendsShiftDetails" autocomplete="on" >
<div class="brand">
<table style="width:100%" >
<tr>
<td>
<p> <br><br><br>
<label for="weekendDetails" class=""> Worked On Weekend :- </label>
</p>
</td>
<td>
<p><br><br><br>
<input type="text" id= "datepicker1" placeholder="Weekend Date" name="pickedDate"/>
<script>
var datepicker = $("#datepicker1").datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true
}).val();
</script>
</p>
</td>
</tr>
<tr>
<td>
<p> <br>
<label for="processname" class="uname" data-icon="PN" > Process Name :- </label>
</p>
</td>
<td>
<p> <br>
<input id="processname" name="processname" required="required" type="text" placeholder="ex:-BAC"/>
</p>
</td>
</tr>
<tr>
<td> </td>
<td>
<p> <br>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</p>
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Comp Off -->
<section id="compoff" class="home-section bg-white">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<form method = "post" action="AddCompOffDetails" autocomplete="on" >
<div class="brand">
<%
final String USER_WEEKENDS_COMPOFF_DETAILS_QRY = "SELECT WEEKEND_DATE FROM tbl_weekend_rota WHERE (LANID= ? and IS_COMPOFF_CONSUMED = 'N' and IS_APPROVED != 'P')";
Connection con = null;
con = DBConnection.createConnection();
PreparedStatement ps = null;
ps =con.prepareStatement(USER_WEEKENDS_COMPOFF_DETAILS_QRY);
ps.setString(1, lanId);
ResultSet rs = ps.executeQuery();
%>
<table style="width:100%" >
<tr>
<td>
<p> <br><br><br>
<label for="userName" class=""> Apply CompOff :- </label>
</p>
</td>
<td>
<p><br><br><br>
<select name="compOffDate">
<option>-- Available CompOffs --</option>
<% while(rs.next()) { %>
<option><%=rs.getString(1)%></option>
<% } %>
<% con.close();%>
</select>
<p>
</td>
</tr>
<tr>
<td> </td>
<td>
<p><br>
<input type="submit" value="Apply"/>
<input type="reset" value="Reset"/>
<br><br>
</p>
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
But when I clicked on Submit button it calls the AddWeekendsShiftDetails servlet,
So in this case this form will send its own request and response object right ?
So from the AddWeekendsShiftDetails servlet I'm inserting values to the Mysql DB
Below is the code from AddWeekendsShiftDetails servlet:-
package com.taskManagment.login;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Date;
//import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/AddWeekendsShiftDetails")
public class AddWeekendsShiftDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddWeekendsShiftDetails() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sDate = request.getParameter("pickedDate");
String processName = request.getParameter("processname");
try {
Date sqlDate=Date.valueOf(sDate);
Connection con = null;
con = DBConnection.createConnection();
String lanId = SessionDetails.getDetailsFromSession(request, "lanid");
System.out.println("session Lanid from Weekend Servlet:- " + lanId);
insertWeekendShiftDetails(con, lanId, processName, sqlDate);
con.close();
/*RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void insertWeekendShiftDetails(Connection con, String lanId, String processname, Date date ) {
PreparedStatement ps = null;
try {
String insertWeekendRotaDetails = "MY INSERT QUERY";
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
ps = con.prepareStatement(insertWeekendRotaDetails);
ps.setString(1, null); ps.setString(2, lanId);
ps.setDate(3, (java.sql.Date) date); ps.setString(4, processname);
ps.setString(5, "Y"); ps.setString(6, "N");
ps.setString(7, null); ps.setDate(8, null);
ps.setString(9, "N"); ps.setDate(10, sqlDate);
ps.setDate(11, null);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now from the doPost when I want to go back to the "Welcome.jsp" with the code like
RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);
so it will send back the request and response object of the form which was called from the section
and because of which the other values on the fields are getting null,
So I want a way with which I can hold the old values on Welcome.jsp page.
before sending it back you need to set the attributes you want to the request. You can do that using request.setAttribute("attribute_name","attribute_value"); and the you can retrieve it by using request.getAttribute in the next page. For example
request.setAttribute("errorMsg", "Invalid data . Please correct the input data");
requestDispatcher = request.getRequestDispatcher("error.jsp");
requestDispatcher.forward(request, response);
And then in error.jsp you can use:
<%=request.getAttribute("errorMsg") %>

Hebrew characters looks garbled (Java+Objectify+JSP)

I have a HTML form
<form method="post" accept-charset="UTF-8"
action="<%=blobstoreService.createUploadUrl("/nonameyet")%>"
enctype="multipart/form-data">
<tr>
<td><input type="text" name=name /></td>
<td><input type="text" name=price /></td>
<td><input type="text" name=quantity /></td>
<td><input type="file" name="image" /></td>
<td><input type="submit" value="add" /></td>
</tr>
after sending the data I receive it here:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("image");
if (blobKeys.get(0) == null) {
resp.sendRedirect("/");
}
req.setCharacterEncoding("UTF-8");
BlobKey blobKey = blobKeys.get(0);
Product product = new Product();
String name = req.getParameter("name");
String priceAsString = req.getParameter("price");
int price = Integer.parseInt(priceAsString);
String quantityAsString = req.getParameter("quantity");
int quantity = Integer.parseInt(quantityAsString);
product.setName(name);
product.setPrice(price);
product.setQuantity(quantity);
String url = ImagesServiceFactory.getImagesService().getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
product.setImage(url);
ofy().save().entities(product).now();
resp.sendRedirect("/index.jsp");
}
and now the JSP is:
<%
List<Product> list = ofy().load().type(Product.class).limit(20)
.list();
for (Product product : list) {
%>
<tr>
<td><%=product.getName()%></td>
<td><%=product.getPrice()%></td>
<td><%=product.getQuantity()%></td>
<td><img alt="<%=product.getName()%>"
src="<%=product.getImage()%>" width="100" height="100" /></td>
<td>delete
</tr>
<%
}
%>
But when I view the page in Chrome it looks like this:
After examining the data in http://localhost:8888/_ah/admin/datastore, I can see the word in Hebrew is correct:
So I get to the conclusion that somewhere on the way from the datastore to the jsp the text gets garbled. Can someone help?

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

image not retrieving when submitting form using servlet

I have a image in my sql and I want to retrieve it in web page
so i have developed a servlet. now when I hit the submit button then it calls to the servlet but image is not displayed but in the browser if if I am writing localhost:8080/y/testimageServlet then the image is displayed.
imagetestServlet.java
import java.sql.*;
import DB.DataBaseConnection;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class imagetestServlet
*/
#WebServlet("/imagetestServlet")
public class imagetestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public imagetestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataBaseConnection db= new DataBaseConnection();
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con=db.connet();
stmt = con.createStatement();
rs = stmt.executeQuery("select img from one where id = '4'");
if (rs.next()) {
image = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<font color='red'>image not found for given id</font>");
return;
}
response.setContentType("image/gif");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Unable To Display image</title></head>");
out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
"</font></h4></body></html>");
return;
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
login
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
<img src="header.png"><br><br><br><br><br>
<table >
<tr>
<td>
<table class="table">
<tr>
<td>
<table class="table">
<tr>
<td>
<div class="content"><div class="signin-header"><h3>Welcome to DiaEmr</h3></div></div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div class="signin-box">
<p class="one">
Welcome to all at the <b>"Workshop on Ileal Interposition".</b><br>
<b>Brazil</b> to inaugurate & launch this very important Data Registry<br>
Key features of the solution-<br>
</div>
</div>
</td>
</tr>
</table>
</td>
<td>image</td>
<td>
<table class="table" >
<tr>
<td>
<div class="content">
<div class="signin-header">
<h3>Portal Login</h3>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div align="center" class="signin-box">
<table class="table">
<tr>
<td><b>User ID</b></td>
<td><input name="uid" type="text" /></td>
</tr>
<tr >
<td><b>Password</b></td>
<td><input name="cpass" type="password" /></td>
</tr>
<tr >
<td><input type="submit"
class="button button-submit" value="Submit" /></td>
<td><input type="reset" class="button button-submit"
value="Reset" /></td>
<tr>New UserRegister</tr><br>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="footer-bar">
<img align="left" src="footer.png">
</div>
</form>
your form sends a post request,
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
but you only define a doGet method in your servlet. This is resulting in your page working if you navigate in a browser (GET) but not when submitting your form (POST).
You will either need to change your form to use get or implement your code in the doPost method

Sample Ajax program for JSP+Servlets+Hibernate

In my app im using JSP as view,servlet as controller,hibernate as model..
in that app jsp pages im have to fill form while creating new user with fields like username and all.
now i want to use AJAX code to check if username name with entered name in form is already there in the database or not...
can any1 guide me how to write coding for this as well as the control flow..
i have googled but didnt got any idea how to do this requirement..
thanks in advance
Here you are having two option for user name validation.
1> Client(User Interface) Side validation
2> Server side validation
For option 1>, you need to write ajax call which will make a request to server and respond a result which will inform if a use is valid or not.
For client side, I will suggest you to use java script OR jQuery.
Here is the sample jQuery ajax code.
$.ajax({
url: "validateUser.html?username=username",
success:function(data){
//YOUR CODE FOR FUTHRE ACTION FOR VALID/INVALID ACTION
}
});
You can refer jQuery ajax here.
For option 2>, validation on server side...
You can validate the user name on submit of the form.
you can retrieve the value by request.getParamter("userName"); and check into the DB if it already there OR not.
Regards,
Gunjan.
In Jsp
<script type="text/javascript">
function VerifyUsername()
{
//alert("In Verify Method");
var name=document.getElementById("username").value;
//alert(name);
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
//alert("http");
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
alert("http active");
}
xmlhttp.onreadystatechange=function()
{
//alert("in Function()");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
try
{
//alert("In Try");
document.getElementById("errorpass").innerHTML=xmlhttp.responseText;
/*var response = xmlhttp.responseText;
alert(response);
if(response.toString()=='notmatch')
{
alert("Ok");
document.getElementById("errorpass").innerHTML ="OK";
}
if(response =='match')
{
alert("Not Ok");
document.getElementById("errorpass").innerHTML ="Take Other Name.";
}*/
}
catch(ex)
{
alert("Exception in function "+ex);
}
}
}
//xmlhttp.open("POST","servlet/UsernamePresence_Serv?UserId"+name,true);
xmlhttp.open("POST","servlet/UsernamePresence_Serv?"+name,true);
var params = "UserId="+name;
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
in Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
{
Session session=Hibernate_Class.sessionObject();
String userID=null;
userID = request.getParameter("UserId");
login_model loginModel_Obj=new login_model();
loginModel_Obj._Name=userID;
System.out.print("at "+userID);
boolean username_bool=Hibernate_Class.usernamePresence(loginModel_Obj, session);
if (username_bool)
{
out.println("Username Present In Database");
}
else
{
out.println("Username Not Present In Database");
}
}
finally{}
out.close();
}
In Below code just replace JDBC code with your Hibernate Code .
JSP
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<title> - User Login</title>
<style type="text/css">
#marqueecontainer{
position: relative;
width: 150px; /*marquee width */
height: 163px; /*marquee height */
/*background-color: white;*/
overflow: hidden;
/*border: 3px solid orange;
padding: 2px;
padding-left: 4px;*/
}
</style>
</head>
<script language="javascript">
var mWindow="windows";
var objLogRequest;
function chekUserId()
{
try
{
if(document.getElementById("userID").value=="")
{
alert(" You have not entered Username. ");
return 0;
}
if(document.getElementById("userPass").value=="")
{
alert("You have not entered Password.");
return 0;
}
var userId = document.getElementById("userID").value;
var userPass = document.getElementById("userPass").value;
//alert("userId:->"+userId);
//alert("userPass:->"+userPass);
serUrl ='/servlet/UserLogin?userID='+userId
+'&userPass='+userPass+'&randomNum='+Math.random()*Math.random();
//alert("serUrl:->"+serUrl);
if(window.ActiveXObject)
{
objLogRequest = new ActiveXObject('Microsoft.XMLHTTP');
//alert("Windos Browser");
}
else
{
objLogRequest = new XMLHttpRequest();
mWindow = "nonWindows";
}
if(objLogRequest)
{
//alert("objAddRequest 1");
objLogRequest.onreadystatechange = sendLogInfo;
//alert("objAddRequest 2");
objLogRequest.open('Get',serUrl);
//alert("objAddRequest 3");
if(mWindow=='nonWindows')
{
objLogRequest.send('');
}
else
{
//alert("before send ");
objLogRequest.send();
//alert("after send ");
}
}
}// end try
catch(e)
{
alert("Exception in chekUserId function "+e);
}
}
function sendLogInfo()
{
try
{
//alert('object state :-> '+objLogRequest.readyState)
if(objLogRequest.readyState==4)
{
if(objLogRequest.status==200)
{
var response = objLogRequest.responseText;
//alert('response :-> '+response)
if(response =='notmatch')
{
document.getElementById("errorpass").innerHTML ="Username and
password do not match.(You provided
"+document.getElementById("userID").value+" )";
document.getElementById("userPass").value="";
}
if(response =='match')
{
alert('user valid');
}
}
}
}
catch(ex)
{
alert("Exception in sendInfo function "+ex);
}
}
</script>
<body marginheight="0" marginwidth='0' topmargin='0'
bottommargin='0'leftmargin='0' class="body">
<table width="751" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td bgcolor="#000099"><table width="751" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td bgcolor="#FFFFFF"><table width="751" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td>
</td>
</tr>
<tr>
<td height="25" align="left" valign="middle"
bgcolor="#C7C7C7" class="plan-a-trip"><span class="welcometext"></
span></td>
</tr>
<tr>
<td height="10" align="left" valign="top"></td>
</tr>
<tr>
<td><table width="751" border="0" cellspacing="0"
cellpadding="0">
<tr>
<td width="10" align="left" valign="middle"> </
td>
<td width="150" align="left" valign="top">
</td>
<td width="10" align="left" valign="top"></td>
<td width="571" height="270" align="left"
valign="top" bgcolor="#999999"><table width="571" border="0"
cellspacing="1" cellpadding="0">
<tr>
<td width="579" height="476" align="left"
valign="top" bgcolor="#FFFFFF">
<table width="571" height="391" border="0" cellpadding="0"
cellspacing="0">
<form name='loginform' method='get' action='/servlet/UserLogin'
onSubmit="return submit(document.loginform);" >
<tr>
<td width="25" rowspan="11" align="left"
valign="top"> </td>
<td width="459" height="20" align="left"
valign="top"> </td>
<td width="20" rowspan="11" align="left"
valign="top"> </td>
</tr>
<tr>
<td height="16" align="left"
valign="middle"><img src="/image/PlanATrip/UserLogin/member_login.jpg"
width="120" height="13" /></td>
</tr>
<tr>
<td height="10" align="left"
valign="middle"> </td>
</tr>
<tr>
<td height="5" align="left" valign="top"></td>
</tr>
<tr>
<td height="100" align="left"
valign="top"><table width="479" height="115" border="0"
cellpadding="0" cellspacing="0">
<tr>
<td width="85" align="left"
valign="middle" class="text">Username</td>
<td width="10" rowspan="6" align="left"
valign="top"> </td>
<td width="376">
<input id="userID" name="userID"
type="text" class="inputtext" maxLength="25"/> </td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"></
td>
</tr>
<tr>
<td align="left" valign="middle"
class="text">Passward</td>
<td><input id="userPass" name="userPass"
type="password" maxlength="15" class="inputtext" /></td>
</tr>
<tr>
<td height="5" align="left"
valign="middle"></td>
<td height="5" align="left" valign="top"
class="wrongpass" id="errorpass"> </td>
</tr>
<tr>
<td align="left" valign="middle"> </
td>
<td><input name="loginBut" type="button"
id="loginBut" class="searchButton" value="Login"
onclick="chekUserId()"/></td>
</tr>
<tr>
<td align="left" valign="middle"> </
td>
<td ><a href="/servlets/Registration.html"
class="fyp">New User Sign Up</a></td>
</tr>
</table></td>
</tr>
<tr>
<td height="10" align="left"
valign="top"> </td>
</tr>
<tr>
</tr>
</form>
</table></td>
</tr>
</table></td>
<td width="10" align="left" valign="middle"> </
td>
</tr>
</table></td>
</tr>
<tr>
<td></td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>
Servlet Code
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UserLogin extends HttpServlet
{
public String DBUrl = "jdbc:mysql://127.0.0.1:3306/
databasename";
public void init ()
{
//getCon();
System.out.println("UserLogin called");
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
ResultSet rs=null;
Connection con = null;
Statement stm=null;
//Vector userId;
String userID=null,userPass=null,currentDate=null;
userID = req.getParameter("userID");
userPass = req.getParameter("userPass");
HttpSession session = req.getSession(true);
try
{
con = pool.getCon();
stm = con.createStatement();
//System.out.println("connect");
////chek user ID Start ***//////
String querySelctId = "select count(*)user from userinfo where
UserId='"+userID+"'AND UserPassword='"+userPass+"';";
rs = stm.executeQuery(querySelctId);
//System.out.println("4");
int count = 0
try{
count = rs.getString(1);
}catch(SQLException sqlEx){
System.out.println("sqlEx");
}catch(Exception ex){
System.out.println("Ex");
}
if(count==1)
{
System.out.println(userID+":-> Login");
out.print("match");
}
else
{
out.print("notmatch");
}
}
catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
//res.sendRedirect("/servlets/RegistrationFail.html");
}
catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
res.sendRedirect("/servlets/ErrorPage.htm");
}
finally
{
try
{
if(con != null)
{
System.out.print("UserLogin Servlet release:-> ");
pool.releaseConnection(con);
rs.close();
stm.close();
out.flush();
out.close();
}
}
catch(Exception Ex)
{
System.out.println(" Exception in release the connection ");
System.out.println(Ex);
}
}
}
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
doPost(req,res);
}
public Connection getCon()
{
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DBUrl,"root","");
databaseMetaData = con.getMetaData();
stm = con.createStatement();
}catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}catch (SQLException sqle)
{
System.out.println("SQLException");
System.out.println(sqle);
}catch (Exception ex)
{
System.out.println("Exception");
System.out.println(ex);
}
return con;
}
}

Categories

Resources