ga('set', 'anonymizeIp', 1);
Categories: CodingJAVA

[Java] Tomcat Server Session Control

Share

本文講述如何控管使用者登入登出之session。

Login頁面

建立form,連結至loginServlet。




Servlet – login

建立一個login servlet處理登入事件。範例程式登入後會跳轉至admin路徑下之loginSuccess.jsp頁面。


package !!!YOURPACKAGE!!!;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // Default valid login acc/pw
    private final String username = "admin";
    private final String password = "admin";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");

        if (this.username.equals(username) && this.password.equals(password)) {
            //get the old session and invalidate
            HttpSession oldSession = request.getSession(false);
            if (oldSession != null) {
                oldSession.invalidate();
            }
            //generate a new session
            HttpSession newSession = request.getSession(true);

            //setting session to expiry in 5 mins
            newSession.setMaxInactiveInterval(5*60);
            System.out.println(newSession.getId());

            //Cookie message = new Cookie("message", "Welcome");
            //response.addCookie(message);
            response.sendRedirect("admin/loginSuccess.jsp");
            System.out.println("Login successfully.");
        } else {
            System.out.println("Login failed.");
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }

}

Servlet – logout

建立一個logout servlet 處理登出事件。


package !!!YOURPACKAGE!!!;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/admin/logoutServlet")
public class logoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //invalidate the session if exists
        HttpSession session = request.getSession(false);
        if(session != null){
            System.out.println("session set invalidate.");
            session.invalidate();
        }  response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
}

處理到這邊,若使用者登出後再直接連入admin/loginSuccess.jsp會發現server還是沒有對session坐管控,仍然可以進到該頁面,所以我們必須做filter來控制。

Filter

Filter在此範例程式中,設計為,如連入admin路徑底下之連結,都須經過session認證,若認證不成功,直接跳轉回login登入頁。須注意Filter也要在web.xml中做設定。


package !!!YOURPACKAGE!!!;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class authenticationFilter implements Filter {
    private ServletContext context;
    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        HttpSession session = req.getSession(false);
        if (session == null) {   //checking whether the session exists
            this.context.log("Unauthorized access request");
            res.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            // pass the request along the filter chain
            chain.doFilter(request, response);
        }
    }
    public void destroy() {
        //close any resources here
    }
}

web.xml設定

請複製一份web.xml至WebContent下的WEB-INF資料夾中,並新增以下內容。(如果沒有放在該路徑底下,程式會出現找不到class的編譯錯誤。)


authenticationFilter!!!YOURPACKAGE!!!.authenticationFilterauthenticationFilter/admin/*

如此一來應該就能在登出後清除session,再進到admin路徑下的頁面會做filter的session管制了。

Jys

Published by
Jys

Recent Posts

[python] Flask Create RESTful API

This article gi... Read More

3 年 前發表

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

3 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表