JSP Servlet无法访问会话数据

时间:2012-11-10 04:24:16

标签: java jsp servlets

好的,我将在这里发布很多代码,其中一些你们可能都希望从中睁开眼睛。这是我的第一个servlet项目,我想我已经找到了一切可能的方法来打破它,然后又发明了一些。

以下是三个jsp页面。用户通过电话号码选择客户的第一页(索引)或单击按钮以输入新用户。这会调用一个servlet(ChooseCustomer)。选择客户或选择输入新客户会将用户发送到第2页(customer.jsp),如果他们选择了客户或者需要编辑/输入新客户,则会填写客户信息。这一切都很好。这是我的麻烦开始的地方。此页面有两个按钮,用户单击这些按钮以启动交货单或拣配订单。这些按钮调用servlet(Customersrvlt)似乎工作正常。但是,然后将用户定向到订单页面。页面加载(有时)但我在从会话到页面获取信息时遇到问题。我尝试过使用session.setAttribute(“name”,“object”),我尝试过使用bean,以及我在书籍和网上找到的所有其他内容。正如您从最后一个jsp页面上的代码中看到的,我有一些不同的东西。它工作,我现在吃晚餐它没有。为了以防万一,我关闭了一切并重新启动。没变。我无法访问订单和客户会话对象,或者我可以获得一个而不是另一个,并且我无法使用$ {order.oid}标签获取订单对象。它说我的oid不存在jasper错误(我可以在必要时发布)。我已经编写并重写了代码并尝试使用。 <%...%>给我一个关于它在div中的错误,这就是它被注释掉的原因。 PS:我有两个类OrderBean和Customer,它们有setter和getter以及构造函数。我有双重和三重检查,他们对类中的所有东西都有正确的小写setOrderId()格式。我的web.xml文件很好,并且servlet被映射。我使用控制台设置会话属性后,我也在servlet中检查并且对象似乎在那里。我正在使用Eclipse Juno,Tomcat 7(使用XAMPP)和MySQL。帮助!

的index.jsp

    <%-- index.jsp --%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
    <%@ page import="java.util.*" %>  
    <%@ include file="staticpages/pageHeader.html" %>
        <br />      
            <hr />      
            <br />
            <form name="selectcust" method="POST" action="ChooseCustomer.do" >
            <div class="sectionheader" style="margin_right: auto; margin-left: auto; text-align: center;">Look Up Customer by Phone Number</div>
            <br />
            <div style="margin-right: auto; margin-left: auto; text-align: center;">
                <input type="text" name="phone1" size="3" maxlength="3"  />             
                <input type="text" name="phone2" size="3" maxlength="3"  />
                <input type="text" name="phone3" size="4" maxlength="4"  />
                <br /><br />
                <input type="submit" name="formaction" value="Search" size="30" class="btn" />
                <br /><br />
                <input type="submit" name="formaction" value="Enter New Customer" size="30" class="btn" />
                <br /><br />
                <% if("No".equals(request.getAttribute("customerFound"))) { %>
                <div style="color: #FF0000; text-align: center;" >Customer was not found, please re-enter or start a new customer.</div>
                <% } %>
            </div>
            </form> 
    <%@ include file="staticpages/pageFooter.html" %>

customer.jsp

    <%-- customer.jsp --%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
    <%@ page import="java.util.*" %>  
    <%@ include file="staticpages/pageHeader.html" %>
    <script src="scripts/customervalidation.js" type="text/javascript" ></script>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>  


        <br />      
            <hr />
            <br />
            <form name="custform" method="POST" onSubmit="return validateCustomerData();" action="submitCustomer.do" >

            <span class="sectionheader">Enter or Edit Customer:</span>
            <br /><input type="text" size="50" name="errmsg" class="err" />
            <br />
            <table>
            <tr>
            <td>
                <span class="leftspan">First Name:</span>
                <span class="rightspan">
                    <input type="text" name="fname" id="fname" disabled="disabled" value="${customer.cfname}" onKeyDown="editedCust()" size="45" />
                    <input type="text" size="1" name="errfn" class="err" disabled="disabled" /> </span><br />
                <span class="leftspan">Last Name:</span>
                <span class="rightspan">
                    <input type="text" name="lname" disabled="disabled" value="${customer.clname}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errln" class="err" disabled="disabled" /></span><br />
                <span class="leftspan">Address:</span>
                <span class="rightspan">
                    <input type="text" name="address" disabled="disabled" value="${customer.caddress}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errad" class="err" disabled="disabled" /></span><br />
                <span class="leftspan">City:</span>
                <span class="rightspan">
                    <input type="text" name="city" disabled="disabled" value="${customer.ccity}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errct" class="err" disabled="disabled" /></span><br />
                <span class="leftspan">State:</span>
                <span class="rightspan">
                    <input type="text" name="state" size="3" maxlength="2" disabled="disabled" onKeyUp="checklen(this)" value="${customer.cstate}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errst" class="err" disabled="disabled" />
                    &nbsp;&nbsp;&nbsp; Zip Code:
                    <input type="text" name="zip" size="5" maxlength="5" disabled="disabled" onKeyUp="checklen(this)" value="${customer.czip}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errzp" class="err" disabled="disabled" /></span><br />
                <span class="leftspan">Phone:</span>
                <span class="rightspan">
                    <input type="text" name="phone4" size="3" maxlength="3" disabled="disabled" onKeyUp="checklen(this)" value="${fn:substring(customer.cphone, 0, 3)}" onKeyDown="editedCust()" />             
                    <input type="text" name="phone5" size="3" maxlength="3" disabled="disabled" onKeyUp="checklen(this)" value="${fn:substring(customer.cphone, 3, 6)}" onKeyDown="editedCust()" />
                    <input type="text" name="phone6" size="4" maxlength="4" disabled="disabled" onKeyUp="checklen(this)" value="${fn:substring(customer.cphone, 6, 10)}" onKeyDown="editedCust()" />
                    <input type="text" size="1" name="errph" class="err" disabled="disabled" /></span>
                <br />
                <span class="leftspan" style="verticle-align: top">Notes:</span><br />
                    <textarea name="notes" rows="5" cols="35" disabled="disabled" onKeyDown="editedCust()">${customer.cnotes}</textarea><br />
                <input type="hidden" name="custid" value="${customer.cid}" />
                <input type="hidden" name="edited" />
            </td>
            <td>
                <input type="button" name="editaddcustomer" value="Edit/Add Customer" onClick="enableFields()" />
                <br />
                <br />
                <br />
                <br />
                <input type="submit" name="formaction" value="Save-Start Delivery Order" />
                <br />
                <br />
                <br />
                <br />
                <input type="submit" name="formaction" value="Save-Start Pick Up Order" />
                </td></tr>
            </table>
            </form>     

        <%@ include file="staticpages/pageFooter.html" %>

order.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page language="java" import="java.util.*"%>
<%@ include file="staticpages/pageHeader.html" %>
<%@ page import="pizzapkg.OrderBean" %>

    Customer Info: 

    <%--<% Customer cust = (Customer) session.getAttribute("customer"); --%>
    Customer #: ${customer.cid}<br />
    <%-- <% cust.getCid(); %>
     <% cust.getCfname(); %> <% cust.getClname(); %><br />
     <% cust.getCaddress(); %><br />
     <% cust.getCcity(); %><br />
     <% cust.getCstate(); %>, <% cust.getCzip(); %>
     <% cust.getCphone(); %>$<br />
     <% cust.getCnotes(); %><br />--%> 
    <% OrderBean ob = (OrderBean) session.getAttribute("order"); %>
    Order #: <% ob.getOrderId(); %>
    Date/Time: <% ob.getOrderDate(); ob.getOrderTime(); %>
    <% ob.getOrderType(); %>

<%@ include file="staticpages/pageFooter.html" %>

ChooseCustomer Servlet

package pizzapkg;

        import java.io.IOException;
        import java.sql.ResultSet;

        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;
        import javax.servlet.http.HttpSession;

        /** Servlet implementation class ChooseCustomer  */
        @WebServlet("/ChooseCustomer")
        public class ChooseCustomer extends HttpServlet {
            private static final long serialVersionUID = 1L;

            /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  */
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                HttpSession session = request.getSession(true);
                session.isNew();

                // Create customer object
                Customer c = null;

                // Check which button was selected on index page. 
                if (request.getParameter("formaction").equals("Search")) {

                    // Create database object to search for customer phone number
                    Database db = (Database) getServletContext().getAttribute("db");

                    /* Search Database for existing customer */
                    String searchPhone = request.getParameter("phone1") 
                            + request.getParameter("phone2") 
                            + request.getParameter("phone3");
                    String sql = "SELECT * FROM customers WHERE cust_phone=\"" + searchPhone + "\";";
                    ResultSet rs;

                    try {
                        rs = db.runSqlQuery(sql);
                        rs.next();

                        // Check to see if any records were returned.
                        if (rs.isFirst()) {
                            // Get data from database and populate customer object
                            c = new Customer(rs.getString("cust_id"), rs.getString("cust_fname"), 
                                rs.getString("cust_lname"), rs.getString("cust_address"), 
                                rs.getString("cust_city"), rs.getString("cust_state"), 
                                rs.getString("cust_zip"), rs.getString("cust_phone"),
                                rs.getString("cust_notes"));
                                request.setAttribute("customerFound", "Yes");
                        }
                        else {
                            // Customer phone number not in database send error message.
                            request.setAttribute("customerFound", "No");                    
                        }
                    } catch (Exception e) { e.printStackTrace(); }

                    // Set request customer attribute
                    session.setAttribute("customer", c);

                    // If customer found forward to customer.jsp otherwise stay on index page. 
                    if (request.getAttribute("customerFound").equals("No")) {
                        RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
                        rd.forward(request, response);
                    }
                    else {              
                        RequestDispatcher rd = request.getRequestDispatcher("/customer.jsp");
                        rd.forward(request, response);
                    }           
                }
                else {
                    RequestDispatcher rd = request.getRequestDispatcher("/customer.jsp");
                    rd.forward(request, response);
                }       
            }
        }

Customersrvlt Servlet

    package pizzapkg;

    import java.io.IOException;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.text.SimpleDateFormat;

    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;
    import javax.servlet.http.HttpSession;

    /** Servlet implementation class Customersvlt */
    @WebServlet("/Customersvlt")
    public class Customersvlt extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            HttpSession session = request.getSession();

            String btn = request.getParameter("formaction");
            String delv = "Save-Start Delivery Order";

            // Create customer object
            Customer c = (Customer) session.getAttribute("customer");
            // Create database object
            Database db = (Database) getServletContext().getAttribute("db");

            String phone = request.getParameter("phone4") 
                    + request.getParameter("phone5") 
                    + request.getParameter("phone6");


            // If customer was not selected from database, insert customer
            if(request.getParameter("custid").isEmpty()) {              
                try {
                    // Get customer information from index form. 
                    c = new Customer(request.getParameter("custid"), 
                            request.getParameter("fname"), request.getParameter("lname"),
                            request.getParameter("address"), request.getParameter("city"), 
                            request.getParameter("state"),request.getParameter("zip"), phone, 
                            request.getParameter("notes")); 
                    c.setCid(db.insertCustomer(c));
                    String p = c.getCphone();
                    FormatPhone fp = new FormatPhone(p);
                    c.setCphone(fp.getPhone());                 
                    session.setAttribute("customer", c);
                } catch (SQLException e) { e.printStackTrace(); }
            }
            else if (request.getParameter("edited").equals("edited") 
                    && !request.getParameter("custid").isEmpty()) {

                // If customer was selected and edited update customer information.
                c.setCid(request.getParameter("custid"));
                try { 
                db.updateCustomer(c);
                String p = c.getCphone();
                FormatPhone fp = new FormatPhone(p);
                c.setCphone(fp.getPhone());
                session.setAttribute("customer", c);
                } catch (SQLException e) { e.printStackTrace(); }               
            }
            else {
                // Customer information was not edited just start order.
                String p = c.getCphone();
                FormatPhone fp = new FormatPhone(p);
                c.setCphone(fp.getPhone());
                //session.setAttribute("customer", c);
            }

            // Start order based on user selection
            //PizzaOrder po = null;
            ResultSet rs = null;
            OrderBean obean = null;
            if (btn.equals(delv)) {
                // Start new delivery order
                try {
                    rs = db.startOrder(c, "Delivery");
                    rs.next();

                } catch (SQLException e) { e.printStackTrace(); }
            }
            else {
                // Start new pickup order
                try {
                    rs = db.startOrder(c, "Pick Up");
                    rs.next();

                } catch (SQLException e) { e.printStackTrace(); }
            }
            //String id, String cd, String dt, String tm, String pd, double tt) {

            try {
                String d = new SimpleDateFormat("MM/dd/yyyy").format(rs.getDate("order_datetime"));
                String time = new SimpleDateFormat("h:mm a").format(rs.getTime("order_datetime"));
                obean = new OrderBean(rs.getString("order_id"), rs.getString("order_cust_id"),
                        d, time, rs.getString("order_pupdeliv"), rs.getDouble("order_total"));
            } catch (SQLException e) { e.printStackTrace(); }

            session.setAttribute("order", obean);
            RequestDispatcher rd = request.getRequestDispatcher("/order.jsp");
            rd.forward(request, response);          
        }       
    }

0 个答案:

没有答案