text field in file upload servlet, Java - java

In my java application i am uploading multiple files using java servlet.
All things works fine until i added extra text field in my form.
I am getting null document when i add text field.
Here is my code:-
JSP Form:-
<form action="upload/servlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Upload File: </td>
<td><input type="file" name="file" multiple/>
</td>
<td style="color: red; font-style: italic;"><form:errors
path="file" />
</td>
</tr>
<tr>
<td>Generate Key</td><td> </td>
<td><input type="button" value="Change Key"/>
</td>
<td>${key}</td>
</tr>
<tr>
<td>Zip Code</td><td> </td>
<td><input type="text" value="100001" name="zipcode"/>
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Upload" />
</td>
<td> </td>
</tr>
</table>
</form>
Here is my servlet:-
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Multipart content expected!");
}
ModelMap model = new ModelMap();
try {
#SuppressWarnings("unchecked")
List<FileItem> files = this.upload.parseRequest(req);
String userName=req.getSession().getAttribute("username").toString();
String fileName;
String contentType;
byte[] content;
System.out.print("Zipcode is "+req.getParameter("zipcode"));
for(FileItem item : files) {
if(item.isFormField()){
fileName = item.getName();
contentType = item.getContentType();
content = item.get();
String id=this.indexDocument(fileName, contentType, content,userName,req);
model.put(id, fileName);
System.out.println("Done for "+fileName+ " id "+id);
}
}
} catch (FileUploadException e) {
System.out.println("Error FileUploadException: "+e.getMessage());
throw new ServletException(e);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error "+e.getMessage());
}
req.setAttribute("message", model);
req.getSession().setAttribute("tmpRetMessage", model);
// RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/success.do");
//dispatcher.forward(req, resp);
resp.sendRedirect("../success.do");
}
If i add two text fields then getting null document error two times. If i add three times then getting error three times.

Here form enctype type multipart (enctype="multipart/form-data"). So request.getParameter() value will be null. So you need to process file field and regular fields means other than file like text, radio, etc separately.
see for more how to get request parameters

Related

doPost method of servlet class not giving required result

I've created a jsp login page form and I've put my logic inside the doPost(). But seems it is not working.
Even the System.out.println statement result in doPost() method is not shown in the console.
JSP page::(LogIn.jsp)
<body>
<form method="post" action="LogIn">
<table>
<tr>
<td colspan=2 align="center"
style="font-weight: bold; font-size: 20pt;" align="center"><b>User
Login Form</b></td>
</tr>
<tr>
<td colspan=2></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" id="txtUserName" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="txtpassword" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnSubmit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
Servlet class (LogIn.java)
#WebServlet("/LogIn")
public class LogIn extends HttpServlet {
private static final long serialVersionUID = 1L;
public LogIn() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
String UserName = request.getParameter("txtUserName");
String Password = request.getParameter("txtpassword");
System.out.println(UserName);
System.out.println(Password);
if (UserName == "Servlet" && Password == "admin") {
response.sendRedirect("Home.jsp");
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
{
System.out.println("no values");
}
else
System.out.println(paramValue);
} else {
// Read multiple valued data
System.out.println(".....");
for (int i = 0; i < paramValues.length; i++) {
System.out.println( paramValues[i]);
}
}
}
}
}
Web.xml file
<servlet>
<servlet-name>LogIn</servlet-name>
<servlet-class>LogIn</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogIn</servlet-name>
<url-pattern>/LogIn</url-pattern>
</servlet-mapping>
request.getParameter("txtUserName");
searches for the name = "txtUserName" attribute in input tag and similarly for password field as well, which is not present, modify the JSP code as below and it should work:
<body>
<form method="post" action="LogIn">
<table>
<tr>
<td colspan=2 align="center"
style="font-weight: bold; font-size: 20pt;" align="center"><b>User
Login Form</b></td>
</tr>
<tr>
<td colspan=2></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" id="txtUserName" name="txtUserName"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="txtpassword" name="txtpassword" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnSubmit" value="Submit" /></td>
</tr>
</table>
</form>
</body>

Can not insert data into two tables spring mvc

Im using Spring mvc and facing the problem about inserting data into two tables, my target is inserting data into 2 tables from 1 jsp (1 form)
I have two 2 tables:
1.Cars
Id
Name
CityId(FK)
2.City
Id
Name
this is my controller:
#RequestMapping(value="/CreateCar", method = RequestMethod.GET)
public ModelAndView getCreateCarPage(ModelMap model) throws ServletException, IOException {
try {
Car myCar = new Car();
City city = new City();
myCar.setCity(city);
model.addAttribute("city", city);
model.addAttribute("createCar", myCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("testForm");
}
#RequestMapping(value="/CreateCar", method = RequestMethod.POST)
public ModelAndView setCreateCarPage(ModelMap model,
#ModelAttribute("createCar") Car createCar) throws SQLException, Exception {
try {
carService.createCar(createCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("successProcess");
}
}
JSP:
<form:form modelAttribute="createCar" method="POST" commandName="createCar" action="/CreateCar" enctype="multipart/form-data">
<fieldset style="width:300px">
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td>
<label>Name of car</label>
<form:input path="name" id="name"/>
</td>
<td>
<label>Name of city</label>
<form:input path="city.name" />
</td>
</tr>
<tr>
<td><input class="btn btn-danger" type="submit" value="Inser New" style="width:100px;" /></td>
</tr>
</table>
</fieldset>
With above source, it just insert name of car success but can not insert name of city
Log massages:
SqlExceptionHelper - Column 'city_id' cannot be null
How can I fix this problem ? thank so much !

Cannot call getWriter(), getOutputStream() already called [duplicate]

This question already has answers here:
getOutputStream() has already been called for this response
(15 answers)
Servlets in java - both getWriter() and getOutputStream()
(3 answers)
getting error "getOutputStream() has already been called for this response"
(1 answer)
JSP : getOutputStream() has already been called for this response
(2 answers)
Closed 2 years ago.
I have a program which uses spring mvc. I wrote two controllers which first one is for importing data and second one is for generating reports. I have a problem with generating controller. When user clicks generate button I want to generate report, save report on server hard disk and send report to user. When I am trying to save report on hard disk I've got Illegal state exception: Cannot call getWriter(), getOutputStream() already called. I searched for solution but I cannot find matched answer. This is my generator controller code:
#RequestMapping(value = "/generate", method = RequestMethod.POST)
public String generateReport(
Model model,
#Valid #ModelAttribute("reportProperties") ReportProperties reportProperties,
BindingResult result, HttpServletResponse response) {
if (result.hasErrors()) {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
return "import";
}
//Walidacja dat. Mozna przeniesc na validator
if(reportProperties.getEndDate().compareTo(reportProperties.getStartDate()) < 0){
model.addAttribute("logMessage", "Data końcowa jest wcześniejsza od poprzedniej");
return "import";
}
XSSFWorkbook report = null;
if (reportProperties.getReportType().equalsIgnoreCase("tv")) {
report = tvReportGenerator.generate(reportProperties);
} else if (reportProperties.getReportType().equalsIgnoreCase("prod")) {
report = prodReportGenerator.generate(reportProperties);
} else {
report = totalReportGenerator.generate(reportProperties);
}
if (report != null) {
saveReportOnHardDrive(report);
sendReportToUser(report, response);
} else {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
}
return "import";
}
private void saveReportOnHardDrive(XSSFWorkbook report) {
try {
Resource resource = new ClassPathResource("/general.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String path = props.getProperty("saveFilePath");
FileOutputStream out = new FileOutputStream(new File(path
+ new Date() + ".xlsx"));
report.write(out);
out.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void sendReportToUser(XSSFWorkbook report,
HttpServletResponse response) {
try {
response.setContentType("application/xlsx");
response.setHeader("Content-Disposition",
"attachment; filename=generate.xlsx");
report.write(response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I tried some solution with closing and flushing response OutputStream but it did not work.
This is my import.jsp file:
<body>
<div id="Container">
<h1>Mediaplany GigaShopping instrukcja</h1>
<h2>Import Mediaplanu pobierz szablon</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importMediaplan">
<input type="file" name="mediaplanFile"/>
<input type="submit" value="Prześlij plik"/>
</form>
<h2>Import cennika aktualny cennik</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importPriceList">
<input type="file" name="pricelistFile">
<input type="submit" value="Prześlij plik">
</form>
<h2>Generowanie raportów</h2>
<form:form method="POST" action="/GigaShopping/generate" commandName="reportProperties">
<table>
<tr>
<td>Typ raportu:</td>
<td>
<label><form:radiobutton path="reportType" value="tv"/> M/S TV</label>
<label><form:radiobutton path="reportType" value="prod"/> M/S PROD</label>
<label><form:radiobutton path="reportType" value="total"/> M/S TOTAL</label>
</td>
</tr>
<tr>
<td>Stacja</td>
<td>
<form:select path="tvName">
<form:options items="${televisionsList}"/>
</form:select>
</td>
</tr>
<tr>
<td>Od</td>
<td><form:input type="date" path="startDate" id="startDatePicker"/></td>
</tr>
<tr>
<td>Do</td>
<td><form:input type="date" path="endDate" id="endDatePicker"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Generuj"></td>
</tr>
</table>
</form:form>
<form:form method="POST" action="/GigaShopping/requestDBContent" commandName="requestProperties">
<form:input type="date" id="requestDatePicker" path="date"/>
<form:select path="tvName">
<form:option value="wszystkie">--wszystkie--</form:option>
<form:options items="${televisionsList}"/>
</form:select>
<input value="zobacz mediaplan" type="submit" name="requestMediaplanButton" />
<input value="zobacz zamówienia" type="submit" name="requestOrdersButton"/>
</form:form>
<span class="logMessage">${logMessage}</span>
<footer>
CNS 2015
</footer>
</div>
Thanks for any help.
Regards,
Sebatian
As #M. Deinum said
you have to return null instead of the name of page your are trying to forward..

mixing up ajax and jsp to get data into a servlet

I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }

retrieve the data to the same html page i am using

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.

Categories