NullPointer trying to retrieve an Integer value - java

I have a problem when retrieving data (an Integer value) between servlets, when I want to multiply the value retrieved. I have this function in my first servlet,
private int totalNumberOf(Map<String,Integer> cart) {
int counter = 0;
for (String key : cart.keySet())
counter += cart.get(key);
return counter;
}
And I also have the attribute for it (placed at the end of the doGet() method)...
req.setAttribute("quantity", new Integer(totalNumberOf(cart)));
, a function that gives me the total number of products that are in the cart, which updates the value every time I add something to the cart so when I finish buying I can get an updated value of the number of products that are currently in the cart.
The problem comes now, when I try to do the fictional checkout (because I just have a generic price for every type of product) and I have to multiply the number of items by the generic price (here's where the NullPointer shows up).
Here's the code of my second servlet,
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity;
int toPay;
int genericValue = 20;
quantity = (Integer) req.getAttribute("quantity");
toPay = quantity.intValue() * genericValue; // NullPointer
}
I've tried everything in every way but I can't get rid of that ugly NullPointer. Hope you can help me a bit with this...
UPDATE Servlet1
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida = "";
Map<String,Integer> carrito = null;
String articuloElegido = req.getParameter("producto");
HttpSession session = req.getSession();
if (session.isNew()) {
session.invalidate();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
dispatcher.forward(req, res);
}
else {
String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
if (session.getAttribute("carrito") == null) {
carrito = new HashMap<String,Integer>();
session.setAttribute("carrito",carrito);
mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
}
else {
carrito = (Map<String,Integer>) session.getAttribute("carrito");
mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
}
insertarEnCarrito(carrito, articuloElegido);
}
req.setAttribute("mensaje", mensajeBienvenida);
req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
req.setAttribute("cantidad", numeroTotalLibros(carrito));
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
dispatcher.forward(req, res);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
if (carrito.get(articulo) == null){
carrito.put(articulo, new Integer(1));
}
else {
int numeroArticulos = (Integer)carrito.get(articulo).intValue();
carrito.put(articulo, new Integer(numeroArticulos+1));
}
}
private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
String cestaEnHTML = "";
for (String key : carrito.keySet())
cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
return cestaEnHTML;
}
private int numeroTotalLibros(Map<String,Integer> carrito) {
int counterLibro = 0;
for (String key : carrito.keySet())
counterLibro += carrito.get(key);
return counterLibro;
}
}
Servlet2
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida;
String cestaDeLaCompraEnHTML;
mensajeBienvenida = (String) req.getAttribute("mensaje");
cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY>" + mensajeBienvenida + "<br>");
out.println(cestaDeLaCompraEnHTML + "<br>");
out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
out.println("Seguir comprando!</BODY></HTML>");
out.println("Anular Compra</BODY></HTML>");
out.println("Pagar Compra</BODY></HTML>");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Servlet3
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer cantidadLibro;
int pagar;
int valorLibro = 20;
Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
Usuario usuario = (Usuario) session.getAttribute("user");
cantidadLibro = (Integer) req.getAttribute("cantidad");
if (cantidadLibro == null){
cantidadLibro = 0;
} else {
cantidadLibro = (Integer) req.getAttribute("cantidad");
}
// pagar = cantidadLibro.intValue() * valorLibro;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
out.println("<br><p>Total a pagar por su compra - " + "<br>");
out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
out.println("<br><p>User ID - " + usuario.getId() + "<br>");
session.invalidate();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}

Besides the refactoring and optimisation that your code might need, the problem you are refering to is that your are setting the attribute "cantidad" to the request instead of the session.
In Servlet1, replace this
req.setAttribute("cantidad", numeroTotalLibros(carrito));
with this
session.setAttribute("cantidad", numeroTotalLibros(carrito));
And in Servlet3, replace this
cantidadLibro = (Integer) req.getAttribute("cantidad");
with this
cantidadLibro = (Integer) session.getAttribute("cantidad");
The reason is that you are forwarding your request from Servlet1 to Servlet2, and so in Servlet2 you can access the "forwarded" request and all its attributes, BUT Serlvet3 is called independently at a later stage. I guess that is when you press "Pagar" in the rendered HTML page. Therefore, you can no longer access those attributes via the request because it is a different request. You can instead access them via the session if you stored them there previously.
Hope this helps.

Have you ever heard about debugging tools?
Your quantity variable has null value, it could be because of abscense attribute quantity in request. That is why you got NPE: null * (primitive numeric constant) -> NullPointerException.

From your code it it looks like "quantity.intValue()" throws your null pointer because quantity is null. Try this:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity = 0;
int toPay;
int genericValue = 20;
if (req.getAttribute("quantity") != null) {
quantity = (Integer) req.getAttribute("quantity");
}
toPay = quantity.intValue() * genericValue;
}
Notice not only do I initialize quantity with a value of 0 (so that it is not null) I also add a null check to "req.getAttribute("quantity")" so that you do not assign null to quantity in the case where .getAttribute returns null.

It's likely that your getAttribute function returned null. Remember to do null checking in code. I suggest a if (quantity != null) check before you call .intValue()
Another possible solution would be to check what .getAttribute() returned instead of checking what quantity was set to. You could also give quantity a default value.
if (req.getAttribute("quantity") == null) {
quantity = 0;
} else {
quantity = (Integer) req.getAttribute("quantity");
}

Related

How to pass HttpServletResponse in org.apache.catalina.valve invoke(Request,Response) method

I have below Java code to prevent X-FRAME-OPTIONS header being set for specific product responses
public class ResponseHeaderValve extends ValveBase {
private static final Logger LOGGER = Logger.getLogger(ResponseHeaderValve.class.getName());
private static final String PRODUCT_NAME = "PRODUCT_NAME";
#Override
public void invoke(Request request, Response response) throws ServletException, IOException {
try {
HttpSession session = request.getSession();
String productName = (String) session.getAttribute(PRODUCT_NAME);
if (productName == null && request.getParameterMap().containsKey(PRODUCT_NAME)) {
productName = request.getParameter(PRODUCT_NAME);
}
if (productName != null && productName.equalsIgnoreCase("product1")) {
HttpServletResponse httpServletResponse = new HttpServletResponseWrapper(response.getResponse()) {
public void addHeader(String name, String value) {
if (!name.equalsIgnoreCase("X-FRAME-OPTIONS")) {
super.setHeader(name, value);
}
}
public void setHeader(String name, String value) {
if (!name.equalsIgnoreCase("X-FRAME-OPTIONS")) {
super.setHeader(name, value);
}
}
};
this.getNext().invoke(request,httpServletResponse);
} else {
this.getNext().invoke(request, response);
}
}
catch(Exception e){
LOGGER.log(Level.INFO, "Exception in ResponseHeaderValve: invoke():", e);
}
}
}
For cases productName equals "product1" using HttpServletResponseWrapper I tried to prevent header being set.
I have to pass request, httpServletResponse to the next valve using invoke method, but org.apache.catalina.valve invoke(Request,Response) method does not allow passing httpServletResponse. I have tried casting (Response)httpServletResponse, it did not work throws ClassCastException. How can I proceed?

How to call the html from the java servlet

Here is my code:
#WebServlet({ "/Response1", "/resp" })
public class Response1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int count=0;
int Number =1;
System.out.println("s val is ==> "+request.getParameter("empidVal"));
String s1 = request.getParameter("empidVal");
System.out.println(s1);
services3 empjiras = new services3();
try {
Map<Object, Object> map1 = empjiras.getJiras(s1);
Object obj3 = map1.get("obj3");
map1.remove("obj3");
System.out.println(obj3);
Collection c=map1.values();
String myvalue="";
for (Iterator iterator = c.iterator(); iterator.hasNext();)
{
myvalue = (String) iterator.next();
count++;
}
System.out.println(count);
int count1 = count;
if(count!=0)
{
Set<Map.Entry<Object,Object>> s2=map1.entrySet();
PrintWriter out1=response.getWriter();
out1.println("<html>"+
"<center><font size=\"20\"><body><h2>JIRA Details</h2></font>"+
//"<table border='1'>"+
"<table width=\"800\" border ='10'>\r\n" +
"<tr>\r\n" +
"<th><font size ='+2'>Number</font></th>"+
"<th><font size ='+2'>JiraNumber</font></th>"+
"<th><font size ='+2'>Jira Status</font></th>" +
"<th><font size = '+2'>EmailId</font></th>\r\n</center>"+
"<button type='ok' value='ok'>OK</button>" +
"<button type='cancel' value='cancel'>cancel</button>");
for (Iterator<Map.Entry<Object,Object>> iterator = s2.iterator(); iterator.hasNext();) {
Map.Entry<Object,Object> entry = iterator.next();
Object name2 = entry.getKey();
Object value2 = entry.getValue();
Object email = obj3;
int num = Number++;
PrintWriter out=response.getWriter();
out.println(
"</tr>\r\n" +
"<tr>\r\n" +
"<tr>\r\n" +
"<td height=\"100\">"+num+"</td>"+
"<td height=\"100\">"+name2+"</td>\r\n" +
"<td height=\"100\">"+value2+"</td>\r\n"+
"<td height=\"100\">"+email+"</td>\r\n"+
"</tr>\r\n");
}
out1.println("</table></body></html>");
}
else
{
PrintWriter out=response.getWriter();
// out.println("count is :"+count1);
out.println("<html><body><h2>no jira issues in validating release</h2></body></html>");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here i am embedding the html code in an servlet which I think is not a good practice,actually I am reading the objects from another servlet and then processing it and displaying it in the browser.But is there any way how to separate this html code from the servlet.
Thanks in advance..

Java Servlet Switches execution order [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm having a few problems with two switches from a servlet. I'm trying to load data from those switches on a jsp but it basically just gets on the first switch and the second one isn't executed. I've tried creating only one switch but it will give me errors like Cannot forward after response has been committed and so on. Do you guys know what is the correct approach for this problem?
Thanks!
This is the code:
public class UserControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
private ReservationDao reservationDao;
private DBConnection dbConnection;
#Override
public void init() throws ServletException {
super.init();
try {
userDao = new UserDao(dbConnection);
reservationDao = new ReservationDao(dbConnection);
}catch(Exception e) {
throw new ServletException(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try {
// read the "command" parameter
String theCommand = request.getParameter("command");
String theCommand2 = request.getParameter("command2");
if(theCommand == null) {
theCommand = "LIST";
}
if(theCommand2 == null) {
theCommand2 = "LIST";
}
switch(theCommand2) {
case "LIST":
listReservations(request, response);
return;
case "ADD":
addReservation(request, response);
return;
case "LOAD":
loadReservation(request, response);
return;
case "UPDATE":
updateReservation(request, response);
return;
case "DELETE":
deleteReservation(request, response);
return;
default:
listReservations(request, response);
}
//route to the appropriate method
switch(theCommand) {
case "LIST":
listUsers(request, response);
break;
case "ADD":
addUser(request, response);
break;
case "LOAD":
loadUser(request, response);
break;
case "UPDATE":
updateUser(request, response);
break;
case "DELETE":
deleteUser(request, response);
break;
default:
listUsers(request, response);
}
}catch(Exception e) {
throw new ServletException(e);
}
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String theUserId = request.getParameter("userId");
userDao.deleteUser(theUserId);
listUsers(request, response);
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws Exception {
int id = Integer.parseInt(request.getParameter("userId"));
String username = request.getParameter("username");
String password = request.getParameter("password");
String role = request.getParameter("role");
String nume = request.getParameter("nume");
String prenume = request.getParameter("prenume");
String email = request.getParameter("email");
String adresa = request.getParameter("adresa");
UserBean theUser = new UserBean(id, username, password, role,nume,prenume,email,adresa);
userDao.updateUser(theUser);
listUsers(request, response);
}
private void loadUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
String theUserId = request.getParameter("userId");
UserBean theUser = userDao.getUser(theUserId);
request.setAttribute("THE_USER", theUser);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/update-user-form.jsp");
dispatcher.forward(request, response);
return;
}
private void addUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
String role = request.getParameter("role");
String nume = request.getParameter("nume");
String prenume = request.getParameter("prenume");
String email = request.getParameter("email");
String adresa = request.getParameter("adresa");
UserBean theUser = new UserBean(username, password, role,nume,prenume,email,adresa);
userDao.addUser(theUser);
listUsers(request, response);
}
private void listUsers(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<UserBean> users = userDao.getUsers();
request.setAttribute("USER_LIST", users);
RequestDispatcher dispatcher = request.getRequestDispatcher("/list-users.jsp");
dispatcher.forward(request, response);
return;
}
//Reservations Methods
private void deleteReservation(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String theReservationId = request.getParameter("reservationId");
reservationDao.deleteReservation(theReservationId);
listReservations(request, response);
}
private void updateReservation(HttpServletRequest request, HttpServletResponse response)
throws Exception {
int idReservation = Integer.parseInt(request.getParameter("reservationId"));
int idUser = Integer.parseInt(request.getParameter("userId"));
String dataCheckin = request.getParameter("dataCheckin");
String dataCheckout = request.getParameter("dataCheckout");
int nrPersoane = Integer.parseInt(request.getParameter("nrPersoane"));
int nrCamere = Integer.parseInt(request.getParameter("nrCamere"));
ReservationBean theReservation = new ReservationBean(idReservation, idUser, dataCheckin, dataCheckout,nrPersoane,nrCamere);
reservationDao.updateReservation(theReservation);
listReservations(request, response);
}
private void loadReservation(HttpServletRequest request, HttpServletResponse response) throws Exception {
String theReservationId = request.getParameter("reservationId");
ReservationBean theReservation = reservationDao.getReservation(theReservationId);
request.setAttribute("THE_RESERVATION", theReservation);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/update-reservation-form.jsp");
dispatcher.forward(request, response);
return;
}
private void addReservation(HttpServletRequest request, HttpServletResponse response) throws Exception {
int userId = Integer.parseInt(request.getParameter("userId"));
String dataCheckin = request.getParameter("dataCheckin");
String dataCheckout = request.getParameter("dataCheckout");
int nrPersoane = Integer.parseInt(request.getParameter("nrPersoane"));
int nrCamere = Integer.parseInt(request.getParameter("nrCamere"));
ReservationBean theReservation = new ReservationBean(userId, dataCheckin, dataCheckout,nrPersoane,nrCamere);
reservationDao.addReservation(theReservation);
listReservations(request, response);
}
private void listReservations(HttpServletRequest request, HttpServletResponse response)
throws Exception {
List<ReservationBean> reservations = reservationDao.getReservations();
request.setAttribute("RESERVATION_LIST", reservations);
request.getRequestDispatcher("/list-users.jsp").forward(request, response);
return;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
gets on the first switch and the second one isn't executed
Your first switch contains return statements. Change them to break statements.
switch(theCommand2) {
case "LIST":
listReservations(request, response);
break; // not return.
case "ADD":
addReservation(request, response);
break; // not return..
// ...

RequestDispatcher not redirecting in java servlet to JSP

I'm trying to redirect to another page from my servlet where string value is null. When I run the code it stays on the same page instead of redirecting to my error page. Here is my code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String emp = request.getParameter("emp")!=null ? request.getParameter("emp"): "";
MCenter mCenter = new MCenter();
mCenter = mCenterDAO.getMCenterPocByEmp(emp);
mCenter = mCenterDAO.getMCenterByObject(mCenter);
PrintWriter pw = response.getWriter();
String mPocName = mCenter.getMCenterPocName();
String mCenter = mCenter.getMCenterName();
if(mPocName == null || mCenter == null) {
request.getRequestDispacher("error.jsp").forward(request, response);
System.out.println("Null or not name " + mPocName + "center " + mCenter);
}
String json = getMCenterPoc(emp);
pw.print(json);
pw.close();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
I get no error, and the print out give me null or value depending on whether or not there is value or not.
You must do following changes in your code. Request Dispatcher doesn't work with Ajax post.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String emp = request.getParameter("emp") != null ? request.getParameter("emp") : "";
MCenter mCenter = new MCenter();
mCenter = mCenterDAO.getMCenterPocByEmp(emp);
mCenter = mCenterDAO.getMCenterByObject(mCenter);
String mPocName = mCenter.getMCenterPocName();
String mCenter = mCenter.getMCenterName();
if (mPocName == null || mCenter == null) {
request.sendRedirect("error.jsp");
System.out.println("Null or not name " + mPocName + "center " + mCenter);
} else {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String json = getMCenterPoc(emp);
pw.print(json);
pw.close();
}
}
Or you can do with Ajax success. In this way you don't need to change code to mine.
If you want to do with Ajax.
var emp = $('#emp').val();
$.ajax({
type: "POST",
url: "yourServletName",
data: 'emp='+emp+'',
success: function(response) {
if(response='error'){
window.location.href='error.jsp';
}else{
//What you want
}
}
});
Of course your servlet must change to following.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String emp = request.getParameter("emp") != null ? request.getParameter("emp") : "";
MCenter mCenter = new MCenter();
mCenter = mCenterDAO.getMCenterPocByEmp(emp);
mCenter = mCenterDAO.getMCenterByObject(mCenter);
String mPocName = mCenter.getMCenterPocName();
String mCenter = mCenter.getMCenterName();
if (mPocName == null || mCenter == null) {
String json = "error";
} else {
String json = getMCenterPoc(emp);
}
pw.print(json);
pw.close();
}
You are seeing nothing in UI because there is nothing(no text content) in your error.jsp file.
You need to add some text as below in error.jsp page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error page</title>
</head>
<body>
<p>Error has occurred!!!</p>
</body>
When your request is forwarded to a jsp/servlet/html it does not mean that your browser url will be changed, just your request will be forwarded to another resource to generate a response that will be sent back to you. The URL will remain same.

servlet getParts() in uploading file

I have implemented drag & drop file uploading in jsp and servlet, but I have a problem. Here is a part of my upload.jsp code:
function dropUpload(event) {
var files = event.dataTransfer.files;
upload(files);
}
function upload(files) {
var formData = new FormData();
for (var i in files) {
formData.append('file[]', files[i]);
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.open("POST", "UploadServlet");
xhr.send(formData);
}
I use the getParts() method in my UploadServlet.java code to get the files that the user uploads, like below:
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("login.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String savePath = "D:\\TEST";
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
response.getWriter().println(request.getParts().size());
for (Part part : request.getParts()) {
if(part.getContentType() == null) {
continue;
}
response.getWriter().println("Part name: " + part.getName());
response.getWriter().println("Size: " + part.getSize());
response.getWriter().println("Content Type: " + part.getContentType());
String fileName = extractFileName(part, response);
response.getWriter().println(fileName);
part.write(savePath + File.separator + fileName);
response.getWriter().println("already upload file:" + fileName);
response.getWriter().println("=============================================");
}
}
private String extractFileName(Part part,HttpServletResponse response) throws IOException {
String contentDisp = part.getHeader("content-disposition");
//response.getWriter().println(contentDisp);
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
But I can't understand that if I upload 2 files with upload.jsp,
the value of getParts().size() is 4; it means that I always have 2 more files than exactly what I upload, and the 2 external files name and contentType will be null, and it will cause an error in part.write().
My solution is use the if statement
if(part.getContentType() == null) {
continue; }
to ignore the null file.
Can somebody tell me why this happens?

Categories