将数据从servlet传输到jsp页面

时间:2014-02-09 03:49:50

标签: java jsp servlets

我想摆脱servlet中的printWriter代码。

基本上我想输出当前客户及其各自的城市,其ID是索引页面上的隐藏字段。从那里我希望能够编辑客户名称或城市,然后将其发送回索引页面,以便更新信息。

我该怎么做?

的Servlet

 package edu.witc.Assignment02.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
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 edu.witc.Assignment02_model.*;

/**
 * Servlet implementation class CustomerServlet
 */
@WebServlet(name = "CustomerServlet", urlPatterns = {
        "/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = -20L;

    private List<Customer> customers = new ArrayList<Customer>();


    /**
     * @see HttpServlet#HttpServlet()
     */
    public CustomerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public void init() throws ServletException {
        Customer customer1 = new Customer();
        customer1.setId(1);
        customer1.setName("Donald D.");
        customer1.setCity("Miami");
        customer1.add(customer1);

        Customer customer2 = new Customer();
        customer1.setId(2);
        customer1.setName("Mickey M.");
        customer1.setCity("Orlando");
        customer1.add(customer2);
    }

    private void sendCustomerList(HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><head><title>Customers</title></head>" 
                + "<body><h2>Custoemrs</h2>");
        writer.println("<ul>");
        for (Customer customer : customers){
            writer.println("<li>" + customer.getName() 
                   + "(" + customer.getCity() + ") (" 
                   + "<a href='editCustomer?id=" + customer.getId()
                   + ";>edit</a>)");
        }
        writer.println("</ul>");
        writer.println("</body></html>");
    }

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

    private void sendEditCustomerForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        Integer customerId = 0;
        try{
            customerId = Integer.parseInt(request.getParameter("id"));
        }catch(NumberFormatException e){

            }
        Customer customer = getCustomer(customerId);

        if(customer != null){
            writer.println("<html><head>"
                    + "<title>Edit Customer</title></head>"
                    + "<body><h2>Edit Customer</h2>"
                    + "<form method = 'post' action = 'updateCustomer'>");
            writer.println("<input type = 'hidden' name = 'id' value = 'customerId'/>");
            writer.println("<table>");
            writer.println("<tr><td>Name:</td><td>"
                    + "<input name = 'name' value = '"
                    + customer.getName().replaceAll("'", "&#39")
                    + "'/></td></tr>");
            writer.println("<tr><td>City:</td><td>"
                    + "<input name = 'city' value = '"
                    + customer.getCity().replaceAll("'", "&#39")
                    + "'/></td></tr>");
            writer.println("<tr>"
                    + "<td colspan='2' style = 'text-align: right'>"
                    + "<input type ='submit' value = 'Update'/></td>"
                    + "</tr>");
            writer.println("<tr><td colspan='2'>"
                    + "<a href = 'customer'>CustomerList</a>"
                    + "</td></tr>");
            writer.println("</table>");
            writer.println("</form></body>");
        }else{
            writer.println("No Customer Found");

        }
        }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //update customer
        Integer customerId = 0;
        try{
            customerId = Integer.parseInt(request.getParameter("id"));
        }catch(NumberFormatException e){

        }
        Customer customer = getCustomer(customerId);
        if(customer != null){
            customer.setName(request.getParameter("name"));
            customer.setCity(request.getParameter("city"));
        }
        sendCustomerList(response);
    }

}

客户类


 package edu.witc.Assignment02_model;

    public class Customer {
        private Integer id;
        private String name;
        private String city;

        public Integer getId(){
            return id;
        }

        public void setId(Integer id){
            this.id = id;
        }

        public String getName(){
            return name;
        }

        public void setName(String name){
            this.name = name;
        }

        public String getCity(){
            return city;
        }

        public void setCity(String city){
            this.city = city;
        }

        public void add(Customer customer1) {
            // TODO Auto-generated method stub

        }

    }

索引页


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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>Home</title>
</head>
<body>
<h1>Current Customer(s) w/City</h1><br>
<%! String name, city; %>

<%  %>






</body>
</html>

1 个答案:

答案 0 :(得分:0)

迟到总比没有好。

好的,要实现这一点,您应该将jstl库添加到项目中。

<强>的Servlet

 @WebServlet(name = "CustomerServlet", urlPatterns = {
        "/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = -20L;

    private List<Customer> customers = new ArrayList<Customer>();

    @Override
    public void init() throws ServletException {
        Customer customer1 = new Customer();
        ...
        customers.add(customer1);

        Customer customer2 = new Customer();
        ...
        customers.add(customer2);
    }

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


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if(uri.endsWith("/customer")){

            request.setAttribute("customers", customers);
            request.getRequestDispatcher("/customers.jsp").forward(request, response);

        }else if(uri.endsWith("/editCustomer")){

            try{
                customerId = Integer.parseInt(request.getParameter("id"));
            }catch(NumberFormatException e){
                e.printStackTrace();
            }
            Customer customer = getCustomer(customerId);

            request.setAttribute("customer", customer);
            request.getRequestDispatcher("/edit_customer.jsp").forward(request, response);

        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Integer customerId = 0;
        try{
            customerId = Integer.parseInt(request.getParameter("id"));
        }catch(NumberFormatException e){

        }
        Customer customer = getCustomer(customerId);
        if(customer != null){
            customer.setName(request.getParameter("name"));
            customer.setCity(request.getParameter("city"));
        }
        response.sendRedirect("/customer");
    }

}

<强> customers.jsp

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h1>Customer list</h1>

<ul>
<c:forEach var="c" items="${customers}">
    <li>${c.name} (<a href="editCustomer?id=${c.id}">Edit</a>)</li>
</c:forEach>
</ul>

<强> edit_customer.jsp

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<h1>Edit customer</h1>

<form method="POST" action="/updateCustomer">
    <input type="hidden" name="id" value="${customer.id}"/>
    Name: <input type="text" name="name" value="${customer.name}"/><br/>
    City: <input type="text" name="city" value="${customer.city}"/><br/>
    <input type="submit" value="Save"/>

</form>