jsp:通過Session控制登陸時間和內部頁面的訪問
阿新 • • 發佈:2017-12-14
erro attr 行數 its text client fault pri getattr
一,通過session的關閉瀏覽器銷毀,和使用getAttribute設置session對象值來控制頁面用戶是否有權限進入。
1,以下是登陸頁面的代碼,使用表單提交數據給一個servlet進行數據的處理
<form action="com.in.User" method="post"> <div class="loginbox"> <div class="errorbox"><i class="error"></i>用戶名或密碼錯誤,請重新輸入!</div> <div class="logongroup"> <input class="intext" type="text" name="UserName" placeholder="用戶名" /> <i class="user"></i> </div> <div class="logongroup"> <input class="intext" type="password" name="PassWord" placeholder="密碼" /> <i class="password"></i> </div> <div class="logongroup submitbox"> <button class="submitbtn" type="submit">登 錄</button> </div> </div> </form>
2,創建一個名為User的servlet頁面
在doget方法中創建session對象,使用setAttribute方法為其賦值,
package com.in; import java.io.IOException; import java.io.PrintWriter; 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 User extends HttpServlet { /** * Constructor of the object. */ public User() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); session.setAttribute("user","yes"); request.getRequestDispatcher("default.jsp").forward(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
3,在登陸之後的頁面中加入以下代碼,以控制頁面的訪問權限。
放在<body>的下方,如果session為空或不等於上面賦的值,便跳轉到登陸頁面,重新為session賦值。
<% String aa=(String)session.getAttribute("user"); if(!"yes".equals(aa)&&aa==null){ response.sendRedirect("longin.jsp"); } %>
jsp:通過Session控制登陸時間和內部頁面的訪問