-1

So basically, when I try submitting my jsp, the control wents to the servlet , but the values of all the control in jsp becomes null

"ViewBook.jsp"

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@include file="Header_1.jsp" %>
<form action="<%=request.getContextPath()%>/BookServlet" method="post" 
enctype="multipart/form-data">
<table>    
        <th colspan="2"></th>
        <tr>    
            <td>
                ID:
            </td>
            <td>
                <input type="number" name="id">
            </td>

        </tr>
         <tr>    
            <td>
                Title:
            </td>
            <td>
                <input type="text" name="title">
            </td>
        </tr>
         <tr>    
            <td>
                Author
            </td>
            <td>
                <input type="text" name="author">
            </td>

        </tr>
         <tr>    
            <td>
                Price:
            </td>
            <td>
                <input type="number" name="price">
            </td>

        </tr>
         <tr>    
            <td>
                Book image:
            </td>
            <td>
                <input type="file" name="book_img">
            </td>

        </tr>
         <tr>    
            <td>
                Publish date:
            </td>
            <td>
                <input type="date" name="pub_date">     
            </td>
        </tr>
         <tr>    
            <td>                          
                <input type="submit" value="add" formaction=" 
   <%=request.getContextPath()%>/BookServlet?action=add">
                <input type="submit" value="delete" 
    formaction="G:\sem5\AJT\Q-4\src\java\BookServle?action=delete">
                <input type="submit" value="update" formaction=" 
   <%=request.getContextPath()%>/BookServlet?action=update">
                <input type="submit" value="view" formaction=" 
   <%=request.getContextPath()%>/BookServlet?action=view">
            </td>
        </tr>   
</table>
</form>

<%@include file="Footer.jsp" %>

"BookServlet.java"

@WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, 
HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse 
response)
        throws ServletException, IOException {
      try (PrintWriter out = response.getWriter()) {

    } 
    }  
//    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse 
response)
        throws ServletException, IOException {
     String title=request.getParameter("title");
        String author=request.getParameter("author");
        String price=request.getParameter("price");
        System.out.println("price=="+price);
        String book_img=request.getParameter("book_img");
        System.out.println("book:imagre===="+book_img);
        String pub_date=request.getParameter("pub_date");
        String action=request.getParameter("action");
        SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
        Date d = null;
    try {
        d = (Date) sdf.parse(pub_date);
    } catch (Exception ex) {
        System.out.println("Exception ex="+ex);
    }
    Part filepart=request.getPart("book_img");
    System.out.println("part====="+filepart);
    InputStream is=filepart.getInputStream();
        BookBean bb=new BookBean();
  //      ResultSet rs=bb.ViewAllBooks();
        if(action.equals("add"))
        {
         Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
            bb.add(b);
            HttpSession s=request.getSession(true);
           // s.setAttribute("rs", rs);
            RequestDispatcher 
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
            rd.forward(request, response);
  //  processRequest(request, response);
}else if(action.equals("update"))
        {            Book b=new 
Book(0,title,author,Integer.parseInt(price),d,is);
          //  boolean flag= bb.update(b);
            HttpSession s=request.getSession(true);
      //      s.setAttribute("rs", rs);
            RequestDispatcher 
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
            rd.forward(request, response);
        }else if(action.equals("delete")){}
        else if(action.equals("view")){}

}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

This is what I got in my catch block -Exception ex=java.lang.NullPointerException

StackTrace:

 java.lang.NullPointerException
at BookCrud.BookServlet.doPost(BookServlet.java:136)
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:199)
at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke
(AuthenticatorBase.java:491)
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:668)
at 
org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service
(CoyoteAdapter.java:343)
at 
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process
(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process
(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun
(NioEndpoint.java:1388)
at 
org.apache.tomcat.util.net.SocketProcessorBase.run
(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

any help from your side also, I have surfed a lot for this on StackOverflow and other websites but I didn't get any proper solution for this.......

2 Answers2

1

For all those who are facing the same error ::You can use jar files as mentioned by @secret super star ,But if you dont want to do so here is a tip :

Just

import javax.servlet.annotation.MultipartConfig; 

in your servlet and add

@MultipartConfig(maxFileSize = 16177215)    //Length of the file

annotation ,That's it

Note: In my case following will be my servlet

@WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
@MultipartConfig(maxFileSize = 16177215)    
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, 
HttpServletResponse response)
    throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse 
response)
    throws ServletException, IOException {
  try (PrintWriter out = response.getWriter()) {

} 
}  
//    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse 
response)
    throws ServletException, IOException {
 String title=request.getParameter("title");
    String author=request.getParameter("author");
    String price=request.getParameter("price");
    System.out.println("price=="+price);
    String book_img=request.getParameter("book_img");
    System.out.println("book:imagre===="+book_img);
    String pub_date=request.getParameter("pub_date");
    String action=request.getParameter("action");
    SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
    Date d = null;
try {
    d = (Date) sdf.parse(pub_date);
} catch (Exception ex) {
    System.out.println("Exception ex="+ex);
}
Part filepart=request.getPart("book_img");
System.out.println("part====="+filepart);
InputStream is=filepart.getInputStream();
    BookBean bb=new BookBean();
  //      ResultSet rs=bb.ViewAllBooks();
    if(action.equals("add"))
    {
     Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
        bb.add(b);
        HttpSession s=request.getSession(true);
       // s.setAttribute("rs", rs);
        RequestDispatcher 
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
         rd.forward(request, response);
 //  processRequest(request, response);
}else if(action.equals("update"))
    {            Book b=new 
Book(0,title,author,Integer.parseInt(price),d,is);
      //  boolean flag= bb.update(b);
        HttpSession s=request.getSession(true);
  //      s.setAttribute("rs", rs);
        RequestDispatcher 
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
        rd.forward(request, response);
    }else if(action.equals("delete")){}
    else if(action.equals("view")){}

}

@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}
0

you can not directly get parameters by using request.getParameter(name);. While using it, form fields aren't available as parameter of the request, they are included in the stream, so you can not get it the normal way.

Refer this: http://commons.apache.org/proper/commons-fileupload//using.html, under the section Processing the uploaded items.

Shiva
  • 1,962
  • 2
  • 13
  • 31
  • thanks a lot for this!!! but i wanted to know the reason behind that because in one of my friend's computer this code is working fine... – dubking India Nov 17 '18 at 06:55
  • I will accept this as an answer, but please help me to understand the reason behind that! why we cannot directly use request.getParameter()?? and also this code runs perfectly fine in my friend's pc ....hope you will help me to understand – dubking India Nov 17 '18 at 08:24
  • Not sure, how the other code looks like. The below thread gives detailed answer on the behavior: https://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet… and https://www.w3.org/TR/html4/interact/forms.html Hope this helps and post your comments if any queries. Are you/your friend using servlet 3.0 or newer? – Shiva Nov 17 '18 at 08:47