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.
Related
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:
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.
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.
This question already has answers here:
NullPointerException, when reading HTML input [duplicate]
(3 answers)
Closed 6 years ago.
home.jsp
<form method="POST" action="Initiater.do">
<table>
<tr>
<td>
Internal Diameter from FlowAss:
</td>
<td>
<input type="text" id="Id" />
</td>
<td>
Depth:
</td>
<td>
<input type="text" id="Depth" />
</td>
<td>
Units:
</td>
<td>
<select>
<option value="ft">feet</option>
<option value="mts">meters</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
Home.java
public class Home extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
System.out.println("in Post");
String id = (String) request.getParameter("Id");
String depth = request.getParameter("Depth");
/*double id =Double.parseDouble(request.getParameter("Id"));
double depth =Double.parseDouble(request.getParameter("Depth"));*/
System.out.println("Id"+id);
System.out.println("Depth"+depth);
}
the servlet Home.java's doPost method is called, the values id and depth are returning nulls when I debug can anyone help me out with this.
Add name attribute to the input tag.
Change
<input type="text" id="Depth" />
<input type="text" id="Id" />
To
<input type="text" id="Depth" name="Depth"/>
<input type="text" id="Id" name="Id"/>
Request.getParameter gets data by name attribute and not id
String isno1=request.getParameter("isbn");
String bktitle2=request.getParameter("booktitle");
String authr3=(String) request.getParameter("author");
System.out.println(isno1+bktitle2+authr3);
Enumeration paramaterNames = request.getParameterNames();
when i am taking the parameters in servlet then i am gettin my values as 'null'
what wrong am i doing.
this is the way i am setting the parameters...
from a jsp page using script tag
<script type="text/javascript">
function getHTTPObject()
{
var httpobject;
if(!httpobject && typeof(XMLHttpRequest) != 'undefined')
{
try{
httpobject=new XMLHttpRequest();
}
catch(e){
xmlhttp=false;
}
}
return httpobject;
}
var httpob=getHTTPObject();
function handleHttpResponse(){
if(httpob.readyState==4){
//alert("sd");
var result=httpob.responseText;
alert(result);
/* document.write("hi your book is submitted !!!!!"); */
}
}
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
httpob.open("POST","addbook",true);
httpob.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close");
/* httpob.setRequestHeader("Content-type","application/x-www-from-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close"); */
httpob.onreadystatechange=handleHttpResponse;
httpob.send();
}
</script>
and this my form.....
<form style="margin: 100px;" name="mayurform">
<table align="center">
<tr>
<td align="center">ISBN NO.</td>
<td><input align="middle" type="text" size="20" name="id" id="isbn">
</tr>
<tr>
<td align="center">Book-Title</td>
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
</td>
</tr>
<tr>
<td align="center">Author</td>
<td><input align="middle" type="text" size="20" name="pwd" id="author">
</tr>
<tr>
<td><input align="middle" type="button" size="20" name="Add-Book" onclick="auth()">
</tr>
</table>
</form>
You are fetching parameters with ID's you should give Names.
for example
String isno1=request.getParameter("isbn"); //here is isbn is id
you should write
<input align="middle" type="text" size="20" name="id" id="isbn">
String isno1=request.getParameter("id");-----------^
and also
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
<td><input align="middle" type="text" size="20" name="pwd" id="author">
both inputs have the same **name** please check it
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html
Use like below ajax send() to send data
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
.......
...
httpob.send(params);//change is here
}
call httpob.send(),passing in the parameters that will be sent (without the "?" prefix).