I'm having a little issue connecting with my servlet so that I can pass some data to a mysql database. I've read a bunch of the threads here, but have had no luck with suggestions to other members.
I have a jsp page named "insertData.jsp" On that page there is a form where the action points to a servlet named "UpdateData". When I click submit on the web page, I get a 404 error stating that the requested resource is not available. I have also updated my web xml file to try to point to the right direction.
So here's my folder setup:
The UpdateData.java is in the controller package of the source packages folder. The name of the project is "RukertContainerTracker".
Here's my jsp page:
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data Into Container Records</h1>
<H1>The Rukert Terminals Container Tracker </H1>
<form name="Insert Record" action="/UpdateData" method="Post">
Container Number: <input type="text" name="containerNumber"> <br />
Full Out: <input type="date" name="fullOut" /> <br/>
Empty In: <input type="date" name="emptyIn" /> <br/>
Empty Out <input type="date" name="emptyOut" /> <br/>
Full In: <input type="date" name="fullIn" /> <br/>
Comments: <input type="text" name="comments" /> <br/>
<input type="submit" value="Submit" />
</form>
<div>
<a href="javascript:history.back();">
<span class="categoryLabelText">HOME</span>
</a>
</div>
</body>
</html>
My servlet:
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
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;
public class UpdateData extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//Get container data from the JSP page
String container=request.getParameter("containerNumber");
String fullOutDate=request.getParameter("fullOut");
String emptyInDate=request.getParameter("emptyIn");
String emptyOutDate=request.getParameter("emptyOut");
String fullInDate=request.getParameter("fullIn");
String comments=request.getParameter("comments");
//Print the above got values in console
System.out.println("The username is" +container);
System.out.println("\nand the password is" +fullOutDate);
String connectionparams="jdbc:mysql://localhost:3306/rukerttracker";
String db="rukerttracker";
String uname="root";
String psword="Colorado1982";
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("com.mysql.jdbc.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection
(connectionparams, uname, psword);
//Add the data into the database
String sql = "insert into containerinventory values (?,?,?,?,?,?)";
try (PreparedStatement prep = connection.prepareStatement(sql)) {
prep.setString(1, container);
prep.setString(2, fullOutDate);
prep.setString(3, emptyInDate);
prep.setString(4, emptyOutDate);
prep.setString(5, fullInDate);
prep.setString(6, comments);
prep.executeUpdate();
}
}catch(Exception E){
System.out.println("The error is=="+E.getMessage());
}
finally{
connection.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/insertData")) {
// TODO: Implement category request
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And finally my web.xml page:
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/chooseLanguage</url-pattern>
<url-pattern>/viewTracker</url-pattern>
<url-pattern>/editTracker</url-pattern>
<url-pattern>/addToCart</url-pattern>
<url-pattern>/viewCompany</url-pattern>
<url-pattern>/category</url-pattern>
<url-pattern>/updateCart</url-pattern>
<url-pattern>/purchase</url-pattern>
<url-pattern>/viewCart</url-pattern>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateData</servlet-name>
<servlet-class>controller.UpdateData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
I have two servlets, I don't know if this matters, but I couldn't get the application to work in the controller servlet, so I created the Update Data servlet.
Any help as to why I keep getting this 404 error would be greatly, greatly appreciated. Thanks for taking the time to look at this.
I think in form you are using POST method and your servlet does not have post method. please check it.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{...}
not available.
Related
I am using netbeans 8.2 and using Apache Tomcat server. Whenever I run the program I get to the registration page. But when I submit the information I am supposed to get an output. But I always get a blank page.I am using the database present in JAVA. Please Help I have to submit my java project;_;. I still need to create a login page.
Thanks in Advance.
Jsp Program
<%--
Document : registeration
Created on : Mar 12, 2019, 10:24:50 AM
Author : Pranav Sharma
--%>
<%#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>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="user" required="required"><br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" />
</form>
</div>
</body>
Servlet Program
package jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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(name="Registeration", urlPatterns={"/Registeration"})
public class Registeration extends HttpServlet
{
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
try {
String name = request.getParameter("user");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(name,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/RegForm","pranav","sharma");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Web-xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Registeration</servlet-name>
<servlet-class>jdbc.Registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registeration</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have create a java-servlet project which uses sql server as a database. Underline project takes input from the ui and persist into database.
After inserting data into database, it will show up is records inserted successfully or not.
Change the DBConnectionUtils according to your database
String url = "jdbc:mysql://localhost:3306/";
String dbName = "root";
String driver = "com.mysql.jdbc.Driver";
This is the link for the project on github https://github.com/rosmahajan/java-servlet
Otherwise please post more information like any exception or error you are getting to investigate what is wrong with your code.
Hope this helps you !!
Here is my code, it is connecting to database, in the console I could see the msg "connected" but the problem is after giving the user credentials it is not navigating to the next page(welcome.jsp) and it just shows a msg that "username or password error" could someone help me out
LoginServlet.java
package com.amzi.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
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{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://WMDENTW1\\SQLEXPRESS:1433;" +
"database=FullTextDB;" +
"user=root;" +
"password=root123";
Connection conn = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
PreparedStatement pst = conn.prepareStatement("select User, Password from dbo.AdminLogin where User=? and Password=?");
pst.setString(1, n);
pst.setString(2, p);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("page opened");
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
} else {
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
}
index.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="LoginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4> Hello, <%=session.getAttribute("name")%></h4>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> <servlet> <servlet-name>login</servlet-name> <servlet-class>com.amzi.servlets.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app>
In response your your request to clarify my comment, instead I shall write it as an answer.
IN your doPost method, you have this line:
PrintWriter out = response.getWriter();
After that, you use out to write directly to the response, such as in these lines:
out.println("page opened");
and
out.print("<p style=\"color:red\">Sorry username or password error</p>");
However, you then go and forward to a JSP:
RequestDispatcher rd=request.getRequestDispatcher("WebContent/welcome.jsp");
rd.forward(request,response);
But that does the same thing - after processing the JSP it sends the result to the response PrintWriter, just have you have done.
You really shouldn't do both. Just use the JSPs.
Secondly, your message 'username or password error' indicates that the query returned no rows, so the username/password you used is probably wrong. I can't see anything wrong with the JDBC code or query.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am creating a payroll system. I have a database which contains employee_id and password. My index.html is the login page, where you enter an employee_id and password and the database checks to see if the details are correct and if it is, then the Welcome.java servlet takes you to a page which prints "Welcome user".
What I want is, when an employee logs in, it takes them to a page with the following buttons instead of a screen which simply says "Welcome user":
View personal information, View payslip information, change password
I do not know how to do this.
Below are my files.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login" method="post">
<h3>
Employee Login
</h3>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
if(Validate.checkUser(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Validate.java (class file)
import java.sql.*;
public class Validate
{
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?");
ps.setString(1, employee_id);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Welcome user");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You have to change one line of code of login servlet RequestDispatcher rs = request.getRequestDispatcher("Welcome"); as RequestDispatcher rs = request.getRequestDispatcher("Options");
and create a html file of creating 3 buttons.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Options</title>
</head>
<body>
<form action="Mainservlet" method="post">
<h3>
Options
</h3>
<input type="submit" value="Personalinformation" name="pi">
<br>
<br>
<input type="submit" value="PayslipInformation" name="psi">
<br>
<br>
<input type="submit" value="ChangePassword" name="cp">
<br>
<br>
</form>
</body>
</html>
In mainservlet
if(request.getParameter("pi") != null) {
// Invoke PersonalInformation's job here.
} else if (request.getParameter("psi") != null) {
// Invoke PayslipInformation's job here.
}else if (request.getParameter("cp") != null) {
// Invoke ChangePassword's job here.
}
Create an html or jsp page with your buttons and other content, then redirect from login servlet to your page instead of welcome servlet through request dispatcher or just by response.sendRedirect() method.
I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.
Is it better to invalidate a session in a servlet in which it is declared or in the JSP page where its values will be used ?
I am posting the code of servlet below -
package Controller.UploadInfo;
import File.FileOperations;
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;
import Controller.DatabaseException.*;
public class AttendenceInfoUpload extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
HttpSession session;
if (FileOperations.fileUpload(request)) {
try {
FileOperations.excelToAttendence();
request.getRequestDispatcher("UploadSuccess.jsp").forward(request, response);
} catch (DBException e) {
session = request.getSession(true);
session.setAttribute("exception",e);
request.getRequestDispatcher("FileUpload.jsp").forward(request, response);
session.invalidate();
}
} else {
session = request.getSession(true);
session.setAttribute("exception"," File Upload Failed " );
request.getRequestDispatcher("FileUpload.jsp").forward(request, response);
}
}
}
#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";
}// </editor-fold>
}
In the given servlet above I have invalidated the session right after the getRequestDispatcher() in the catch block. Although the code is working, my concern is will it cause the exception message to loose before it can be displayed in the JSP page. Or is it better to invalidate the session declared in the servlet in the JSP page where its values will be displayed.
The JSP page -
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import = "java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Excel File Upload Example</h1>
<form name="form1" method="post" action="AttendenceInfoUpload" enctype="multipart/form-data">
<table border="1">
<col width="120">
<tr>
<td>Upload Excel File:</td>
<td><input type="file" name="Select File"/></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="submit" value="upload" /></td>
</tr>
</table>
</form>
<c:if test="${not empty exception}">
<label>
<font color="red">
<c:out value="Error:${exception}"></c:out>
</font>
</label>
</c:if>
</body>
</html>
One can suggest an alternate solution as well?
The best solution is probably to invalidate the session in the servlet but make sure that any values required by the JSP are stored in the request rather than in the session. I say this because it is best practice to put all logic in beans or servlet code and keep JSPs for layout only.
There's no need to invalidate a session. Also there's no need to use a session attribute. If you want to forward to a error page you can use request attribute. Using a session heavily is a bad practice because it requires a lot of memory to utilize those variables you put into it.
} catch (DBException e) {
request.setAttribute("exception",e);
request.getRequestDispatcher("FileUpload.jsp").forward(request, response);
}
as I said it's not a good practice to invalidate a session when you are going to forward to a error page. Even if JSP page is rendered in the same thread other threads that can use the same session might not work. And you can't use session variables after the session is invalidated. However it's rarely happens but other request might invalidate a session while JSP is rendered.