3 Replies - 1898 Views - Last Post: 10 February 2014 - 03:30 PM

#1 jesders88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 25-October 12

getting data from servlet to jsp

Posted 09 February 2014 - 11:55 AM

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? The most extended way would be best. I am a beginner at jsps and servlets. I would like it heavily commented if possible. Can anyone help?


Model
-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
		
	}

}





Controller
-Customer 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");
        

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

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

}




view
-index.jsp

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



Is This A Good Question/Topic? 0
  • +

Replies To: getting data from servlet to jsp

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1159
  • View blog
  • Posts: 2,547
  • Joined: 05-May 05

Re: getting data from servlet to jsp

Posted 09 February 2014 - 06:44 PM

Let's start simple here. Your model looks fine. I really don't see the need for a JSP page, when it's nothing more than a compiled servlet. Scrap it for simplicity, and have the servlet pick up on the URL pattern for the index page. Again, for simplicity lets have the index page show the full list of customers. That's fairly straightforward. For each entry, add a widget to let the user edit the entry. In the example below, I use a checkbox button.

@WebServlet(name = "CustomerServlet", urlPatterns = {
        "", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {

    private List<Customer> customers;

    @Override
    public void init() throws ServletException {
	customers = new ArrayList<>();
	customers.add(new Customer("name1", "addr1"));
	customers.add(new Customer("name2", "addr2"));
	customers.add(new Customer("name3", "addr3"));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
	PrintWriter out = response.getWriter();
	
	//Show a table of the customers with a edit checkbox for each
	
        //Or whatever the index page URL ends with
        if(request.getRequestURI().endsWith("/")){
            out.println("<form method='post' action='/editCustomer'><table>");
            for(Customer c: customers)
            {
        	out.println("<tr><td>");
        	out.print(c.getName());
        	out.print("</td><td>");
        	out.print(c.getAddress());
        	out.print("</td><td>");
        	out.print("Edit <input type='checkbox' name='cust_name' value='"+c.getName()+"'>");
        	out.println("</td></tr>");
            }
            out.println("<tr>");
            out.print("<td><input type='submit' value='Submit'/></td>");
    	    out.println("</tr>");
            out.println("</table></form>");
        }
        else if(request.getRequestURI().endsWith("/editCustomer")){
            String name = request.getParameter("cust_name");
            Customer c = null;//findCustomer(name);
            //Show customer form whose submission calls updateCustomer
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#3 jesders88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 46
  • Joined: 25-October 12

Re: getting data from servlet to jsp

Posted 09 February 2014 - 08:56 PM

View Postblackcompe, on 09 February 2014 - 06:44 PM, said:

Let's start simple here. Your model looks fine. I really don't see the need for a JSP page, when it's nothing more than a compiled servlet. Scrap it for simplicity, and have the servlet pick up on the URL pattern for the index page. Again, for simplicity lets have the index page show the full list of customers. That's fairly straightforward. For each entry, add a widget to let the user edit the entry. In the example below, I use a checkbox button.

@WebServlet(name = "CustomerServlet", urlPatterns = {
        "", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {

    private List<Customer> customers;

    @Override
    public void init() throws ServletException {
	customers = new ArrayList<>();
	customers.add(new Customer("name1", "addr1"));
	customers.add(new Customer("name2", "addr2"));
	customers.add(new Customer("name3", "addr3"));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
	PrintWriter out = response.getWriter();
	
	//Show a table of the customers with a edit checkbox for each
	
        //Or whatever the index page URL ends with
        if(request.getRequestURI().endsWith("/")){
            out.println("<form method='post' action='/editCustomer'><table>");
            for(Customer c: customers)
            {
        	out.println("<tr><td>");
        	out.print(c.getName());
        	out.print("</td><td>");
        	out.print(c.getAddress());
        	out.print("</td><td>");
        	out.print("Edit <input type='checkbox' name='cust_name' value='"+c.getName()+"'>");
        	out.println("</td></tr>");
            }
            out.println("<tr>");
            out.print("<td><input type='submit' value='Submit'/></td>");
    	    out.println("</tr>");
            out.println("</table></form>");
        }
        else if(request.getRequestURI().endsWith("/editCustomer")){
            String name = request.getParameter("cust_name");
            Customer c = null;//findCustomer(name);
            //Show customer form whose submission calls updateCustomer
        }
    }
}






The problem is I want to get away from print writer. I want to learn how to be able to get information like listing the name and city on the jsp page but actually retrieve that from the servlet
Was This Post Helpful? 0
  • +
  • -

#4 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1159
  • View blog
  • Posts: 2,547
  • Joined: 05-May 05

Re: getting data from servlet to jsp

Posted 10 February 2014 - 03:30 PM

Have your servlets process the input, use HttpServletRequest.setAttribute as a buffer for the JSP page to retrieve whatever outputs you create in the servlet, and then call HttpServletRequest.getRequestDispatcher.forward to hand the request off to the JSP page. You can use EL or JSTL in your page rendering.

This post has been edited by blackcompe: 10 February 2014 - 03:31 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1