本文主要是介绍HttpServlet 会话管理(一)(URL重写 表单隐藏域 简单示例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文代码转载自《Servlet、JSP和Spring MVC初学指南》
会话管理的目的是记录用户访问的状态,
使得之前的Http访问状态可以被之后的应用直接使用,状态的记录即通过请求传值被记录应用的过程,所以也可以看成 不同请求方式与不同的页面跳转形式的结合。下面先分别针对GET\POST 给出通过URL重写及隐藏域的方法进行状态传送、 会话管理的实例。URL重写的例子如下,就是简单的GET请求页面跳转
package main.ServletStudy;/*** Created by ehang on 2017/2/9.*/import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;@WebServlet(name = "Top10Servlet",urlPatterns = {"/top10"} ) public class Top10Servlet extends HttpServlet {private static final long serialVersionUID = 987654321L;private List<String> londonAttractions;private List<String> parisAttrictions;@Overridepublic void init()throws ServletException{londonAttractions = new ArrayList<String>(10);londonAttractions.add("Buckingham Palace");londonAttractions.add("London Eye");londonAttractions.add("British Museum");londonAttractions.add("Notaional Gallery");londonAttractions.add("Big Ben");londonAttractions.add("Tower of London");londonAttractions.add("Natural History Museum");londonAttractions.add("Canary Wharf");londonAttractions.add("2012 Olympic Park");londonAttractions.add("St Paul's Cathedral");parisAttrictions = new ArrayList<String>(10);parisAttrictions.add("Eiffel Tower");parisAttrictions.add("Notre Dame");parisAttrictions.add("The Louvre");parisAttrictions.add("Champs Elysees");parisAttrictions.add("Arc de Triomphe");parisAttrictions.add("Sainte Chapelle Church");parisAttrictions.add("Les Invalides");parisAttrictions.add("Musee d'Orsay");parisAttrictions.add("Montmarte");parisAttrictions.add("Sacre Couer Basilica");}@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{String city = request.getParameter("city");if(city!= null&&(city.equals("london")||city.equals("paris"))){showAttractions(request, response, city);}else{showMainPage(request, response);}}private void showMainPage(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{response.setContentType("text/html");PrintWriter writer = response.getWriter();writer.println("<html><head><title>Top 10 Tourist Attractions</title></head><body>" +"Please select a city:" +"<br/><a href = '?city=london'>London</a>" +"<br/><a href = '?city=paris'>Paris</a>" +"</body></html>");}private void showAttractions(HttpServletRequest request, HttpServletResponse response, String city)throws ServletException, IOException{int page = 1;String pageParameter = request.getParameter("page");if(pageParameter!= null){try{page = Integer.parseInt(pageParameter);}catch(NumberFormatException e){}if(page > 2){page = 1;}}List<String> attractions = null;if(city.equals("london")){attractions = londonAttractions;}else if(city.equals("paris")){attractions = parisAttrictions;}response.setContentType("text/html");PrintWriter writer = response.getWriter();writer.println("<html><head><title>Top 10 Tourist Attraction</title></head><body>" +"<a href = 'top10'>Select City</a>");writer.println("<hr/>Page " + page + "<hr/>");int start = page * 5 - 5;for(int i = start;i < start + 5;i ++){writer.println(attractions.get(i) + "</br>");}writer.print("<hr style = 'color:blue'/><a href = '?city=" + city + "&page=1'>Page 1</a>");writer.print(" <a href = '?city=" + city + "&page=2'>Page 2</.a>");writer.println("</body></html>");}}
隐藏域的方式即是利用input(type = 'hidden'')的隐藏表单记录一个默认POST参数, 使得默认传值得以进行。(这种方法仅能应用于表单情形,因其需要input submit来提交请求) 下面是简单例子
package main.ServletStudy;/*** Created by ehang on 2017/2/9.*/public class Customer {private int id;private String name;private String city;public int getId(){return id;}public void setId(int 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;}}import java.io.IOException; import java.io.PrintWriter; import java.net.HttpRetryException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;@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>();@Overridepublic void init() throws ServletException{Customer customer1 = new Customer();customer1.setId(1);customer1.setName("Donald D.");customer1.setCity("Miami");customers.add(customer1);Customer customer2 = new Customer();customer2.setId(2);customer2.setName("Mickey M.");customer2.setCity("Orlando");customers.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>Customers</h2><ul>");for(Customer customer: customers){writer.println("<li>" + customer.getName() + "(" + customer.getCity() + ") (" +"<a href = 'editCustomer?id=" + customer.getId() + "'>edit</a>)");}writer.println("</ul></body></html>");}private Customer getCustomer(int 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();int 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'>" +"<input type = 'hidden' name = 'id' value = '" + customerId + "'/>" +"<table>" +"<tr><td>Name:</td><td>" +"<input name = 'name' value = '" + customer.getName().replaceAll("'", "'") +"'/></td></tr>" +"<tr><td>City:</td><td>" +"<input name = 'city' value = '" + customer.getCity().replaceAll("'", "'") +"'/></td></tr>" +"<tr><td colspan = '2' style = 'text-align:right'>" +"<input type = 'submit' value = 'Update'></td></tr>" +"<tr><td colspan = '2'><a href = 'customer'>Customer List</a></td></tr>" +"</table></form></body></html>");}else{writer.println("No customer found");}}@Overridepublic 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);}}@Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response) throws HttpRetryException, IOException {int 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);}}
该例与之前的例子的不同是通过request.getRequestURI()来进行URI判断进行同一个Servlet的不同页面的访问处理。 html td标签 colspan指定宽度跨多少列。URL重写及隐藏域的方法适用于较少的页面跳转。
这篇关于HttpServlet 会话管理(一)(URL重写 表单隐藏域 简单示例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!