Session保存用戶名
1.構造登錄界面
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Session保存用戶名</title> </head> <body> <form action="doS3" method= "post"> 用戶名:<input type="text" name="name"/><br/> 密 碼:<input type="password" name = "pwd"><br/> <input type="submit"> </form> </body> </html>
2.獲取Session並將用戶名保存到Session域對象中
package com.oaec.session;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class servletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
// req.getAttribute(arg0)
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
if ("高圓圓".equals(name) && "123".equals(pwd)) {
// 將用戶名保存在session中
// 1.獲得session
HttpSession session = req.getSession();
// 2.將用戶名保存在session中
session.setAttribute("uname", name);
resp.sendRedirect("doS4");
} else {
resp.sendRedirect("index.html");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3.從Session中取出數據 並對頁面進行保護 沒有登錄通過URL訪問 直接重定向到登錄界面 即主頁
package com.oaec.session;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class servletDemo4 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//從session中取出數據
HttpSession session = req.getSession(false);
Object object = null;
if (session != null && (object = session.getAttribute("uname"))!=null) {
PrintWriter writer = resp.getWriter();
writer.write("登錄成功<br>");
writer.write("歡迎你"+object);
}else {
//沒有登錄過 直接重定向到主頁
resp.sendRedirect("index.html");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
