HttpServlet 会话管理(一)(URL重写 表单隐藏域 简单示例)

2023-12-23 00:48

本文主要是介绍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重写 表单隐藏域 简单示例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/526136

相关文章

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

springboot简单集成Security配置的教程

《springboot简单集成Security配置的教程》:本文主要介绍springboot简单集成Security配置的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录集成Security安全框架引入依赖编写配置类WebSecurityConfig(自定义资源权限规则

golang 日志log与logrus示例详解

《golang日志log与logrus示例详解》log是Go语言标准库中一个简单的日志库,本文给大家介绍golang日志log与logrus示例详解,感兴趣的朋友一起看看吧... 目录一、Go 标准库 log 详解1. 功能特点2. 常用函数3. 示例代码4. 优势和局限二、第三方库 logrus 详解1.

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

Redis 中的热点键和数据倾斜示例详解

《Redis中的热点键和数据倾斜示例详解》热点键是指在Redis中被频繁访问的特定键,这些键由于其高访问频率,可能导致Redis服务器的性能问题,尤其是在高并发场景下,本文给大家介绍Redis中的热... 目录Redis 中的热点键和数据倾斜热点键(Hot Key)定义特点应对策略示例数据倾斜(Data S

JavaScript Array.from及其相关用法详解(示例演示)

《JavaScriptArray.from及其相关用法详解(示例演示)》Array.from方法是ES6引入的一个静态方法,用于从类数组对象或可迭代对象创建一个新的数组实例,本文将详细介绍Array... 目录一、Array.from 方法概述1. 方法介绍2. 示例演示二、结合实际场景的使用1. 初始化二

C#中的 StreamReader/StreamWriter 使用示例详解

《C#中的StreamReader/StreamWriter使用示例详解》在C#开发中,StreamReader和StreamWriter是处理文本文件的核心类,属于System.IO命名空间,本... 目录前言一、什么是 StreamReader 和 StreamWriter?1. 定义2. 特点3. 用

Java中&和&&以及|和||的区别、应用场景和代码示例

《Java中&和&&以及|和||的区别、应用场景和代码示例》:本文主要介绍Java中的逻辑运算符&、&&、|和||的区别,包括它们在布尔和整数类型上的应用,文中通过代码介绍的非常详细,需要的朋友可... 目录前言1. & 和 &&代码示例2. | 和 ||代码示例3. 为什么要使用 & 和 | 而不是总是使