servlet4 單元測試、Session、ServletConfig配置、ServletContext上下文
阿新 • • 發佈:2020-12-23
單元測試。
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(username)
&& reqPassword.equals(password)) {
System.out.println("登陸成功");
// 寫入session key 作重登陸
session.setAttribute("username","admin");
session.setAttribute("password","123");
} else {
System.out.println("登陸失敗");
}
} else {
// 重新登陸,需要重新開啟地址
if (session.getAttribute("username").equals(username)
&& session.getAttribute("password").equals(password)) {
System.out.println("重登陸成功");
} else {
System.out.println("重登陸失敗");
}
}
}
}
ValidateCode.jar 圖片驗證碼的使用。
<%-- index.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form method="post" action="webServlet">
使用者名稱:<input type="text" name="username" value="admin"><br>
密碼:<input type="text" name="password" value="123"><br>
code:<input type="text" name="code"> <img src="codeServlet"><br>
<input type="submit" value="登陸"><br>
</form>
</body>
</html>
@WebServlet("/codeServlet")
public class codeServlet 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 {
System.out.println("codeServlet");
ValidateCode validateCode = new ValidateCode();
String code = validateCode.getCode();
request.getSession().setAttribute("code",code);
// 位元組流,把這個圖片的流直接響應給瀏覽器,<img> 可接收
validateCode.write(response.getOutputStream());
// 字元流
// response.getWriter();
}
}
WebServlet("/webServlet")
public class webServlet 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 reqUsername = request.getParameter("username");
String reqPassword = request.getParameter("password");
String reqCode = request.getParameter("code");
// 取出 session 儲存的 code 用來比對
String code =(String) request.getSession().getAttribute("code");
System.out.println("reqUsername:" + reqUsername + " reqPassword:" + reqPassword + " reqCode:" + reqCode + " code:" + code);
}
}
ServletConfig 讀取 web.xml 的初始化配置。
@WebServlet(
value = "/webServlet",
initParams = {
@WebInitParam(name = "username", value = "admin"),
@WebInitParam(name = "password", value = "123")
},
// 優先順序
loadOnStartup = 1
)
public class webServlet extends HttpServlet {
private String username = null;
private String password = null;
@Override
public void init() throws ServletException {
// 讀取配置檔案
ServletConfig servletConfig = this.getServletConfig();
username = servletConfig.getInitParameter("username");
password = servletConfig.getInitParameter("password");
System.out.println("username " + username);
System.out.println("password " + password);
}
}
ServletContext 物件。
一個應用對應唯一 ServletContext。
在 Web 伺服器啟動時建立,伺服器關閉時銷燬。
基本用法。
// 1 獲取 context 物件,都是同一個物件
ServletContext servletContext1 = request.getServletContext();
// 2
ServletContext servletContext3 = this.getServletConfig().getServletContext();
// 3
ServletContext servletContext4 = this.getServletContext();
System.out.println(servletContext1 + "\t" + servletContext3 + "\t" + servletContext4 + "\t");
servletContext.setAttribute(“name”,value);
servletContext.getAttribute(“name”);
servletContext.removeAttribute(“name”);
// 獲取當前專案在伺服器釋出的真實路徑
String realpath=servletContext.getRealPath("/");
//上下文路徑(應用程式名稱)
System.out.println(servletContext.getContextPath());
System.out.println(request.getContextPath());
ServletContext 統計當前專案線上人數。
@WebServlet("/loginContextServlet")
public class loginContextServlet 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 {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf8");
String username = request.getParameter("username");
if (username == null || username.length() == 0) {
response.getWriter().write("使用者名稱不能為空");
return;
}
ServletContext servletContext = this.getServletContext();
List<String> list =(List<String>) servletContext.getAttribute("onlineNum");
if (list == null) {
// 例項化集合
list = new ArrayList<>();
} else {
if (list.contains(username)) {
response.getWriter().write("你已經登陸了");
return;
}
}
list.add(username);
servletContext.setAttribute("onlineNum", list);
response.getWriter().write("歡迎 " + username + "登陸成功");
}
}
// 顯示登陸的人數
@WebServlet("/viewOnlineNumServlet")
public class viewOnlineNumServlet 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");
ServletContext servletContext = this.getServletContext();
Object onlineNum = servletContext.getAttribute("onlineNum");
List<String> list = (List<String>) onlineNum;
if (list == null) {
response.getWriter().write("目前線上0人");
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append("<html>");
buffer.append("<body>");
buffer.append("<h3>" + "目前線上: " + list.size() +"人</h3>");
buffer.append("<h4>線上人數列表: </h4><br>");
for (String username : list) {
buffer.append("<ul>");
buffer.append("<li>" + username +"</li>");
buffer.append("</ul>");
}
buffer.append("</body>");
buffer.append("</html>");
response.getWriter().write(buffer.toString());
}
}