here I want to upload my file into my upload folder but in my scenario, it cannot store in that folder. The file name is printed in the console but the file does not store in the upload folder. In the Developer tool console, I get an error called Failed to load resource: the server responded with a status of 404 (Not Found).
DemoForm.java
package controller;
import java.io.*;
import java.util.* ;
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 DemoForm
*/
#WebServlet("/DemoForm")
#MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10, //10MB
maxFileSize = 1024 * 1024 * 50, //50MB
maxRequestSize = 1024 * 1024 * 100 //100MB
)
public class DemoForm extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "upload";
/**
* #see HttpServlet#HttpServlet()
*/
public DemoForm() {
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 {
request.setAttribute("username", request.getParameter("username"));
request.setAttribute("password", request.getParameter("password"));
request.setAttribute("sex", request.getParameter("sex"));
request.setAttribute("favious", Arrays.toString(request.getParameterValues("favious")));
request.setAttribute("description", request.getParameter("description"));
request.setAttribute("experience", request.getParameter("experience"));
request.setAttribute("fileName", uploadFile(request));
request.getRequestDispatcher("form_result.jsp").forward(request, response);
}
private String uploadFile(HttpServletRequest request) {
String fileName = "";
try {
Part filePart = request.getPart("photo");
fileName = getfileName(filePart);
String applicationPath = request.getServletContext().getRealPath("");
String basePath = applicationPath + File.separator + UPLOAD_DIR
+ File.separator;
// creates the save directory if it does not exists
File fileSaveDir = new File(basePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
File outputFilePath = new File(basePath + fileName);
inputStream =filePart.getInputStream();
outputStream = new FileOutputStream(outputFilePath);
int read = 0;
final byte[] bytes = new byte[1024];
while((read = inputStream.read(bytes))!= -1) {
outputStream.write(bytes,0,read);
}
}catch(Exception ex) {
ex.printStackTrace();
fileName="";
}finally {
if(outputStream != null) {
outputStream.close();
}
if(inputStream != null) {
inputStream.close();
}
}
}catch(Exception ex){
fileName = "";
}
return fileName;
}
private String getfileName(Part part) {
final String partHeader = part.getHeader("content-disposition");
System.out.println("*****partHeader:" + partHeader);
for(String content : part.getHeader("content-disposition").split(";")) {
if(content.trim().startsWith("fileName")) {
return content.substring(content.indexOf('=')+ 1).trim()
.replace("\"", "");
}
}
return null;
}
}
Form.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>Upload file</title>
</head>
<body>
<form method="post" action="DemoForm" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td> username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td valign="top"> Sex </td>
<td>
<input type="radio" name="sex" value="male" checked="checked"/>Male
<br>
<input type="radio" name="sex" value="female"/>Female
</td>
</tr>
<tr>
<td valign="top"> Favious </td>
<td>
<input type="checkbox" name="favious" value="fav1"/>Favios 1<br>
<input type="checkbox" name="favious" value="fav2"/>Favios 2<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 3<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 4<br>
<input type="checkbox" name="favious" value="fav1"/>Favios 5<br>
</td>
</tr>
<tr>
<td valign="top"> Description:</td>
<td><textarea rows="10" cols="20" name="description"></textarea></td>
</tr>
<tr>
<td>Experiences</td>
<td>
<select name="experience">
<option value="1"> 1 year </option>
<option value="2"> 2 year </option>
<option value="3"> 3 year </option>
<option value="4"> 4 year </option>
</select>
</td>
</tr>
<tr>
<td valign="top"> Photo</td>
<td><input type="file" name="photo "/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save"/></td>
</tr>
</table>
</form>
</body>
</html>
Form_result.jsp
[<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Account Information</h3>
<table border="0" cellpadding="2" cellspacing="2" width="300">
<tr>
<td>Username</td>
<td> ${username}</td>
</tr>
<tr>
<td>Password</td>
<td> ${password}</td>
</tr>
<tr>
<td valign="top">Sex</td>
<td> ${sex}</td>
</tr>
<tr>
<td valign="top">Favious</td>
<td> ${favious}</td>
</tr>
<tr>
<td valign="top">Description</td>
<td> ${description}</td>
</tr>
<tr>
<td>Experience</td>
<td> ${experience}</td>
</tr>
<tr>
<td valign="top">Photo</td>
<td><img src="upload/${fileName}"></td>
</tr>
</table>
</body>
</html>][1]
I think the error is not in your file uploading. Your request has not been received by your servelet. Just comment out all the codes and check whether your doPost is working or not? Check the URL you are hitting.
The endpoint on which you are trying to upload the file is invalid.
Errorcode 404 means that the endpoint can not be found.
Related
This question already has answers here:
request getParameter is always null when using enctype="multipart/form-data"
(2 answers)
Closed 2 years ago.
I have Registration_Page.jsp in that page i had one form ..I want to submit the form to database with the use of the servlet..My servlet name is Save_User_Details.java i want to get the jsp page form data into the servlet..It is getting null value ..How i can get those values in to the servlet anyone help me i am the newer to java..
Registration_Page.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title> Registration Page</title>
<script language="JavaScript" src="gen_validatorv4.js"
type="text/javascript" xml:space="preserve"></script>
</head>
<body>
<h2 style="color: #ff6666" align="center">NEW USER REGISTRATION HERE</h2>
<form ENCTYPE="multipart/form-data" action="Save_User_Details"
method="POST" align="center" name="myform">
<table border="02" align="center" style="color: #ff3399">
<tr>
<th style="color:#ff6666">FIRST NAME:</th>
<td><input type="text" name="FName" id="FName" placeholder="First name" /></td>
</tr>
<tr>
<th style="color:#ff6666">LAST NAME:</th>
<td><input type="text" name="LName" id="LName" placeholder="Last name" /></td>
</tr>
<tr>
<th style="color:#ff6666">PASSWORD:</th>
<td><input type="password" name="password" id="password" placeholder="password"></td>
</tr>
<!-- <tr>
<th>CONFORM PASSWORD:</th>
<td><input type="password" name="conform_password" placeholder="conform password"></td>
</tr> -->
<tr>
<th style="color:#ff6666">EMAIL ID:</th>
<td><input type="email" name="mailid" id="mailid" placeholder="Mailid"></td>
</tr>
<tr>
<th style="color:#ff6666">MOBILE NUMBER</th>
<td><input type="number" name="mobile" id="mobile" placeholder="Mobile number"></td>
</tr>
<tr>
<th style="color:#ff6666">GENDER:</th>
<td style="color:#ff6666"><input type="radio" value="male" name="gender" id="gender"
checked="true">MALE <input type="radio" value="female"
name="gender">FEMALE <input type="radio" value="other"
name="gender">OTHER<br> <br></td>
</tr>
<tr>
<th style="color:#ff6666"><label>DATE OF BIRTH:</label></th>
<td><input type="date" name="dob" id="dob"><br> <br></td>
</tr>
<tr>
<th style="color:#ff6666">COUNTRY:</th>
<td><select name="Country" id="country" style="width: 150px">
<option value="000" selected="selected">[choose yours]</option>
<!-- <select name="country" style="width:150px"> -->
<option>India</option>
<option>USA</option>
<option>UK</option>
<option>Other</option>
</select>
<tr>
<th></th>
<td><input type="submit" style="color: #ff3399" value="SUMIT" />
<button style="color: #ff3399" type="reset">CLEAR</button>
</td>
</tr>
</tr>
<tr>
<td></td>
<td>LOGIN PAGE</td>
</tr>
</table>
</form>
<script language="JavaScript" type="text/javascript"
xml:space="preserve">
//<![CDATA[
//You should create the validator only after the definition of the HTML form
var frmvalidator = new Validator("myform");
frmvalidator.addValidation("FName", "req",
"Please enter your First Name");
frmvalidator.addValidation("FName", "maxlen=20",
"Max length for FirstName is 20");
frmvalidator.addValidation("FName", "minlen=4",
"Min length for FirstName is 4");
frmvalidator.addValidation("FName", "alpha", "Alphabetic chars only");
frmvalidator.addValidation("LName", "req",
"Please enter your Last Name");
frmvalidator.addValidation("LName", "maxlen=20", "Max length is 20");
frmvalidator.addValidation("LName", "minlen=4",
"Min length for LastName is 4");
frmvalidator.addValidation("password", "maxlen=10");
frmvalidator.addValidation("password", "req");
frmvalidator.addValidation("password", "");
frmvalidator.addValidation("password", "minlen=6",
"Min length for Password is 6");
frmvalidator.addValidation("mailid", "maxlen=50");
frmvalidator.addValidation("mailid", "req");
frmvalidator.addValidation("mailid", "email");
frmvalidator.addValidation("mailid", "minlen=6",
"Min length for Mailid is 6");
frmvalidator.addValidation("gender", "dontselect=000");
frmvalidator.addValidation("gender", "req");
frmvalidator.addValidation("mobile", "maxlen=10");
frmvalidator.addValidation("mobile", "numeric");
frmvalidator.addValidation("mobile", "req");
frmvalidator.addValidation("mobile", "minlen=10",
"Mobile number should be 10 numbers");
frmvalidator.addValidation("dob", "maxlen=40");
frmvalidator.addValidation("dob", "req");
frmvalidator.addValidation("Country", "dontselect=000");
frmvalidator.addValidation("Country", "req");
//]]>
</script>
</body>
</html>
Save_User_Details.java
package com.ih.Control;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
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 com.ih.Dao.UserDao;
import com.ih.Model.User_Details;
/**
* Servlet implementation class Save_User_Details
*/
#WebServlet("/Save_User_Details")
public class Save_User_Details extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Save_User_Details() {
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 {
// TODO Auto-generated method stub
doGet(request, response);
User_Details ud=new User_Details();
System.out.println("i am in Save_User_Details..........");
PrintWriter out=response.getWriter();
int status=0;
String fname=request.getParameter("FName");
System.out.println("The FNAME::"+fname);
String lname=request.getParameter("LName");
System.out.println("The LNAME::"+lname);
String password=request.getParameter("password");
System.out.println("The PASSWORD::"+password);
String mailid=request.getParameter("mailid");
String mobile=request.getParameter("mobile");
String gender=request.getParameter("gender");
String dob=request.getParameter("dob");
String country=request.getParameter("country");
System.out.println("FNAME::"+fname+"LNAME::"+lname+"PASSWORD::"+password+"MAILID::"+mailid+"MOBILE::"+mobile+"GENDER::"+gender+"DOB::"+dob+"COUNTRY::"+country);
ud.setFName(fname);
ud.setLName(lname);
ud.setPassword(password);
ud.setMailid(mailid);
ud.setMobile(mobile);
ud.setGender(gender);
ud.setDob(dob);
ud.setCountry(country);
try {
UserDao.SaveRegistration_Details();
RequestDispatcher rd=request.getRequestDispatcher("Login.jsp");
rd.forward(request, response);
} catch (SQLException e) {
out.println("<h1 style='color:red'>FAILED TO INSERT USER DATA TRY AGAIN!!</h1>");
out.println("<a href='Registration_Page.jsp'>REGISTER AGAIN</a>");
e.printStackTrace();
}
}
}
enctype="multipart/form-data" is for 'file upload', not for normal textbox.
When you use enctype="multipart/form-data" form fields aren't available as parameter of the request, so you will get request.getParameter() as null.
You can find more info in HTML5 specification.
There are two tables in my database (filedetails and filestatus).
I using the following code to insert value in filedetails table.
In filestatus table i have 3 columns
filenumber,
fdepartment,
status(either in or out).
In my status.jsp page I have given 3 dropdown list in which 2 dropdownlist take filenumber and department from filedetails table and 1 takes status(which is either IN or OUT).
If status is OUT values are simply inserted in filestatus table but if it is in the values are inserted into filestatus and department corresponding to filenumber gets updated.
The problem is the filenumber, if i use the following code to insert filenumber then how will i update the file number ?
Is ther some other way to do this?
file.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert File Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}
section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<font color="black">back</font>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<form action="FileServlet" method="post">
<h3>Insert File Details</h3>
<table border="1">
<tbody>
<tr>
<td>File Name :</td>
<td><input type="text" name="filename" value="" size="50" /></td>
</tr>
<tr>
<td>File Type</td>
<td><input type="text" name="type" value="" size="50" /> </td>
</tr>
<tr>
<td>Place of Origin(company) :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>HeadOffice :</td>
<td><input type="text" name="HO" value="" size="50" /> </td>
</tr>
<tr>
<td>File Location :</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Subject :</td>
<td><input type="text" name="subject" value="" size="50" /></td>
</tr>
<tr>
<td>File Number :</td>
<td><input type="text" name="fileno" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.
</footer>
</body>
</html>
fileServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FileServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
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("User="+session.getAttribute("user"));
if(session!=null && session.getAttribute("user") != null){
String user=(String)session.getAttribute("user");
boolean status=false;
try{
String fname=request.getParameter("name");
String type=request.getParameter("type");
String company=request.getParameter("department");
String headoffice=request.getParameter("HO");
String location=request.getParameter("department");
String subject=request.getParameter("subject");
String fno=company+"/"+headoffice+"/"+location+"/"+type+"/"+fname;
Connection con=ConnectionProvider.getCon();
String sql="insert into files(fileno,fname,ftype,subject,company,headoffice,fdepartment) values (?,?,?,?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,fno);
pstmt.setString(2,fname);
pstmt.setString(3,type);
pstmt.setString(4,subject);
pstmt.setString(5,company);
pstmt.setString(6,headoffice);
pstmt.setString(7,location);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){System.out.println(e);}
if(status){
PrintWriter out= response.getWriter();
out.println("Values have been inserted"+user);
response.sendRedirect("create1.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.println("failed");
response.sendRedirect("create1.jsp");
}
}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);
}
}
}
There is create.jsp which gives link to choose for filedetails.jsp or status.jsp
status.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import ="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Status Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}
section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<font color="black">back</font>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<h3>Change Status</h3>
<form action="statusServlet" method="post">
<select name="files">
<%
try{
String sql="select * from files";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getInt("fileno")%>"><%=rs.getString("fname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select>
<select name="departments">
<%
try{
String sql="select * from department";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getInt("departmentid")%>"><%=rs.getString("departmentname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select>
<select name="input">
<option>IN</option>
<option>OUT</option>
</select>
<input type="submit" value="submit" name="submit" />
</form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.
</footer>
</body>
</html>
I have not yet created statusServlet.java
I will seperate department into two parts like below.
1) Department from which the file is being originated
2) Current location of file.
I will use the file origin department for generating the filenumber and will update the current location separately (Initially the current location will be same as origin department).
If anyone having more effective way than this, then I will accept that too.
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
package com.gtlsoftware;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.PreparedStatement;
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class MenuServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MenuServlet()
{
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Connection con;
ResultSet rs;
PreparedStatement pst;
//INSERT INTO DATABASE
PrintWriter pw=response.getWriter();
pw.print("hello");
String name=request.getParameter("name");
pw.println(name);
System.out.println(name);
String description = request.getParameter("description");
String image = request.getParameter("image");
String category=request.getParameter("category");
String unit=request.getParameter("unit");
String units=request.getParameter("units");
String price=request.getParameter("price");
byte[] b=null;
try
{
con=MyConnection.getConnection();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
if (!item.isFormField())
{
b = item.get();
}
}
pst=con.prepareStatement("insert into menu(menu_name,description,image,category,unit,units,price) values(?,?,?,?,?,?,?)");
pst.setString(1, name);
pst.setString(2, description);
pst.setBytes(3,b);
pst.setString(4, category);
pst.setString(5, unit);
pst.setString(6,units);
pst.setString(7,price);
pst.executeUpdate();
System.out.println("inserted successfully");
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (FileUploadException e)
{
System.out.println(e.getMessage());
// TODO: handle exception
}
}
}
I did coding image is inserted .but when i am use in form enctype="multipart/form-data then null values goes to next page i also add commons logging and file upload jar and if i remove enctype then value inserts but image not insert am taking image in longblob
and jsp page is menu.jsp
<body>
<center>
<div>
<table border="0" cellspacing="10" cellpadding="5" style="text-align: left">
<tr>
<td><%# include file="header.jsp" %></td>
</tr>
<tr>
<td>
<div class="main_div">
<fieldset>
<form name="menuFrm" action="MenuServlet" method="post" onsubmit="reurn(validate())" enctype="multipart/form-data" >
<table cellspacing="7" cellpadding="2" align="center" border="0" style="font-family: sans-serif;font-weight: normal;font-size: medium">
<tr>
<td colspan="2" style="background-color: black;color: white;font-family: Centaur;font-size: 20px;text-align: center;">
<h4>Menu</h4>
</td>
</tr>
<tr>
<td>Menu Id :</td>
<td><input type="text" name="menuId" id="MenuId" value="<%=++cnt %>" tabindex="1" size="30%" placeholder="enter menu name"></td>
</tr>
<tr>
<td>Name :</td>
<td><input type="text" name="name" id="name" value="hdsuidd" tabindex="1" size="30%" placeholder="enter menu name"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="6" cols="30" name="description" size="30%" tabindex="4" id="description" size="30%" placeholder="enter description"></textarea></td>
</tr>
<tr>
<td>Image:</td>
<td><input type="file" class="txtset" id="image" name="image" tabindex="5"/></td>
</form>
</tr>
<tr>
<td>Category:</td>
<td>
<select id="category" class="txtset" name="category">
<option selected="selected">select category</option>
<option value="veg">Veg</option>
<option value="non-veg">Non-Veg</option>
</select>
</td>
</tr>
<tr>
<td>Units:</td>
<td><input type="text" name="unit" id="unit" class="txtset" tabindex="6" width="10%" onkeyup="myNum()"/>
<select id="units" name="units">
<option selected="selected">select units</option>
<option value="kg">KG</option>
<option value="gram">GRAM</option>
<option value="unit">Unit</option>
</select>
</td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" class="txtset" id="price" onkeyup="myNum()" tabindex="7" width="30%" height="10%"> /-Rs.</td>
</tr>
<tr>
<td><font color='white'> <DIV id="une" style="background-color: red;font-weight: bold;"> </DIV> </font></td>
</tr>
<tr>
<td><input type="submit" value="Add" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="valid();check()"/></td>
<td><input type="reset" value="Cancel" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="reset()"/></td>
</tr>
<tr>
<td colspan="2">
<br>
<br>
<a href="edit.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;">
<u>Edit</u></a>
<a href="update.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;">
<u>Update</u></a>
<a href="delete.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px";>
<u>Delete</u></a>
</td>
</tr>
</table>
</form>
<%
con.close();
%>
</fieldset>
</div>
</td>
</tr>
<tr>
<td><%# include file="footer.jsp" %></td>
</tr>
</table>
</div>
</center>
</body>
You are using wrong code to receive and insert image in your servlet. Image is always send as multipart data to a servlet so use of form enctype="multipart/form-data is correct. But in your servlet you are receiving image as parameter which is wrong. Image should be received as part data like this:-
Part filePart=request.getPart("image");
Then we retrieve file path from part data like this :-
String filePath = filePart.getSubmittedFileName();
After we retrieve image file from path and then convert it to File input stream so it can be inserted as binary data :-
File image = new File(filePath);
FileInputStream fis = new FileInputStream(image);
After it the correct statement to insert image is this :-
pst.setBinaryStream (3, fis, (int) image.length() );
Here 3 is the column value of longblob data in your table. After these modifications in your servlet, I am sure all your form data will be inserted successfully in your database. And yes, remove these following lines from your code :-
pw.print("hello");
pw.println(name);
System.out.println("inserted successfully");
Create two Html pages named SuccessPage.html and FailurePage.html which print Success and failure messages to console and code last line of insert operation like this :-
int rowCount=pst.executeUpdate();
if(rowCount>0){
response.sendRedirect("SuccessPage.jsp");
}
else{
response.sendRedirect("FailurePage.jsp");
}
P.S. : Replace your mulitpart config line :-
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
by this :-
#MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024*2, maxFileSize=1024*1024*10, maxRequestSize=1024*1024*50)
If this answer helps you, accept it by clicking right mark on top left corner of it. If not, let me know. All the best :)
Here is your modified JSP :-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<center>
<div>
<table border="0" cellspacing="10" cellpadding="5" style="text-align: left">
<%--<tr>
<td><%# include file="header.jsp" %></td>
</tr>--%>
<tr>
<td>
<div class="main_div">
<fieldset>
<form name="menuFrm" action="SOQ52" method="post" onsubmit="reurn(validate())" enctype="multipart/form-data" >
<table cellspacing="7" cellpadding="2" align="center" border="0" style="font-family: sans-serif;font-weight: normal;font-size: medium">
<tr>
<td colspan="2" style="background-color: black;color: white;font-family: Centaur;font-size: 20px;text-align: center;">
<h4>Menu</h4>
</td>
</tr>
<tr>
<td>Menu Id :</td>
<td><input type="text" name="menuId" id="MenuId" tabindex="1" size="30%" placeholder="enter menu name"></td>
</tr>
<tr>
<td>Name :</td>
<td><input type="text" name="name" id="name" tabindex="1" size="30%" placeholder="enter menu name"></td>
</tr>
<tr>
<td>Description:</td>
<td><textarea rows="6" cols="30" name="description" size="30%" tabindex="4" id="description" size="30%" placeholder="enter description"></textarea></td>
</tr>
<tr>
<td>Image:</td>
<td><input type="file" class="txtset" id="image" name="image" tabindex="5"/></td>
</form>
</tr>
<tr>
<td>Category:</td>
<td>
<select id="category" class="txtset" name="category">
<option selected="selected">select category</option>
<option value="veg">Veg</option>
<option value="non-veg">Non-Veg</option>
</select>
</td>
</tr>
<tr>
<td>Units:</td>
<td><input type="text" name="unit" id="unit" class="txtset" tabindex="6" width="10%" onkeyup="myNum()"/>
<select id="units" name="units">
<option selected="selected">select units</option>
<option value="kg">KG</option>
<option value="gram">GRAM</option>
<option value="unit">Unit</option>
</select>
</td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" class="txtset" id="price" onkeyup="myNum()" tabindex="7" width="30%" height="10%"> /-Rs.</td>
</tr>
<tr>
<td><font color='white'> <DIV id="une" style="background-color: red;font-weight: bold;"> </DIV> </font></td>
</tr>
<tr>
<td><input type="submit" value="Add" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="valid();check()"/></td>
<td><input type="reset" value="Cancel" style="font-family: sans-serif;font-size: large;text-align: center;width" onclick="reset()"/></td>
</tr>
<tr>
<td colspan="2">
<br>
<br>
<a href="edit.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;">
<u>Edit</u></a>
<a href="update.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px;">
<u>Update</u></a>
<a href="delete.jsp" style="color: black;text-align:center;font-family: Centaur;font-size: 20px";>
<u>Delete</u></a>
</td>
</tr>
</table>
</form>
</fieldset>
</div>
</td>
</tr>
<%--<tr>
<td><%# include file="footer.jsp" %></td>
</tr>--%>
</table>
</div>
</center>
</body>
</html>
and this is your servlet :-
import java.util.List;
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 org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.FileUploadException;
//import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.PreparedStatement;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.Part;
#MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB
maxFileSize=1024*1024*10, // 10MB
maxRequestSize=1024*1024*50) // 50MB
public class SOQ52 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Connection con;
ResultSet rs;
PreparedStatement pst;
//INSERT INTO DATABASE
PrintWriter out=response.getWriter();
//pw.print("hello");
String name=request.getParameter("name");
//pw.println(name);
System.out.println(name);
String description = request.getParameter("description");
//String image = request.getParameter("image");
String category=request.getParameter("category");
String unit=request.getParameter("unit");
String units=request.getParameter("units");
String price=request.getParameter("price");
//byte[] b=null;
Part filePart=request.getPart("image");
String filePath = filePart.getSubmittedFileName();
File image = new File(filePath);
FileInputStream fis = new FileInputStream(image);
/*
try
{
//con=MyConnection.getConnection();
//DiskFileItemFactory factory = new DiskFileItemFactory();
//ServletFileUpload sfu = new ServletFileUpload(factory);
//List items = sfu.parseRequest(request);
//Iterator iter = items.iterator();
//while (iter.hasNext())
{
//FileItem item = (FileItem) iter.next();
//if (!item.isFormField())
{
//b = item.get();
}
}
pst=con.prepareStatement("insert into menu(menu_name,description,image,category,unit,units,price) values(?,?,?,?,?,?,?)");
pst.setString(1, name);
pst.setString(2, description);
pst.setBytes(3,b);
pst.setString(4, category);
pst.setString(5, unit);
pst.setString(6,units);
pst.setString(7,price);
pst.executeUpdate();
System.out.println("inserted successfully");
}
//catch (SQLException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
}
//catch (FileUploadException e)
{
//System.out.println(e.getMessage());
// TODO: handle exception
}*/
response.setContentType("text/html;charset=UTF-8");
try {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> Name : " +name+"</h1>");
out.println("<h1> Desc : " +description+"</h1>");
out.println("<h1> Category : " +category+"</h1>");
out.println("<h1> Unit : " +unit+"</h1>");
out.println("<h1> Units : " +units+"</h1>");
out.println("<h1> Price : " +price+"</h1>");
out.println("<h1> Image filePath : " +filePath+"</h1>");
out.print("");
out.println("</body>");
out.println("</html>");
}catch(Exception ex){
}
}
}
Run it and check it yourself. Nothing is giving null.
I am working with AngularJs with spring mvc module. I am uploading files from UI and displaying the file in UI in table format. When i upload for the first time its working fine but when I upload for the second time my code is not working. If i refresh the page and upload the file that its working fine. Please help me where I went wrong. I need to upload files multiple times without page refresh.
JSP COde:
<%# 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>
<title>Angular JS Custom Directives</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "StudentController">
<table width="100%" border="0" cellspacing="5" cellpadding="0" id="uploadFile">
<tr>
<td align="left" valign="middle">Upload File:</td><br/>
<td align="left" valign="middle">
<input name="file2" id="file2" type="file" file-model="file2"/><br/>
</td>
<td><input type="button" value="Submit" ng-click="uploadFormData();"></td>
</tr>
<tr>
<td align="left" valign="middle">
</td>
</tr>
</table>
<table border="1" cellspacing="0" cellpadding="4">
<tr ng-repeat="row in rows">
<td ng-repeat="column in row.split(',')">{{column}}</td>
</tr>
</table>
<mydirc></mydirc>
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('StudentController', function($scope,$http)
{
$scope.uploadFormData= function()
{
var oMyForm = new FormData();
oMyForm.append("file",file2.files[0]);
$http({
method: 'POST',
url: 'uploadFile',
headers: {'Content-Type': undefined},
data: oMyForm,
transformRequest: function(response, headersGetterFunction) {
return response;
}
}).success(function(data, headers)
{
$scope.rows=data.list;
});
}; //end of click
});
</script>
</body>
</html>
Controller :
#RequestMapping(value = "/uploadFile")
public #ResponseBody void upLoadFile(HttpServletRequest request,HttpServletResponse response,
#RequestParam(value = "file") MultipartFile file) {
JSONObject object = new JSONObject();
StringBuilder result=null;
try
{
System.out.println(file.getOriginalFilename());
InputStream in=file.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
List<String> ite=new ArrayList<String>();
object.put("list", ite);
response.getWriter().write(object.toString());
} catch (IOException e) {e.printStackTrace();
} catch (JSONException e) {e.printStackTrace();
}
}
Based on your code, please find the pseudo code for a directive with isolated scope and a separate controller handling the file upload.
Code for HTML:
<div ng-app = "mainApp" ng-controller = "StudentController">
<table width="100%" border="0" cellspacing="5" cellpadding="0" id="uploadFile">
<tr>
<td align="left" valign="middle">Upload File:</td><br/>
<td align="left" valign="middle">
<input name="file2" id="file2" type="file" file-model="file2"/><br/>
</td>
<td><input type="button" value="Submit" ng-click="uploadFormData();"></td>
</tr>
<tr>
<td align="left" valign="middle">
</td>
</tr>
</table>
<list-files rows="fileList"></list-files>
</div>
Code for the directive:
angular.module("mainApp").directive('listFiles', function() {
var template = '<table border="1" cellspacing="0" cellpadding="4">';
template += '<tr ng-repeat="row in rows">';
template += '<td ng-repeat="column in row.split(',')">{{column}}</td>';
template += '</tr>';
return {
restrict: 'E',
replace: true,
template : template,
scope: {
rows: '='
}
};
});
Pseudo code for StudentController:
angular.module("mainApp").controller("StudentController", function($scope, $http){
$scope.fileList = [];
$scope.uploadFormData = function() {
// Code to upload file.
// Ex:
$http(...).success(function(response){
$scope.fileList = response.list;
});
};
});
Hope this helps to solve the issue.
hi all I have a LoginServlet that has the functionality to log in a user however I have a jsp page with the styling I'd to use. I am unsure how I can use the functionality from my LoginServlet in my login.jsp
here is the entirety of my code for the LoginServlet, I am aware I have coded to display a page but I need to use this jsp page to display. This is a uni assignment I have been given and it's part of the requirement that we use JSP for display.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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 javax.servlet.RequestDispatcher;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
private void sendLoginForm(HttpServletResponse response,
boolean withErrorMessage)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<CENTER>");
if (withErrorMessage)
out.println("Login failed. Please try again.<BR>");
out.println("<BR>");
out.println("<BR><H2>Login Page</H2>");
out.println("<BR>");
out.println("<BR>Please enter your user name and password.");
out.println("<BR>");
out.println("<BR><FORM METHOD=POST>");
out.println("<TABLE>");
out.println("<TR>");
out.println("<TD>User Name:</TD>");
out.println("<TD><INPUT TYPE=TEXT NAME=uniid></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD>Password:</TD>");
out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");
out.println("</TR>");
out.println("<TR>");
out.println("<TD ALIGN=RIGHT COLSPAN=2>");
out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");
out.println("</TR>");
out.println("</TABLE>");
out.println("</FORM>");
out.println("</CENTER>");
out.println("</BODY>");
out.println("</HTML>");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendLoginForm(response, false);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uniid = request.getParameter("uniid");
String password = request.getParameter("password");
if (login(uniid, password)) {
/*RequestDispatcher rd =
request.getRequestDispatcher("AnotherServlet");
rd.forward(request, response); */
response.sendRedirect("home_student.jsp");
}
else {
sendLoginForm(response, true);
}
}
boolean login(String uniid, String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
Statement s = con.createStatement();
String sql = "SELECT uniid FROM user" +
" WHERE uniid='" + uniid + "'" +
" AND password='" + password + "'";
ResultSet rs = s.executeQuery(sql);
if (rs.next()) {
return true;
}
rs.close();
s.close();
con.close();
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
catch (SQLException e) {
System.out.println(e.toString());
}
catch (Exception e) {
System.out.println(e.toString());
}
return false;
}
}
here is my jsp page
<%# 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>Mars University Lab System</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>
<body>
<jsp:include page="header.jsp"/>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<div id = "centrecontent">
<table border="0" cellpadding="2">
<tr>
<td width="500px" align="center">
<br>
<font size="5">Welcome to <i>The Department of <br>Rocket Science</i> Lab System<br></font>
<br>
For <b>Students</b> you can enrol in labs<br> and manage the labs you're enrolled in.<br><br>
For <b>Tutors</b> you can view the labs<br> you're teaching and record attendence.<br><br>
For <b>Lecturers</b> you can create and<br> manage lab classes, register Tutors and<br> assign those Tutors to labs.<br><br>
</td>
<td width="500px">
<table border="0" align="center">
<tr>
<td align="center">
<table border="0" align="center">
<tr> <br><br><b>Existing Member? <br>Sign In Here!</b><br>
<td align="right">
<form name ="login" METHOD=POST ACTION="SaveSession.jsp">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pword"/><br />
<input type=SUBMIT value="Login" name="Submit" />
</td>
</tr>
</table>
<br><br><br><br>
<form name="search_cat_bar" method="get" action="">
<input type="hidden" name="dff_view" value="grid">
Search:<input type="text" name="dff_keyword" size="30" maxlength="50"> <br>in
<select name="dff_cat1num" size="1">
<option value="-1">All Subjects
<option value="-2">--------------
<option value="101">CSE2ICE
<option value="193">CSE3PRA
<option value="193">CSE3PRB
<option value="193">CSE3WAE
</select>
<input type="submit" value="Find">
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table>
<tr>
</tr>
</table>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
I'd like the login.jsp page to call my LoginServlet for the login functions.
You can call servlet by this way:
web.xml
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>//full class path
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
login.jsp
<form name="login" action="<%=request.getContextPath()%>/servlet/login" method="post">
</form>
Servlet:
Login check and also you can send just error message to login page and display message like,
res.sendRedirect(req.getContextPath()+"/webpages/login.jsp?login=failed");
And in login.jsp you can retrieve parameter request.getParameter("login") and display proper message
add action in the html form tag.
action is LoginServlet URL.
It's easier to have the standard way of doing this:
Have jsp page with a form, to receive inputs from the user.
Have a servlet to process the data.
If there is a problem, set an error message and redirect the user to the login page. Otherwise redirect him to the destination.
Do not forget to set your form's action the address of your servlet.