Hello guys i'm facing a problem with my code, i have a jsp form that send a file into a servlet, and when i try to extract the file using request.getParts() it return null value wheni try to print it to the console, can anyone help me please. here is my code.
my jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="/PartsServlet" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
My servlet:
package Servv;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class PartsServlet
*/
#WebServlet("/PartsServlet")
public class PartsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PartsServlet() {
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());
System.out.println("Get Parts "+request.getPart("file"));
System.out.println("Get Parts "+request.getPart("destination"));
}
/**
* #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);
}
}
Add #MultipartConfig annotation.
Always parse your request body only once and store it in a list.
so that one part cannot consume it.
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
for (Part part : fileParts) {
}
File uploads = new File("/path/to/uploads");
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Related
This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 2 years ago.
In my JSP Servlet application, One of the JSP page is able to send in form parameters to Servlet while other throws Null Pointer exception while doing the same thing. Why so? Will deeply appreciate help on this, please find code below.
Name.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>What's Your Name</h1>
<form action="Name" method="POST">
First Name: <input type="text" name="firstname"></br>
Last Name: <input type="text" name="lastname"></br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NameServlet file
package com.servelets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.objects.Name;
/**
* Servlet implementation class NameServlet
*/
#WebServlet("/Name")
public class NameServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NameServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Get Name");
response.getWriter().append("Served at: ").append(request.getContextPath());
request.getRequestDispatcher("WEB-INF/views/Name.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Post Name");
Name name = new Name();
HttpSession session = request.getSession();
name.setFirstname(request.getParameter("firstname"));
name.setLastname(request.getParameter("lastname"));
session.setAttribute("name", name);
//request.getRequestDispatcher("/WEB-INF/views/Bio.jsp").forward(request, response);
response.sendRedirect("Bio");
//request.getRequestDispatcher("Bio").include(request, response);
}
}
Bio.jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Give us your Age, Weight, Height</h1>
<h1>Welcome ${name.firstname} ${name.lastname} </h1>
<form action="Bio" method="POST">
Age: <input type="text" name="age"></br>
Weight: <input type="number" name="weight">
<select id="weightunit" name="weightunit">
<option value="kg">Kg</option>
<option value="Lb">Lb</option>
</select></br>
Height: <input type="number" name="height"> Unit: <input type="text" name="heightunit"></br>
<input type="submit" value="Submit">
</form>
</body>
</html>
BioServlet file
package com.servelets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.objects.Bio;
/**
* Servlet implementation class BioServlet
*/
#WebServlet(description = "Servlet for Bio Page", urlPatterns = { "/Bio" })
public class BioServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BioServlet() {
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
System.out.println("Get Bio");
response.getWriter().append("Served at: ").append(request.getContextPath());
request.getRequestDispatcher("WEB-INF/views/Bio.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Post Bio");
Bio bio = new Bio();
if(request.getAttribute("age")==null) {
System.out.println("age is null");
}
HttpSession session = request.getSession();
String age = (String) request.getAttribute("age");
bio.setAge(Integer.parseInt(age));
bio.setHeight(Double.parseDouble(request.getAttribute("height").toString()));
bio.setHeightunit(request.getAttribute("heightunit").toString());
bio.setWeight(Double.parseDouble(request.getAttribute("weight").toString()));
bio.setWeightunit(request.getAttribute("weightunit").toString());
session.setAttribute("bio", bio);
response.sendRedirect("Address");
}
}
I am able to go from Name.jsp page to Bio.jsp page and access attributes in NameServlet but as soon as I enter values in Bio.jsp page and try to redirect it to next page in application, I run into a null pointer exception. stacktrace below.
May 16, 2020 5:35:53 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in [3,151] milliseconds
Get Name
Post Name
Get Bio
Post Bio
age is null
May 16, 2020 5:38:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.servelets.BioServlet] in context with path [/DisplayAddress] threw exception
java.lang.NumberFormatException: null
at java.base/java.lang.Integer.parseInt(Integer.java:614)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at com.servelets.BioServlet.doPost(BioServlet.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
The request.getAttribute("age")is coming as null from Bio.jsp page, I will deeply appreciate any help on this.
I realized I was using Request.getAttribute instead of Request.getParameter, I updated the code in my BioServlet file and it worked, updated code is shown below.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Post Bio");
Bio bio = new Bio();
if(request.getParameter("age")==null) {
System.out.println("age is null");
}
HttpSession session = request.getSession();
String age = (String) request.getParameter("age");
bio.setAge(Integer.parseInt(age));
bio.setHeight(Double.parseDouble(request.getParameter("height").toString()));
bio.setHeightunit(request.getParameter("heightunit").toString());
bio.setWeight(Double.parseDouble(request.getParameter("weight").toString()));
bio.setWeightunit(request.getParameter("weightunit").toString());
session.setAttribute("bio", bio);
response.sendRedirect("Address");
}
I would like to print out my current variable value on my HTML page. I cannot seem to figure it out. On my HTML page, I want to print out the current Exchange rate.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="get" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
<br>Current Rate:
</form>
</body>
</html>
My Java 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;
/**
* Servlet implementation class Converter
*/
#WebServlet("/Converter")
public class Converter extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Converter() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
String n2 = "1.0";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
if(n2.equals("tempStr")){
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
else if(n2.equals(n2)){
out.println("test");
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
How can I print out the current rate. Which in this case is n2 on my HTML page? I want it to update on each load of the website. But I cannot figure out how to print out the variable value through the HTML page.
You can use your PrintWriter instance to print the whole HTML into the response object, example:
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Bla</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Your current rate is: ");
//Your Java code here
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
out.println(n2);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
Hope that helps.
I have a Java servlet as
package com.nh.bookapp;
import com.books.Book;
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class BookApp
*/
#WebServlet("/BookApp")
public class BookApp extends HttpServlet {
private static final long serialVersionUID = 1L;
List <Book> Books = new ArrayList<Book>();
/*List<String> BookNames = new ArrayList<String>();
List<String> Authors = new ArrayList<String>();
List<String> Costs = new ArrayList<String>();*/
/**
* #see HttpServlet#HttpServlet()
*/
public BookApp() {
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);
String bookName = request.getParameter("bookname");
String author = request.getParameter("authorname");
String bookCost = request.getParameter("cost");
String url = ("");
/*BookNames.add(bookName);
Authors.add(author);
Costs.add(cost);*/
Book newBook = new Book();
if(bookName.length()!=0&&author.length()!=0&&bookCost.length()!=0)
{
newBook.authorName=author;
newBook.name=bookName;
newBook.cost = Float.parseFloat(bookCost);
Books.add(newBook);
request.setAttribute("Book", newBook);
url =("/displayBook.jsp");
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The class Book is defined as :
package com.books;
public class Book {
public String name;
public String authorName;
public Float cost;
}
The index.html is as follows :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a book entry</title>
</head>
<body>
<form name="BookForm" id="fBook" action="BookApp" method="post">
Name:
<input type="text" name="bookname" id="tbBook">
<br>
Author:
<input type="text" name="authorname" id="tbAuthor">
<br>
Cost:
<input type="text" name="cost" id="tbCost">
<br>
<input type ="submit" value="Create">
</form>
</body>
</html>
And displayBook.jsp is :
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create a book entry</title>
</head>
<body>
<form name="BookForm" id="fBook" action="BookApp" method="post">
Name:
<input type="text" name="bookname" id="tbBook">
<br>
Author:
<input type="text" name="authorname" id="tbAuthor">
<br>
Cost:
<input type="text" name="cost" id="tbCost">
<br>
<input type ="submit" value="Create">
</form>
</body>
</html>
When I run the server, I encounter the error under root cause as
javax.el.PropertyNotFoundException: Property [name] not found on type [com.books.Book]
I have the necessary imports in the JSP file and the variables are declared in the class, yet I am unable to access them despite them being public.
I cannot figure out what's going wrong where. I've tried using
<c:out value="${Book.name}" />
as it was suggested in another answer but it didn't work.
Why am I getting null value while using "sendReditect" in servlet as per below
my code as per below : I am getting fname value null even in both FirstServlet and SecondServlet
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname"></br> <input type="submit"
value="SUBMIT">
</form>
</body>
</html>
FirstServlet:
package com.naveen;
import java.io.IOException;
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;
/**
* Servlet implementation class FirstServlet
*/
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname");
// TODO Auto-generated method stub
/*String s1=request.getParameter("t1");*/
/*RequestDispatcher rd=request.getRequestDispatcher("SecondServlet");
rd.forward(request, response);*/
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SecondServlet:
package com.naveen;
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;
/**
* Servlet implementation class SecondServlet
*/
#WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s3=request.getParameter("fname");
out.print("hi i am siddharth");
out.println(s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
why i am getting null value while using "sendReditect" in servlet as
per below my code as per below : i am getting fname value null even in
both FirstServlet and SecondServlet,
Because you're not setting any values to your request. You need to set the value to the request like this:
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname"); //get the value you set in your jsp/html/url
request.setAttribute("fname", s3); // set the s3 value to the request
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I'm assuming here you have sent the fname value via a form or something. If you call FirstServlet by just typing it in the url, you will get null.
But not if you set something, try it like this if you are not submitting a form:
/FirstServlet?fname=helloworld
EDIT:
just noticed in your form you're not actually setting fname with any value. You need to give it a value:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname" value="helloworld"></br> //add value to your input!!
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
I am creating a java servlet which should get a number from a textbox (created using using HTML) calculate its factorial and when i will press submit button (also created using HTML) it should calculate and display the factorial in another textbox which i have created.
Problem I have successfully retrieved the number from the first textbox (using request.getParameter) and calculated it factorial. Now the problem is that i am unable to post the calculated factorial in that 2nd textbox.
Plz help me what should i do?
Thank in advance!
Here is the code:
servlet:
package factorial;
import java.io.*;
import javax.servlet.Servlet;
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 org.apache.jasper.tagplugins.jstl.core.Out;
/**
* Servlet implementation class fact
*/
#WebServlet("/fact")
public class fact extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public fact() {
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
PrintWriter out = response.getWriter();
long number = Long.parseLong((request.getParameter("num")));
long fact=1;
while(number>1){
fact=fact*number;
number--;
}
//request.setAttribute("factorial", fact); //***this is not working***
//out.println(fact);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="get">
Enter a number: <input type="text" name="num">
<input type="submit"/>
Factorial <input type="text" id="factorial" name="factorial"/>
</form>
</body>
</html>
store the value in request or session attributes as request.setAttribute("name",value) or session.setAttribute("name", value). and in JSP, retrieve them using request.getAttribute("name") or session.getAttribute("name")