从Servlet到JSP

时间:2018-03-15 03:41:38

标签: java jsp servlets java-ee

解决方案:变量仅在if / elseif语句的范围内初始化,因此如果未输入范围,则getAttribute调用null。

我验证给定的数字是在我本地存储的SQL数据库中。如果是,我将该行的数据存储在一个对象中,存储在ArrayList中并传递给JSP。如果没有,我将布尔变量设置为true并将其传递给我的JSP。

这样做的时候,我的布尔变量得到了NullPointerException,我不知道为什么。我知道那个例外意味着什么,我不确定为什么它适用于我的情况。任何建议,或替代我如何接近这一点都会很棒。

我的JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.List, java.sql.ResultSet, ca.package.beans.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Scan</title>
</head>
<body>
    <% List<Products> productsList = (List<Products>)request.getAttribute("productsList"); %>

    <h1>List of Scanned Items</h1>
    <table>
        <tr>
            <td><b>Item Code</b></td>
            <td><b>Name</b></td>
            <td><b>Price</b></td>
            <td><b>Tax</b></td>
        </tr>

    <% boolean invalidCode = (boolean)session.getAttribute("invalidCode"); %>

        <% if (!productsList.isEmpty()) { %>
            <% for(Products product : productsList) { %>        
            <tr>
                <td><%= product.getCode() %></td>
                <td><%= product.getName() %></td>
                <td><%= product.getPrice() %></td>
                <td><% if(product.isTaxable()) { %>
                        <%= product.getPrice() * 0.13 %>
                    <% } else if (product.isTaxable() == false) { %>
                        <% out.print("0"); %>
                    <% } %></td>
            </tr>
        <% } %>
    </table>
    <% } else if (invalidCode == true) { %>
        <p>The entered code is wrong</p>
    <% } %>

    <div class='codeBox'> 
        <form action="eShop" method="Post">
            <table>
                <tr>
                    <td align="left"><b>Item Code:</b><input type="text" name="code"><br><br></td>
                </tr>
                <tr>
                    <td align="left"><input type="submit" name="action" value="Scan!" style="width: 150px"></td>
                </tr>
            </table>
        </form>
    </div>



</body>
</html>

我的Servlet

@WebServlet("/eShop")
public class eShop extends HttpServlet {
    private static final long serialVersionUID = 1L;
    List<Products> productsList = new CopyOnWriteArrayList<Products>();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public eShop() {
        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
        HttpSession session = request.getSession();
        String itemCode = request.getParameter("code");
        boolean invalidCode;
        try{  
            Class.forName("com.mysql.jdbc.Driver");  
            Connection con=DriverManager.getConnection(  
            "jdbc:mysql://localhost/assignment2","root","1111");  
            Statement stmt=con.createStatement();  
            ResultSet rs=stmt.executeQuery("select * from ProductCatalogue where code = "+itemCode);  

            int codeCheck = Integer.parseInt(itemCode);
            DataAccessImpl da = new DataAccessImpl();
            if(itemExists(rs)) {
                    Products temp = new Products(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBoolean(4));
                    productsList.add(temp);
                    System.out.println("In the if");
                    request.setAttribute("productsList", productsList);
                    request.getRequestDispatcher("Scan.jsp").forward(request, response);
            } 
            else if(da.codeExists(codeCheck) == false){
                invalidCode = true;
                System.out.println("THIS IS EXECUTING!");
                session.setAttribute("invalidCode", invalidCode);
                request.getRequestDispatcher("Scan.jsp").forward(request, response);
            }

            con.close();  
            }catch(Exception e){ e.printStackTrace();}
    }

    /**
     * @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);
    }

    private boolean itemExists(ResultSet rs) {
        try {
            if(rs.next()) {
                return true;
            }
        }catch(Exception e) {
        }
        return false;
    }
}

堆栈追踪:

SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
    at org.apache.jsp.Scan_jsp._jspService(Scan_jsp.java:141)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at ca.sheridancollege.controllers.eShop.doGet(eShop.java:64)
    at ca.sheridancollege.controllers.eShop.doPost(eShop.java:76)
    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:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:417)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Unknown Source)

org.apache.jasper.JasperException: An exception occurred processing [/Scan.jsp] at line [23]

20:         
21:     <% boolean invalidCode = (boolean)(request.getAttribute("invalidCode")); %>
22: 
23:         <% if (!productsList.isEmpty()) { %>
24:             <% for(Products product : productsList) { %>        
25:             <tr>
26:                 <td><%= product.getCode() %></td>


Stacktrace:
    at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:593)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:482)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
    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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
    at ca.sheridancollege.controllers.eShop.doGet(eShop.java:64)
    at ca.sheridancollege.controllers.eShop.doPost(eShop.java:76)
    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:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:417)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at org.apache.jsp.Scan_jsp._jspService(Scan_jsp.java:141)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:444)

0 个答案:

没有答案