request.getParameter возвращает ноль, я много занимался серфингом для этого, но не нашел правильного решения - PullRequest
0 голосов
/ 17 ноября 2018

Таким образом, в основном, когда я пытаюсь отправить свой jsp, элемент управления переходит к сервлету, но значения всего элемента управления в jsp становятся равными нулю

"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>

}

Это то, что я получил в своем блоке catch -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)

Любая помощь с вашей стороны, я много занимался этим на StackOverflow и других сайтах, но у меня не было подходящего решения для этого .......

Ответы [ 2 ]

0 голосов
/ 24 ноября 2018

Для всех тех, кто сталкивается с одной и той же ошибкой: вы можете использовать jar-файлы, как указано @secret super star, но если вы не хотите этого делать, вот совет:

Просто

import javax.servlet.annotation.MultipartConfig; 

в вашем сервлете и добавьте

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

аннотацию, вот и все

Примечание: в моем случае следующим будет мой сервлет

@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 голосов
/ 17 ноября 2018

Вы не можете напрямую получить параметры, используя request.getParameter(name);.При его использовании поля формы недоступны как parameter из request, они включены в stream, поэтому вы не можете получить его обычным способом.

См. Это: http://commons.apache.org/proper/commons-fileupload//using.html, в разделе «Обработка загруженных предметов».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...