简体   繁体   中英

Transferring data from servlet to jsp page

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

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.

How do I do this?

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);
    }

}

Customer Class


 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

        }

    }

index page


<%@ 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>

Better late than never.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM