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.
Related
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.
Here i've have 2 servlets
#WebServlet("/Login")
public class Login extends HttpServlet {
.........
.........
}
#WebServlet("/Create")
public class Create extends HttpServlet {
.........
.........
}
And a HTML page like this.
<form name="loginForm" method="post" action="Login">
<table width="20%" bgcolor="0099CC" align="center">
<tr>
<td colspan=2>
<center>
<font size=4><b>HTML Login Page</b></font>
</center>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" size=25 name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="Password" size=25 name="password"></td>
</tr>
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Login"></td>
</tr>
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Create profile"></td>
</tr>
</table>
</form>
I want to redirect to Create servlet when the user clicks on create profile. Can anyone help me with this?
You need to select the action based on the button which is clicked. You can do it using JavaScript. Given below is the minimal, working example which you can extend as per your requirement:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
function check(form, button){
if(button.id=='login'){
form.action="Login";
}else if(button.id=='create'){
form.action="Create";
}
form.submit();
}
</script>
<title>Insert title here</title>
</head>
<body>
<form name="loginForm" method="post">
<table width="20%" bgcolor="0099CC" align="center">
<tr>
<td colspan=2>
<center>
<font size=4><b>HTML Login Page</b></font>
</center>
</td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" size=25 name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="Password" size=25 name="password"></td>
</tr>
<tr>
<td><input type="button" id="login" onclick="check(this.form,this)"
value="Login"></td>
</tr>
<tr>
<td><input type="button" id="create" onclick="check(this.form,this)"
value="Create profile"></td>
</tr>
</table>
</form>
</body>
</html>
Login.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Login")
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Login");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
Create.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Create")
public class Create extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Create");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
You have one form and you want it to go to two different servlet. You can't do that. If you want to goto login servlet first and then goto create servlet. You can do that view requestDispatcher or httpServletresponse.sendRedirect()
RequestDispatcher rd=request.getRequestDispatcher("servlet Name")
rd.forward(request, response);
or by
response.sendRedirect("/url");
Or if you dont want to go the login servlet at all and directly want to go to create then use two forms one for your Login and another one for your Create Profile.
<form name="loginForm" method="post" action="Create">
<tr>
<td><input type="submit" onclick="return check(this.form)" value="Create profile"></td>
</tr>
I am creating a Tic-Tac-Toe program using HTML and Java. After user input, the server goes to the servlet, which puts the value back into the array and then redirects the server back to the HTML page.
HTML code (with Tic-Tac-Toe table that needs values to go in the entries):
<form action="servlet1" method="get">
<br><br> <table>
<tr>
<td><input type="radio" name="input" value="0"> </td>
<td><input type="radio" name="input" value="1"> </td>
<td><input type="radio" name="input" value="2"> </td>
</tr>
<tr>
<td><input type="radio" name="input" value="3"> </td>
<td><input type="radio" name="input" value="4"> </td>
<td><input type="radio" name="input" value="5"> </td>
</tr>
<tr>
<td><input type="radio" name="input" value="6"> </td>
<td><input type="radio" name="input" value="7"> </td>
<td><input type="radio" name="input" value="8"> </td>
</tr>
</table>
<br><input type="submit" value="Turn Completed" />
</form>
Java Servlet code:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/servlet1")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] board = new String[9];
for (int i = 0; i < 9; i ++) {
board[i] = "<input type=\"radio\" name=\"input\" value=\"" + i + "\">";
}
int loc = Integer.parseInt(req.getParameter("input"));
board[loc] = "X";
resp.setStatus(resp.SC_MOVED_TEMPORARILY);
resp.setHeader("Location", "index.html");
}
}
How do I get the value of board in my Java code to transfer to the HTML page each time and render Xs based on user input? Is there any way to access board in the HTML program and use board[0], board[1] etc to fill the table values in the HTML code?
You have to form a response, here is a simple example:
public void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
// set content type
response.setContentType("text/html");
// get response writer
PrintWriter writer = response.getWriter();
// build HTML code
String htmlResponse = "<html>";
htmlResponse += "<h2>This is my Response example:</h2>";
htmlResponse += "Some Text as an example.";
htmlResponse += "</html>";
// return response
writer.println(htmlResponse);
}
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.
using servlet code i inserted the data to database.
and i want to retrieve that data to the same html page.....i want the servlet code
in the same class for inserting and editing. i am using eclipse.....so plz help me frnds.....i am new to java and
my knowledge is close to nothing
html page
<!DOCTYPE html>
<html>
<head>
<title>PATIENT</title>
<style type="text/css">
input, textarea,select {
background-color : lightgray;
}
table
{
border: 2px solid gray;
}
</style>
</head>
<body bgcolor="#DDDDDD">
<script>
function myFunction()
{
var reg_no=prompt("Please enter your Register No", "")
}
</script>
<p align ="center"><b>PATIENT</b></p><br>
<form method="post" name ="patientForm" action="patientDemo">
<table align="center" cellpadding="2" cellspacing="2">
<tr>
<td>
<font color="maroon">Register Number</font>
</td>
<td colspan="1">
<input type="text" maxlength="15" name="regs_numb" required>
</td>
<td>
<font color="maroon">PatientId</font>
</td>
<td colspan="2">
<input type="text" maxlength="10" size="18" name="pat_Id" required>
</td>
<td>
<font color="maroon">Patient Type</font>
</td>
<td colspan="2">
<input type="text" size="3" maxlength="3" name="pat_Type">
</td>
<tr>
<td>
<font color="maroon">Patient Name</font>
</td>
<td colspan="4">
<input type="text" maxlength="50" size="53" name="pat_Name">
</td>
<td>
<font color="maroon">Age</font>
</td>
<td>
<input type="text" maxlength="3" size="3" name="age">
<select name="age_units">
<option value="years">Years</option>
<option value="months">Months</option>
<option value="days">Days</option>
</select>
</td>
</tr>
<tr>
<td>
<font color="maroon">Sex</font>
</td>
<td>
<select name="sex">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</td>
<td>
<font color="maroon">Package</font>
</td>
<td>
<input type="text" maxlength="10" SIZE="18" name="package">
</td>
</table>
<br>
<table align="center" cellpadding="2">
<tr>
<td>
<input type="submit" value="save" id="save"/>
<td>
<input type="button" onclick="myFunction()" value="edit" id="edit"/>
</td>
<td>
<input type="button" value="delete" id="delete">
</td>
<td>
<input type="reset" value="cancel" id="cancel"/>
</td>
<td>
<input type="button" value="exit" id="exit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
PatientDemo.java
package patientDemo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PatientDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String a=request.getParameter("regs_numb");
String b=request.getParameter("pat_Id");
String c=request.getParameter("pat_Type");
String d=request.getParameter("pat_Name");
String e=request.getParameter("age");
String f=request.getParameter("age_units");
String g=request.getParameter("sex");
String h=request.getParameter("package");
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms","root","root");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into patient(p_reg_no_v,p_patient_id_v,p_patient_type_v,p_patientname_v,p_age_s,p_ageunit_v,p_sex_v,p_package_v) values (?,?,?,?,?,?,?,?)");
ps.setString(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.setString(4,d);
ps.setString(5,e);
ps.setString(6,f);
ps.setString(7,g);
ps.setString(8,h);
ps.execute();
out.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
}
}
Name all your buttons something like "action". At the top of doPost() check which button was pressed by calling request.getParameter("action") like you did for the other fields.
Branch your logic depending on the value. For "save" you do what you are already doing. For "delete" you would do delete SQL instead. If it's not set, do nothing.
After all that, have the code fall though to query the database and render the page.
(edited to add example)
In the HTML, give your buttons a name like this
<input type="submit" value="save" id="save" name="action"/>
Also make place holders for your data like this
<input type="text" maxlength="15" name="regs_numb" required value="${regs_numb}">
In java do what i described above
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("save")) {
saveData(request);
} else if (action.equals("delete")) {
deleteData(request);
}
renderPage(request, response);
}
private void renderPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// load your html file from disk
String html = loadHtml(filename);
// load the last data you were just editing
String a=request.getParameter("regs_numb") // or whatever you primary key field id
Map<String,String> model = loadSqlData(a);
// inject the data into your html
for(Entry<String,String> entry : model.entrySet()) {
html = html.replace("${" + entry.getKey() +"}", entry.getValue());
}
// send the page to the browser
response.getWriter().println(html);
response.flush();
}
You'll need to implement those methods for saveData, deleteData, loadHtml, and loadSqlData.
For loadSqlData have it return a HashMap where the key is all the fields you put placeholder for like ${regs_numb), and the value is from the database.
If this seems like a lot of work, it is. That's why everyone is recommending using a framework that does 90% of this for you.