单元测试。
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