servlet4 单元测试、Session、ServletConfig配置、ServletContext上下文


在这里插入图片描述

  单元测试。
  src 同级建立 test 文件夹,右键 -> Mark Directory as -> Sources Root,新建 java 测试类,写 java 测试方法,方法上写 @Test 标注,option + return快捷键 ,自动引入 junit4 的 jar 包。


import org.junit.*;

public class servletTest {

    @BeforeClass
    public void TestMethod1() {
        // 在整个单元测试之前运行,执行一次
    }

    @Before
    public void TestMethod2() {
        // 在每个单元测试之前运行
    }

    @Test
    public void TestMethod3() {
        // 这是一个单元测试的方法, 可以右键直接运行该方法
    }

    @After
    public void TestMethod4() {
        // 在每个单元测试之后运行
    }

    @AfterClass
    public void TestMethod5() {
        //在整个单元测试之后运行,执行一次
    }

}

  Session 对象。
  Session用于记录用户的状态。
  服务器会为每一次会话分配一个Session对象,同一个浏览器发起的多次请求,同属于一次会话(Session),一旦浏览器关闭,则结束会话。
  请求服务器时,服务器会自动创建 Session,并创建 Cookie 存储 SessionId 发送回客户端。
  SessionId 可传递任何数据(基本数据类型、对象、集合、数组)。

  Session 基本用法。


//获取Session对象
HttpSession session=request.getSession();
//唯一标记
System.out.println("Id:"+session.getId());

session.setAttribute("key",value);
session.getAttribute("key");
session.removeAttribute("key");

// 设置 session 最大有效期为一小时
session.setMaxInactiveInterval(60*60);

//手工销毁
session.invalidate();

  浏览器禁用 Cookie 后采用 URL 拼接方式发送 Session。


HttpSession session = request.getSession();
// URL追加 SessionId
String newUrl = response.encodeRedirectURL("/WebProject_war_exploded?JSESSIONID=" + session.getId());

response.sendRedirect(newUrl);

  Session 实现再次登陆时不输入用户名和密码。


<%-- index.jsp --%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

  <form method="post" action="loginServlet">
    用户名:<input type="text" name="username" value="admin"><br>
    密码:<input type="text" name="password" value="123"><br>
    <input type="submit" value="登陆"><br>
  </form>

  </body>
</html>


@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   

        response.setContentType("text/html;charset=utf8");

        String username = "admin";
        String password = "123";

        String reqUsername = request.getParameter("username");
        String reqPassword = request.getParameter("password");

        HttpSession session = request.getSession();

        if (reqUsername != null && reqUsername.length() > 0) {
   

            if (reqUsername.equals
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值