How to pass variable from java to jsp? - java

EmployeeController.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Employee employee = new Employee();
employee.setFirstname(request.getParameter("firstName"));
employee.setLastname(request.getParameter("lastName"));
employee.setEmail(request.getParameter("email"));
employee.setStatus(request.getParameter("status"));
String employeeId = request.getParameter("email");
employee.setEmail(employeeId);
dao.addEmployee(employee);
RequestDispatcher view = request.getRequestDispatcher(employee_listing);
request.setAttribute("employees", dao.getAllEmployees());
view.forward(request, response);
}
EmployeeDao.java
HttpServletRequest request;
public void addEmployee(Employee employee) throws ServletException, IOException{
try {
PreparedStatement preparedStatement = conn.prepareStatement("insert into login(firstname, lastname, email, pass, role, status) values (?, ?, ?, ?, 'employee', ?)");
preparedStatement.setString(1, employee.getFirstname());
preparedStatement.setString(2, employee.getLastname());
preparedStatement.setString(3, employee.getEmail());
//preparedStatement.setString(4, employee.getFirstname());
preparedStatement.setInt(4, employee.getFirstname().hashCode());
preparedStatement.setString(5, employee.getStatus());
//preparedStatement.setBoolean(4, employee.getStatus());
int i = preparedStatement.executeUpdate();
if(i > 0){
System.out.println("Employee added successfully.");
HttpSession session = request.getSession();
session.setAttribute("successMessage", "Employee added successfully.");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
//e.printStackTrace();
}
}
addEmployee.jsp
<form class="form-horizontal" method="post" action="EmployeeController" name="frmAddEmployee" id="frmAddEmployee">
<!-- <form class="form-horizontal" method="post" action="adduser.jsp" name="frmAddEmployee" id="frmAddEmployee"> -->
<div class="form-group">
<label for="" class="col-sm-4 control-label">First Name</label>
<div class="col-sm-8">
<input type="text" name="firstName" class="form-control" id="firstName">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Last Name</label>
<div class="col-sm-8">
<input type="text" name="lastName" class="form-control" id="lastName" >
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="email" >
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Employee Status</label>
<div class="col-sm-8">
<label class="switch">
<input type="checkbox" name="status" value="1" checked>
<div class="slider round"></div>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<input type="submit" name="submit" value="Submit" class="btn btn-primary"> <!-- <button name="cancel" onclick='employee-listing.jsp' class="btn btn-primary" >Cancel</button> -->
</div>
</div>
</form>
So basically when submit the form It redirects to EmployeeController.java file and get all the values in Employee and then redirect to EmployeeDao.java file to addEmployee(employee);
And I will get this in jsp page like ::
session.getAttribute("successMessage");
I tried all this but i didn't get any message form "successMessage" attribute and got only "null" value.
I also tried to response.sendRedirect("employee-success.jsp") but still it didnt redirect to that page.
So can anyone help me to set the value in java code and get that value in jsp page for further use.

change your
public void addEmployee(Employee employee)
to
public void addEmployee(Employee employee, HttpServletRequest request)
pass HttpServletRequest object in EmployeeController.java
dao.addEmployee(employee,request);

Pass the request object from your Controller,
dao.addEmployee(employee);
and access the sessionAttribute directly in your jsp anywhere like,
${successMessage}
OR
you can send the success message back to your Controller from addEmployee method and then set that String message in request attribute like,
String successMessage = dao.addEmployee(employee);
RequestDispatcher view = request.getRequestDispatcher(employee_listing);
request.setAttribute("employees", dao.getAllEmployees());
request.setAttribute("successMessage", successMessage);
In your DAO method,
public String addEmployee(Employee employee) throws ServletException, IOException{
String successMessage = "";
try {
PreparedStatement preparedStatement = conn.prepareStatement("insert into login(firstname, lastname, email, pass, role, status) values (?, ?, ?, ?, 'employee', ?)");
preparedStatement.setString(1, employee.getFirstname());
preparedStatement.setString(2, employee.getLastname());
preparedStatement.setString(3, employee.getEmail());
//preparedStatement.setString(4, employee.getFirstname());
preparedStatement.setInt(4, employee.getFirstname().hashCode());
preparedStatement.setString(5, employee.getStatus());
//preparedStatement.setBoolean(4, employee.getStatus());
int i = preparedStatement.executeUpdate();
if(i > 0){
System.out.println("Employee added successfully.");
HttpSession session = request.getSession();
successMessage = "Employee added successfully.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
//e.printStackTrace();
successMessage = "Error occured while adding employee."
}
return successMessage;
}

Related

HTTP Status 404 Error - [Message] The requested resource [/DentalRecordFYP/updateInvent] is not available

I have this error and I can't seem to fix it. The java file is supposed to update the new details of the item to the database table "inventory". While the jsp file is where you do the adjustment. Please assist me in this issue
This is the JSP file where the details can be edited.
<section>
<div class="main">
<div class="container-contact100">
<div class="wrap-contact100">
<div class="contact100-form-title"
style="background-image: url(img/bg-01.jpg);">
<span class="contact100-form-title-1"> Item Details </span>
</div>
<form class="contact100-form validate-form" action="updateInvent"
method="post" id="register-form">
<div class="hiddeninfo">
<label for="name"><i
class="zmdi zmdi-account material-icons-name"></i></label> <input
type="text" name="id" id="id" value=<%=rs.getString(1)%> />
</div>
<div class="wrap-input100 validate-input"
data-validate="Item Name is required">
<span class="label-input100"><i
class="zmdi zmdi-account material-icons-name"></i></span> <input
class="input100" type="text" name="itemname" id="itemname"
value=<%=rs.getString(2)%> > <span
class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input"
data-validate="Item status is required">
<span class="label-input100"><i class="zmdi zmdi-status"></i></span>
<input class="input100" type="itemstatus" name="itemstatus" id="itemstatus"
value=<%=rs.getString(3)%> > <span
class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input"
data-validate="Item quantity is required">
<span class="label-input100"><i class="zmdi zmdi-quantity"></i></span>
<input class="input100" type="text" name="itemqty" id="itemqty"
value=<%=rs.getString(4)%> >
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input"
data-validate="Date of Birth is required">
<span class="label-input100"><i class="zmdi zmdi-calendar"></i></span>
<input class="input100" type="date" name="itemexpdate" id="itemexpdate"
value=<%=rs.getString(5)%> >
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<button class="contact100-form-btn btn-updateInvent">
<span> Update </span>
</button>
</div>
</form>
<form method="post" action="delete"
class="contact100-form validate-form small-form" id="register-form">
<div class="hiddeninfo">
<label for="name"> <i
class="zmdi zmdi-account material-icons-name"></i></label> <input
type="text" name="id" id="id" value=<%=rs.getString(1)%> />
</div>
<div class="container-contact100-form-btn">
<button class="btn-danger">
<span> Delete </span>
</button>
</div>
</form>
</div>
</div>
</div>
</section>
Where this is the java file where it update the new data that was edited in the JSP and replace the new data to the database table accordingly
#WebServlet("/updateInvent")
public class UpdateInventory extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public UpdateInventory() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String itemname = request.getParameter("itemname");
String itemstatus = request.getParameter("itemstatus");
String itemqty = request.getParameter("itemqty");
String itemexpdate = request.getParameter("itemexpdate");
Connection conn = null;
RequestDispatcher dispatcher = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dentalrecord?useSSL=false","root","");
PreparedStatement pst = conn.prepareStatement("UPDATE inventory set itemname=?,itemstatus=?,itemqty=?,itemexpdate=?");
pst.setString(1, itemname);
pst.setString(2, itemstatus);
pst.setString(3, itemqty);
pst.setString(4, itemexpdate);
pst.executeUpdate();
response.sendRedirect("inventorylist.jsp");
}
catch(IllegalStateException ignore) {
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Inserting user records into MYSQL table

I am trying to create a register page for users to register new accounts.
I am using signup.jsp page with the register form
Which is then connected to RegisterServlet.java (gets form parameters and inserts parameters into database after connecting to DBConnection.java)
DBConnection contains the try{} of connecting to the mysql database.
I have tried multiple ways of registering a user, but the users information never inserts into database.
signup.jsp:
<form action="RegisterServlet" method="post" onsubmit="return validate()">
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="First Name" name="fname" class="form-control" />
</div>
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="Last Name" name="lname" class="form-control" />
</div>
</div>
<div>
<input type="text" placeholder="User Name" name="username" class="form-control" />
</div>
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Password" name="password" class="form-control" id="pass" name="pass" />
</div>
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Retype Password" name="confirm_password" class="form-control" id="pass2" name="pass2" />
</div>
<div class="col-lg-6 col-md-6">
<%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%>
</div>
</div>
<div class="pull-left"><button type="submit" class="btn btn-primary">Sign Up</button></div>
</form>
RegisterServlet.java:
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String username = request.getParameter("username");
String password = request.getParameter("password");
DBConnection db = new DBConnection();
Connection con = db.getCon();
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
System.out.println("data inserted sucessfully");
response.sendRedirect("login.jsp");
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
DBConnection.java
public class DBConnection {
public Connection con;
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cultureexchange", "root", "");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
Sql user table:
fname lname username password
varchar varchar varchar varchar
My login.jsp works so the connection to database must work,
appreciate the help in advance.
try Changing these line
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
to
PreparedStatement stmt = con.prepareStatement("insert into user (fname, lname, username, password)values(?,?,?,?)");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, username);
ps.setString(4, password);
ps.executeUpdate();
And make sure that you have mysql-j-connector in your lib folder under WEB-INF.

login page with 2 radio button in java languages

I have a login page and when i run it, it must check which radio button is checked and check database for that radio button.
When I run the codes I get this error:
HTTP Status 500 - Request processing failed;
nested exception is java.lang.NullPointerException
and
this is my web page:
<form action="/HelloWorldInWeb/login" method="post">
<div class="col-lg-12" id="div3">
<div class="form-group input-group" id="div4">
<div class="input-group-addon "><span class="glyphicon glyphicon-eye-open "></span></div>
<input type="text" class="form-control" name="username" id="textbox1" placeholder="Enter your username">
</div>
<div class="form-group input-group" id="div5">
<div class="input-group-addon "><span class="glyphicon glyphicon-eye-close "></span></div>
<input type="text" class="form-control" name="password" id="textbox2" placeholder="Enter your Password">
</div>
<div class="form-group" id="div6">
<label><input type="radio" name="sign" name="checkbox" value="adminstrator" id="adminstrator" checked>Adminstrator</label>
<label><input type="radio" name="sign" name="checkbox" value="admin" id="admin">Admin</label>
</div>
<div class="align">
<button type="submit" class="btn btn-danger">Ok</button>
</div>
</div>
</form>
this is my controler servelt:
#SuppressWarnings({ "null", "static-access"})
#RequestMapping(value="/login" , method = RequestMethod.POST)
protected void doPost(HttpServletRequest reque, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=reque.getParameter("username");
String password=reque.getParameter("password");
String radio=reque.getParameter("checkbox");
if(radio.equals("admin")){
Boolean t = stdDAO.validate(username, password);
if(t){
out.print(username);
out.print(password);
out.print(" username or password succes");
response.sendRedirect("/HelloWorldInWeb/addozvv");
}
else{
out.print(username);
out.print(password);
out.print("Sorry username or password error");
response.sendRedirect("/HelloWorldInWeb/login");
}
out.close();
}else
if(radio.equals("adminstrator")){
Boolean s = stdDAO.validateadm(username, password);
if(s){
out.print(username);
out.print(password);
out.print(" username or password succes");
response.sendRedirect("/HelloWorldInWeb/addozvv");
}
else{
out.print(username);
out.print(password);
out.print("Sorry username or password error");
response.sendRedirect("/HelloWorldInWeb/login");
}
}
}
this is my validates:
public Boolean validate(String username, String password) {
boolean t =false;
try{
Connection con = dataSource.getConnection();
PreparedStatement ps =con.prepareStatement
("select * from admins where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
t = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return t;
}
#Override
public java.lang.Boolean validateadm(String username, String password) {
boolean s =false;
try{
Connection con = dataSource.getConnection();
PreparedStatement ps =con.prepareStatement
("select * from admin where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
s = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return s;
}
radio may be null. Use "admin". equals(radio) and "administrator".equals(radio) in your if statements.

Updating database in JSP

I coded this Java code for my JSP page to update current login details of a user. Code is not showing any errors or exceptions but not updates the MySql database.
Help me to to implement this functionality;
My code:
<%
//variable declaration for encrypt and decrypt
byte [] input ;
byte [] keyBytes = "12345678".getBytes();
byte [] ivBytes ="input123".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText;
int ctLength=0;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
if(request.getParameter("submit")!=null){
String cuser=request.getParameter("currentusername");
String user = request.getParameter("username");
String pwd = request.getParameter("password");
String cpwd = request.getParameter("confirmpassword");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input = pwd.getBytes();
key = new SecretKeySpec(keyBytes, "DES");
ivSpec = new IvParameterSpec(ivBytes);
cipher = Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(input.length)];
ctLength+=cipher.update(input, 0, input.length, cipherText, 0);
ctLength+= cipher.doFinal(cipherText, ctLength);
String enpwd = new String(cipherText);
String sql2 = "update webadmin set username=? ,password=? where username='"+cuser+"' ";
if((cuser!=null &&cuser.length()>0)
&& (user!=null &&user.length()>0)
&& (pwd!=null && pwd.length()>0)
&& cpwd!=null && cpwd.length()>0) {
if((pwd.equals(cpwd))){
pst =conn.prepareStatement(sql2);
pst.setString(1, user);
pst.setString(2, enpwd);
pst.executeUpdate();
%>
<script language="JavaScript">
alert("Sucessfully Updated");
</script>
<%
}else{
%>
<script language="JavaScript">
alert("Passwords are not matching try again");
</script>
<%
}
}
}
}
%>
Note: I implement to encrypt the password and store that encrypted password to the database.
HTML form;
<form id="login-form" action="adminpg-mysettings.jsp" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="currentusername" id="currentusername" tabindex="1" class="form-control" placeholder="Current Username" value="" required="">
</div>
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="New Username" value="" required="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="New Password" required="">
</div>
<div class="form-group">
<input type="password" name="confirmpassword" id="password" tabindex="2" class="form-control" placeholder="Confirm New Password" required="">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="submit" id="submit" tabindex="4" class="form-control btn btn-login" value="Save">
</div>
</div>
</div>
</form>
First of, like everyone will tell you, it is a very bad idea to put Java in JSP. The correct way of operating is with a Servlet and requests stored in session. It will prevent malicious sql injections.
Second of, your security constraints should be handled in the web.xml and Servlet, which is best for back-end maintenance. Following good programming practice will prevent you from going crazy over bugging logs.
I can help you implement what you are trying to do with a Servlet, but before I do, I need to know the following:
The obvious: Do you have a Servlet?
Do you use JDBC/JNDI connectivity?
Do you have entity and session classes for user?
Which IDE/framework do you use to develop your app?
What server are you deploying to?
It is the most effective way of accomplishing what you want. Please provide with the answers and I will update my answer with some code :)
public class UpdateController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
request.setAttribute("id", new StudentDAO().getStudent(id));
request.getRequestDispatcher("update.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Date dob = Date.valueOf(request.getParameter("dob")); // yyyy-mm-dd
String gender = request.getParameter("gender");
Student s = new Student();
s.setId(id);
s.setName(name);
s.setGender(gender);
s.setDob(dob);
StudentDAO db = new StudentDAO();
db.update(s);
response.sendRedirect("list");
request.setAttribute("students", new StudentDAO().getAll());
// request.getRequestDispatcher("list.jsp").forward(request, response);
}
public void update(Student s) {
try {
String sql = "UPDATE [dbo].[Student]\n"
+ " SET [name] = ?\n"
+ " ,[gender] = ?\n"
+ " ,[dob] = ?\n"
+ " WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, s.getName());
ps.setString(2, s.getGender());
ps.setDate(3, s.getDob());
ps.setInt(4, s.getId());
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update</title>
<% String id = request.getParameter("id");%>
</head>
<body>
<form action="update" method="post">
<table>
<tr>
<td>ID: <input type="text" name="id"
value="<%=id%>" readonly></td>
</tr>
<tr>
<td>Name: <input type="text" name="name"/></td>
</tr>
<tr>
<td>Gender: <input type="radio" name="gender" value="male"/> Male
<input type="radio" name="gender" value="female"/> Female </td>
</tr>
<tr>
<td>Dob: <input type="date" name="dob" /></td>
</tr>
</table>
<input type="submit" value="Create" />
</form>
</body>

Cannot pass multipart data to servlet when using jsp el

I am passing checkbox values, username , file as parameter to a servlet that uses MultipartRequest class from com.orielly.servlet package. I am using the jsp el in my jsp.
my jsp is
<c:set var="currentUser" value="${currentUser}" />
<div class="container">
<div class="panel panel-default" >
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-body">
<form action="ProcessShareFileReq?username="${currentUser}" method="post" enctype="multipart/form-data">
<h4>Upload file here</h4>
<input type="file" class="form-control" required="required" name="file" value=""/>
<h4 class="page header">Share with</h4>
<ul class="list-group">
<c:forEach var="request" items="${requestList}">
<li class="list-group-item title">
<input type="checkbox" name="usersList" value="${request.senderFullName}" /><strong> ${request.senderFullName} </strong>
</li>
</c:forEach>
</ul>
<label class="label" for ="description">Description(Helps other users understand the content of file)</label>
<textarea id="description" name="fileDescription" rows="10" cols="5"></textarea>
<div class="break"></div>
<input type="submit" class="btn btn-default pull-left" value="Upload">
<input type="reset" class="btn btn-default pull-left" value="Reset">
</form>
</div>
</div>
</div>
</div>
</div>
my servlet
#WebServlet("/ProcessShareFileReq")
#MultipartConfig
public class ProcessShareFileReq extends HttpServlet {
private static final long serialVersionUID = 1L;
private String webTempPath;
public void init( ) {
webTempPath= "C://BEProject/Shared";
//webTempPath = getServletContext( ).getRealPath("/") + "data";
}
//Generates current time suitable for oracle timestamp
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection currentCon =null;
PreparedStatement ps = null;
int result;
//list of users to share with
String[] UserList = request.getParameterValues("usersList");
//logged-in-user's username
String loggedInUser = request.getParameter("username");
//Shared file's description
String fileDescription = request.getParameter("fileDescription");
//adding path according to sharer's user-name
String userPath = webTempPath + "/" + loggedInUser;
//generate directory
boolean success =( new File(userPath)).mkdirs();
//make directory
if(success) {
System.out.println("Directory: " + webTempPath + " created");
}
//Renames file to the 'sharer_receipent_timestamp' pattern
//Get the uploaded file with multipartRequest
//file limit size of 50 MB
MultipartRequest mpr = new MultipartRequest(request,userPath,50 * 1024 * 1024);
//Database create operations.
Enumeration enum1 = null;
try {
currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
for(int i=0;i<UserList.length;i++)
{
String shareFileQuery = "insert into sharedfiles values(share_seq.NEXTVAL,?,?,?,?,?)";
ps = currentCon.prepareStatement(shareFileQuery);
//set the values to put in the query
ps.setString(1, loggedInUser);
ps.setString(2, UserList[i]);
enum1 = mpr.getFileNames( );
String filename = mpr.getFilesystemName((String) enum1.nextElement());
ps.setString(3, filename);
ps.setString(4, fileDescription);
ps.setTimestamp(5, getCurrentTimeStamp());
result=ps.executeUpdate();
if(result>0)
{
System.out.println("Database updated \n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html");
request.setAttribute("username", loggedInUser);
RequestDispatcher rd = request.getRequestDispatcher("/SharedFilesHistory");
rd.forward(request, response);
}
I have annotated the servlet with #MultipartConfig so that it can handle the file parameter.
But after adding this it goes upto to the last line and gives error as
java.io.IOException: Corrupt form data: premature ending
com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:207)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:223)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:110)
servlet.share.ProcessShareFileReq.doPost(ProcessShareFileReq.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
filter.authentication.AuthenticationFilter.doFilter(AuthenticationFilter.java:40)
When remvoving the MultipartConfig it gives a NullPointerException at the for loop since 'UserList' is null since no value is received in servlet from jsp.
Please help
I remember having some little issues when working with MultipartRequest (seems related to some bugs), which made me drop its usage in favor of the native Servelt 3.x Part and which may be a good alternative for you:
Inside your doPost method you can retrieve your file as a Part of the request using its name:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//...
Part filePart = request.getPart("file"); // Retrieves <input type="file" class="form-control" required="required" name="file" value=""/>
InputStream fileContent = filePart.getInputStream(); // Get an InputStream then let the file make its way to your storage location
}

Categories