将数据从servlet传输到jsp页面 [英] Transferring data from servlet to jsp page

查看:86
本文介绍了将数据从servlet传输到jsp页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想摆脱servlet中的printWriter代码.

I would like to get rid of the printWriter code in the servlet.

基本上,我想输出当前客户及其所属城市的ID,该ID是索引页面上的隐藏字段.在这里,我希望能够编辑客户名称或城市,然后将其发送回索引页面,在该页面上将更新信息.

Basically I want to output the current customers and their respective cities with the id which is a hidden field on the index page. From there I would like to be able to edit the customer name or city and then have it sent back to the index page where the information would be updated.

我该怎么做?

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>

推荐答案

迟到总比没有好.

好吧,要使其正常工作,您应该在您的库中添加 jstl 库项目.

Ok, to get this working you should add jstl library to your project.

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>

这篇关于将数据从servlet传输到jsp页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆