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

相关文章

基于Qt开发一个简单的OFD阅读器

《基于Qt开发一个简单的OFD阅读器》这篇文章主要为大家详细介绍了如何使用Qt框架开发一个功能强大且性能优异的OFD阅读器,文中的示例代码讲解详细,有需要的小伙伴可以参考一下... 目录摘要引言一、OFD文件格式解析二、文档结构解析三、页面渲染四、用户交互五、性能优化六、示例代码七、未来发展方向八、结论摘要

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Apache Tomcat服务器版本号隐藏的几种方法

《ApacheTomcat服务器版本号隐藏的几种方法》本文主要介绍了ApacheTomcat服务器版本号隐藏的几种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需... 目录1. 隐藏HTTP响应头中的Server信息编辑 server.XML 文件2. 修China编程改错误

Java中ArrayList的8种浅拷贝方式示例代码

《Java中ArrayList的8种浅拷贝方式示例代码》:本文主要介绍Java中ArrayList的8种浅拷贝方式的相关资料,讲解了Java中ArrayList的浅拷贝概念,并详细分享了八种实现浅... 目录引言什么是浅拷贝?ArrayList 浅拷贝的重要性方法一:使用构造函数方法二:使用 addAll(

Golang使用etcd构建分布式锁的示例分享

《Golang使用etcd构建分布式锁的示例分享》在本教程中,我们将学习如何使用Go和etcd构建分布式锁系统,分布式锁系统对于管理对分布式系统中共享资源的并发访问至关重要,它有助于维护一致性,防止竞... 目录引言环境准备新建Go项目实现加锁和解锁功能测试分布式锁重构实现失败重试总结引言我们将使用Go作

JAVA利用顺序表实现“杨辉三角”的思路及代码示例

《JAVA利用顺序表实现“杨辉三角”的思路及代码示例》杨辉三角形是中国古代数学的杰出研究成果之一,是我国北宋数学家贾宪于1050年首先发现并使用的,:本文主要介绍JAVA利用顺序表实现杨辉三角的思... 目录一:“杨辉三角”题目链接二:题解代码:三:题解思路:总结一:“杨辉三角”题目链接题目链接:点击这里

SpringBoot使用注解集成Redis缓存的示例代码

《SpringBoot使用注解集成Redis缓存的示例代码》:本文主要介绍在SpringBoot中使用注解集成Redis缓存的步骤,包括添加依赖、创建相关配置类、需要缓存数据的类(Tes... 目录一、创建 Caching 配置类二、创建需要缓存数据的类三、测试方法Spring Boot 熟悉后,集成一个外

SpringBoot实现基于URL和IP的访问频率限制

《SpringBoot实现基于URL和IP的访问频率限制》在现代Web应用中,接口被恶意刷新或暴力请求是一种常见的攻击手段,为了保护系统资源,需要对接口的访问频率进行限制,下面我们就来看看如何使用... 目录1. 引言2. 项目依赖3. 配置 Redis4. 创建拦截器5. 注册拦截器6. 创建控制器8.

SpringBoot使用minio进行文件管理的流程步骤

《SpringBoot使用minio进行文件管理的流程步骤》MinIO是一个高性能的对象存储系统,兼容AmazonS3API,该软件设计用于处理非结构化数据,如图片、视频、日志文件以及备份数据等,本文... 目录一、拉取minio镜像二、创建配置文件和上传文件的目录三、启动容器四、浏览器登录 minio五、

Springboot使用RabbitMQ实现关闭超时订单(示例详解)

《Springboot使用RabbitMQ实现关闭超时订单(示例详解)》介绍了如何在SpringBoot项目中使用RabbitMQ实现订单的延时处理和超时关闭,通过配置RabbitMQ的交换机、队列和... 目录1.maven中引入rabbitmq的依赖:2.application.yml中进行rabbit