java - 从模型获取信息到 Servlet 再到 JSP 选项列表

标签 java jsp jakarta-ee servlets arraylist

我有一个模型,其中有一个数组列表。我还有一个需要从模型中提取的 servlet。最后,JSP 需要获取从 servlet( Controller )检索的信息并生成选择列表的选项。我不明白为什么这根本不起作用。我刚刚进入 jsp,所以任何帮助将不胜感激。

我有下面 3 页和堆栈跟踪。

所建议的任何有助于 future 发展的更改也会有所帮助。我非常开放,并且希望以正确的方式做到这一点。

模型(有数组列表)

package edu.witc.Assignment03.model;

import java.util.ArrayList;
import java.util.List;

public class States {

    private List<String> states = new ArrayList<>();{

    states.add("Alabama");
    states.add("Alaska"); 
    states.add("Arizona"); 
    states.add("Arkansas"); 
    states.add("California"); 
    states.add("Colorado"); 
    states.add("Connecticut"); 
    states.add("Delaware"); 
    states.add("Florida"); 
    states.add("Georgia"); 
    states.add("Hawaii"); 
    states.add("Idaho"); 
    states.add("Illinois"); 
    states.add("Indiana"); 
    states.add("Iowa"); 
    states.add("Kansas"); 
    states.add("Kentucky"); 
    states.add("Louisiana"); 
    states.add("Maine"); 
    states.add("Maryland"); 
    states.add("Massachusetts"); 
    states.add("Michigan"); 
    states.add("Minnesota"); 
    states.add("Mississippi"); 
    states.add("Missouri"); 
    states.add("Montana"); 
    states.add("Nebraska"); 
    states.add("Nevada"); 
    states.add("New Hampshire"); 
    states.add("New Jersey"); 
    states.add("New Mexico"); 
    states.add("New York"); 
    states.add("North Carolina"); 
    states.add("North Dakota"); 
    states.add("Ohio"); 
    states.add("Oklahoma"); 
    states.add("Oregon"); 
    states.add("Pennsylvania"); 
    states.add("Rhode Island"); 
    states.add("South Carolina"); 
    states.add("South Dakota"); 
    states.add("Tennessee"); 
    states.add("Texas"); 
    states.add("Utah"); 
    states.add("Vermont"); 
    states.add("Virginia"); 
    states.add("Washington"); 
    states.add("West Virginia"); 
    states.add("Wisconsin"); 
    states.add("Wyoming");
    }

    public List<String> getStates(){
        return this.states;
    }
}

Controller (Servlet)

package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;




import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;

/*
 * Not thread-safe. For illustration purpose only
 */
@WebServlet(name = "CustomerServlet", urlPatterns = { 
        "/customerManagement"})
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = -20L;

    private edu.witc.Assignment03.model.States states = new States();
    private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();



 private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
           throws IOException, ServletException {
    String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);
    }

    private void editCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
           throws IOException, ServletException {
        String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
    request.getRequestDispatcher(url).forward(request,response);
    }

    private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
            throws IOException, ServletException {
        String url = "/index.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);




    }

    private Customer getCustomer(int customerId) {
        for (Customer customer : customers) {
            if (customer.getCustomerId() == customerId) {
                return customer;
            }
        }
        return null;
    }



    private void sendEditCustomerForm(HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {

        String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);
    }


    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("/customer")) {
            sendCustomerList(response, request);
        } else if (uri.endsWith("/editCustomer")) {
            sendEditCustomerForm(request, response);
        }

        request.setAttribute("states", states);

    }



    public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        // update customer
        int customerId = 0;
        try {
            customerId = 
                    Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
        }
        Customer customer = getCustomer(customerId);
        if (customer != null) {
            customer.setFirstName(request.getParameter("firstName"));
            customer.setLastName(request.getParameter("lastName"));
            customer.setEmail(request.getParameter("email"));
            customer.setPhone(request.getParameter("phone"));
            customer.setAddress(request.getParameter("address"));
            customer.setCity(request.getParameter("city"));

            customer.setZip(request.getParameter("zip"));
        }
        addCustomer(response, request);
    }
}

JSP页面(带有选择/选项列表的表单)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.ArrayList" %>
<!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>Customer Management</title>
</head>
<body>
    <form action="/CustomerServlet" method="post">
        First Name:<br>
        <input type="text" name="firstName"/><br>
        Last Name:<br>
        <input type="text" name="lastName"/><br>
        Email:<br>
        <input type="text" name="email"/><br>
        Phone:<br>
        <input type="text" name="phone"/><br>
        Phone Type:<br>

        Street Address:<br>
        <input type="text" name="streetAddress"/><br>
        Apartment Number:<br>
        <input type="text" name="apartmentNumber"/><br>
        City:<br>
        <input type="text" name="city"/><br>


        State:<br>
        <select>
            <%
            edu.witc.Assignment03.model.States states = request.getAttribute("states");
            if(states!=null){   
            for (String state : states.getStates()) { 
                   out.println("<option>"+state+"</option>");
               }
             }else{
                 System.out.print("states is null");
             }
             %>
        </select><br>

        <input type="submit" value="submit">
        </form>
</body>
</html>

堆栈跟踪

Mar 30, 2014 8:17:13 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Justin_EJ_Assignment03_15400579] threw exception [Unable to compile class for JSP: 

An error occurred at line: 33 in the jsp file: /customerManagement.jsp
Type mismatch: cannot convert from Object to States
30:         State:<br>
31:         <select>
32:             <%
33:             edu.witc.Assignment03.model.States states = request.getAttribute("states");
34:             if(states!=null){   
35:             for (String state : states.getStates()) { 
36:                    out.println("<option>"+state+"</option>");


Stacktrace:] with root cause
org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 33 in the jsp file: /customerManagement.jsp
Type mismatch: cannot convert from Object to States
30:         State:<br>
31:         <select>
32:             <%
33:             edu.witc.Assignment03.model.States states = request.getAttribute("states");
34:             if(states!=null){   
35:             for (String state : states.getStates()) { 
36:                    out.println("<option>"+state+"</option>");


Stacktrace:
    at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
    at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:468)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

最佳答案

getAttribute()返回 Object 所以你需要添加强制转换,最好在这里使用 JSTL

<c:forEach var="state" items="states">
        <option>
            <c:out value="${person.name}" />
        </option>
</c:forEach>

关于java - 从模型获取信息到 Servlet 再到 JSP 选项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751696/

相关文章:

java - 我想使用 for 循环来关闭一些方法

java - 将对象数据从 JSP 传递到 Spring Controller Post 方法而不是 GET 方法

java - 在我的例子中,JSF 中选择哪种用户身份验证?

java - 使用动态生成的类进行 Hazelcast 用户代码部署

java - 无法构造 `class name` 的实例(尽管至少在 Creator 上存在)

java - Jsp 不显示 swf 文件

java - 决定请求类的类型?

java - 不使用 Websphere Deployment Manager 部署 Web 应用程序

java - 如何在 org.jboss.logging 中设置运行时日志记录

java - 如何使用 struts2 标签遍历 JSP 中的 bean 数组列表