values are getting inserted in database but they should not - java

LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
response.sendRedirect("create.html");
}
else {
response.sendRedirect("create1.html");
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<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>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
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;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
LogoutServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
With DepartmentServlet, I am inserting values into the database. The problem is that, I am able to open create.html and department.jsp without login and values are also getting inserted into the database even when I have not logged in. I know the problem is with the session not being properly passed(used). How can I solve it? Could someone correct it?

Change the condition if(session != null)
to if(session != null && session.getAttribute("name") != null)

you'll have to implement filter to restrict access for .jsp/.html which would check for active session .if no active session found then it'll redirect request to login page(in you case link.Use below implementation of doFilter method
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("name") == null) {
response.sendRedirect(request.getContextPath() + "/link");
} else {
chain.doFilter(req, res);
}
}

Related

JSP form submit and list population issue

I'm having a couple issues with a simple JSP app. When I go to the Add or Delete pages, I'm able to input data and submit it, the item is either added or deleted to/from the database as it is supposed to be, but instead of returning me to the page, it sends me to a page that says, "Served at: /ToDoList". I can use the back button to return to the page, but it is supposed to simply reload the same jsp page. It worked previously, but I'm not sure what I changed.
Additionally, I'm trying to populate a table with the data from a database on the Show List page (show.jsp), but it gives me a ConcurrentModificationException that I can't figure out. I'm really not sure what I'm doing wrong here. Any help is appreciated. The ListItem object is just an int itemID and string itemDesc. Code follows:
add.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add an item</title>
</head>
<body>
<h1>Add an item</h1>
<form action="AddItem" method="post">
<table>
<tr><td><input type="text" name="desc" value="" size="100"/></td></tr>
<tr><td><input type="submit" value="Submit" name="addSub" /></td></tr>
</table>
</form>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
delete.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
show.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
ItemList.java
package todolist;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.util.LimitedInputStream;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
public class ItemList {
List<ListItem> list = new ArrayList<>();
List<ListItem> tempList = new ArrayList<>();
public static SessionFactory factory;
public ItemList() {
super();
}
public void addItem(String itemStr) {
//list.add(item);
//list.get(list.size() - 1).setItemNumber(list.size());
ListItem item = new ListItem(itemStr);
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
Integer itemID = null;
try {
tx = session.beginTransaction();
itemID = (Integer) session.save(item);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void delItem(int itemNbr) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
ListItem item2 = (ListItem)session.get(ListItem.class, itemNbr);
try {
tx = session.beginTransaction();
session.delete(item2);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<ListItem> getList() {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query<ListItem> queryList = session.createQuery("FROM itemlist");
tempList = queryList.list();
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
list = tempList;
return list;
}
public int size() {
return list.size();
}
}
AddItem.java
package todolist;
import java.io.IOException;
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;
/**
* Servlet implementation class AddItem
*/
#WebServlet("/AddItem")
public class AddItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public AddItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("desc")!=null) {
String desc = request.getParameter("desc");
list.addItem(desc);
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
}
}
DelItem.java
package todolist;
import java.io.IOException;
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;
import org.hibernate.HibernateException;
/**
* Servlet implementation class DelItem
*/
#WebServlet("/DelItem")
public class DelItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public DelItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("itemNbr")!=null && request.getParameter("itemNbr")!="") {
int itemNbr = Integer.parseInt(request.getParameter("itemNbr"));
list.delItem(itemNbr);
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
}
}
ShowList.java
package todolist;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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;
/**
* Servlet implementation class ShowList
*/
#WebServlet("/ShowList")
public class ShowList extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list2 = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public ShowList() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<ListItem> tempList = new ArrayList<>();
tempList = list2.getList();
request.setAttribute("dispList", tempList);
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
}

How can i get my table values from html to servlet?

I need to get my html table values in my servlet
Hi,
Im doing a project during my acadamic courses about sudoku website.
During my project I have encounterd a problem that I can't slove - get my table html values into my servlet.
I have tried doing things like set hidden names and getParameterValues but none of them worked.
this is my html table
<table class="center">
<% int n =9;
for(int s = 0; s<n; s++){
%>
<tr>
<% for(int f=0; f<n; f++)
{
%>
<td><% int z = SF[s][f];
if(z==0) {%>
<input type="text">
<% } else { %>
<%=SF[s][f]%>
<%}%>
</td hidden name="z">
<% } %>
</tr hidden name="z">
<% } %>
</table>
and this is my empty servlet
package View;
import org.omg.CORBA.SystemException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CheckSudokuServlet",urlPatterns = "/CheckSudokuServlet")
public class CheckSudokuServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
//tried - String td[]=request.getParameterValues("z");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
How about using javascript to encode the values into a url
var z=3;
window.location.href = "/CheckSudokuServlet?z="+z;
Then in your servlet you can access as so:
String refBgcId= request.getParameter("refBgcId").toString();

simple login servlet not giving output [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
I developed simple login servlet which runs well in eclipes but i am not getting any output from server side help to fix this
used create statement not prepared statement
help to improve logic
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>welcome to Student Account</title>
</head>
<body>
<font color="red">
<center>
Welcome to Student portal <br> <b>kindly login to your acccount</b></br> <b>Login
form</b>
<form method="post" action="./Account">
<table>
<tr>
<td>Student Login:</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>Student Password:
<td><input type="password" name="spasswd"></td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value="login"> <input
type="reset" value="reset"></td>
</tr>
</table>
</center>
</body>
</html>
StudentAccInfo.java
import java.io.IOException;
import java.io.PrintWriter;
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("/Account")
public class StudentAccInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String sname=request.getParameter("sname");
String spasswd=request.getParameter("spasswd");
String Status=UserService.validate(sname, spasswd);
out.println("<html><body><center>");
out.println("<font color='red' size='7'>");
if(Status.equals("success")){
out.println("Login Success");
}
if(Status.equals("failure")){
out.println("Login failure");
}
out.println("</center></body></html>");
}
}
UserService.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserService {
public static String validate(String sname, String spasswd)
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
String Status="";
try{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:ORCL", "scott", "tiger");
st=con.createStatement();
String sql="";
sql=sql+"select * from std where sname=";
sql=sql+"'"+sname+"'";
sql=sql+" "+"and spasswd=";
sql=sql+"'"+spasswd+"'";
rs=st.executeQuery(sql);
boolean b=rs.next();
if(b==true){
Status="success";
}else{
Status="failure";
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
con.close();
st.close();
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
return Status;
}
}
Note:- I have used create Statement not prepared statement
running well but not getting output
remove ./ from action attribute
<form method="post" action="Account">

unknown Servlet exception throw error of HTTP Status 500

I have tried adding all libraries that are needed for Servlet to run but still I am getting an exception that threw HTTP Status 500 error.
I also have tried all previously asked questions in stack overflow.
LoginServlet.java
package com.testlogin;
import java.io.IOException;
import java.io.PrintWriter;
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("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet" method="post">
<div style="color: red">
User Name
<input type="text" name="username">
<br /> Password
<input type="password" name="password">
<br>
<input type="submit" value="Sign In">
</div>
</form>
</body>
</html>
well, don't complicate your code. I think your code will work fine too and problem should be on your server.
please make sure if you are using servlet version >3.0 and tomcat 7 as it will not run in the previous versions of tomcat
try this..
import java.io.IOException;
import java.io.PrintWriter;
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("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter pw = response.getWriter();
pw.print("Hello");
if (username.equals(password)) {
pw.println("<h1>Hello </h1>" + username);
}
}
}

Insert time and date in MySQL database using jsp,bean class and servlet

I want to insert the date and time in the database table. I got error in the insertdao.java as incompatible types timestamp cannot be convert to time.
I have a dttable in my MySQL database with columnname & data type Logindate DATE,Logintime TIMESTAMP,LogoutTime TIMESTAMP.
In index.jsp we have to insert the value in Logindate,Logintime,LogoutTime
<%#page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Timesheet Page</title>
</head>
<body>
<header>
<h2>WEEKLY TIME SHEET MANAGEMENT V 1.0</h2>
</header>
<form action="insertservlet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<table>
<thead>
<tr>
<th>Date</th>
<th>Time In</th>
<th>Time Out</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="logindate" required="required" /></td>
<td><input type="time" name="logintime" required="required" /></td>
<td><input type="time" name="logouttime" required="required" /></td>
</tr>
</tbody>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>
Logout
</body>
</html>
Bean.java:
package com.eis.bean;
import java.sql.Date;
import java.sql.Timestamp;
public class Bean {
public Bean() {}
private java.sql.Date logindate;
private java.sql.Timestamp logintime;
private java.sql.Timestamp logouttime;
public Date getLogindate() {
return logindate;
}
public void setLogindate(Date logindate) {
this.logindate = logindate;
}
public Timestamp getLogintime() {
return logintime;
}
public void setLogintime(Timestamp logintime) {
this.logintime = logintime;
}
public Timestamp getLogouttime() {
return logouttime;
}
public void setLogouttime(Timestamp logouttime) {
this.logouttime = logouttime;
}
#
Override
public String toString() {
return "Bean [logindate=" + logindate + ", logintime=" + logintime + ", logouttime=" + logouttime + "]";
}
}
insertdao.java:
package com.eis.bean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
public class insertdao {
public static int addBean(Bean user, String sql) throws SQLException {
int i = 0;
Connection conn = ConnectionProvider.getConn();
try {
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setDate(1, new Date(user.getLogindate().getTime()));
preparedStatement.setTimestamp(2, new Timestamp(user.getLogintime().getTime()));
preparedStatement.setTimestamp(3, new Timestamp(user.getLogouttime().getTime()));
i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
}
insertservlet.java:
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.eis.bean.Bean;
import com.eis.bean.insertdao;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
public class insertservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private insertdao dao;
public insertservlet() {
super();
dao = new insertdao();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Bean user = new Bean();
try {
Date logindate = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParameter("logindate"));
user.setLogindate((java.sql.Date) logindate);
} catch (ParseException e) {
e.printStackTrace();
}
try {
Date logintime = new SimpleDateFormat("HH:mm").parse(request.getParameter("logintime"));
user.setLogintime((java.sql.Timestamp) logintime);
} catch (ParseException ex) {
Logger.getLogger(insertservlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Date logouttime = new SimpleDateFormat("HH:mm").parse(request.getParameter("logouttime"));
user.setLogouttime((java.sql.Timestamp) logouttime);
} catch (ParseException ex) {
Logger.getLogger(insertservlet.class.getName()).log(Level.SEVERE, null, ex);
}
insertdao dao = new insertdao();
String sql = "INSERT INTO dttable (LoginDate, LoginTime, LogoutTime) VALUES (?, ?, ?)";
try {
int i = insertdao.addBean(user, sql);
if (i != 0) {
out.print("<p style=\"color:Green\">Record saved successfully!!</p>");
RequestDispatcher rd = request.getRequestDispatcher("Sucsess.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">**Record cannot be saved!**</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#
Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}#
Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}#
Override
public String getServletInfo() {
return "Short description";
}
}
Please go through my code and help if my code is not right.
Try setTimestamp(int parameterIndex, java.sql.Timestamp x)
preparedStatement.setTimestamp(2, new Timestamp(user.getLogintime().getTimes()));
preparedStatement.setTimestamp(3, new Timestamp(user.getLogouttime().getTime()));

Categories