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;

    @Override
    public 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");
    }

    @Override
    public 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>();

    @Override
    public 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");
        }

    }

    @Override
    public 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);
        }
    }

    @Override
    public 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重写及隐藏域的方法适用于较少的页面跳转。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领,每个领都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值