1. 程式人生 > >servlet+filter請求轉發、登入、訪問控制

servlet+filter請求轉發、登入、訪問控制

配置檔案

<welcome-file-list>
        <welcome-file>view/home/index.jsp</welcome-file>
    </welcome-file-list>
    <!--路徑轉發的控制器-->
    <servlet>
        <servlet-name>DispatchersServlet</servlet-name>
        <servlet-class>service.DispatchersServlet</servlet-class
>
</servlet> <servlet-mapping> <servlet-name>DispatchersServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--登入檢測的過濾器--> <filter> <filter-name>LoginFilter</filter-name>
<filter-class>service.LoginFilter</filter-class> <!--初始化的引數--> <init-param> <!--頁面編碼UTF-8--> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param
>
<!--過濾跳轉的頁面--> <param-name>loginPage</param-name> <param-value>/view/login/index.jsp</param-value> </init-param> </filter> <!--過濾的頁面--> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/view/*</url-pattern> </filter-mapping>

控制路由轉發的servlet

package service;

import controller.LoginController;

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 java.io.IOException;

@WebServlet(name = "DispatchersServlet")
public class DispatchersServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        // 獲取訪問的路徑
        String url = request.getRequestURI();
//      System.out.println("url:"+ url);
        // 拆分路徑
        String path = url.substring(url.indexOf("/") + 1, url.lastIndexOf("."));
        System.out.println("path:" + path);
        // 例子: Login/index   =>  ['Login', 'index']
        String ary[] = path.split("/");
//      System.out.println("ary:" + java.util.Arrays.toString(ary));
        // 如果拆分的路徑不是兩個字串, 則跳轉到404頁面
        if(ary.length != 2){
            request.getRequestDispatcher("/view/error/404.jsp").forward(request, response);
        }else{
            if("Login".equals(ary[0])){
                // 第一個字串是 Login, 就new一個LoginController的servlet的控制類
                LoginController login = new LoginController();
                if("index".equals(ary[1])){
                    // 載入登入頁面
                    login.index(request, response);
                }else if("submit".equals(ary[1])){
                    // 登入
                    login.submit(request, response);
                }else if("logout".equals(ary[1])){
                    // 退出登入
                    login.logout(response, request);
                }
            }
        }
    }
}

filter過濾器

package service;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    // 獲取配置檔案的資訊
    private String encoding = null;
    private String loginPage = null;
    private String respEncoding = null;
    // 銷燬過濾器
    public void destroy() {
        System.out.println("銷燬過濾器!");
    }
    // 具體的過濾的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 設定返回資料的編碼方法為utf-8
        resp.setContentType(respEncoding);
        // 設定接收資料的編碼方式為utf-8
        req.setCharacterEncoding(encoding);
        // 將req resp 轉為子介面的型別
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        // 獲取路徑
        String urlPath = request.getServletPath();
        System.out.println(urlPath);
        // 獲取session
        HttpSession session = request.getSession(true);
        // 如果所在頁面不是登入頁面並且沒有session資料則跳轉到登入頁面,否則放行
        if(session.getAttribute("user") == null && !("/view/login/index.jsp".equals(urlPath))){
            response.sendRedirect(loginPage);
            return;
        }else{
            chain.doFilter(request, response);
            return;
        }
    }
    // 初始化方法
    public void init(FilterConfig config) throws ServletException {
        this.encoding = config.getInitParameter("encoding");
        this.loginPage = config.getInitParameter("loginPage");
        this.respEncoding = config.getInitParameter("respEncoding");
        System.out.println("初始化過濾器!");
    }

}

處理登入的servlet控制器

package controller;

import dbDao.checkUser;
import javaBean.Users;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginController {

    /*
        載入登入首頁
     */
    public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.sendRedirect("/view/login/index.jsp");
    }

    /*
        登入表單提交
     */
    public void submit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
        Users user = new Users(userName, passWord);
        checkUser cu = new checkUser();
        boolean ok = cu.OkUser(user);
        if(ok){
            request.getSession().setAttribute("user", user);
            response.sendRedirect("/view/home/index.jsp");
        }else{
            response.sendRedirect("/view/login/register.jsp");
        }
    }

    /*
        退出登入
     */
    public void logout(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException{
        request.getSession().invalidate();
        response.sendRedirect("/view/home/index.jsp");
    }
}

登入頁面

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/3/15
  Time: 20:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>登入</title>
    <link rel="stylesheet" href="/css/bootstrap.css">
</head>
<body>
    <div class="container-fluid" style="margin: 12% auto;">
        <h1 class="text-center" style="margin-bottom: 20px;">登入</h1>
        <div class="row" style="width: 80%; margin: auto;">
            <div class="col-md-6 col-md-offset-3">
                <form class="form-horizontal " action="/Login/submit.do">
                    <div class="form-group" style="margin: 10px auto;">
                        <label for="inputEmail3" class="col-sm-2 control-label">使用者名稱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="inputEmail3" placeholder="請輸入使用者名稱" name="username">
                        </div>
                    </div>
                    <div class="form-group" style="margin: 10px auto;">
                        <label for="inputPassword3" class="col-sm-2 control-label">密  碼</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" id="inputPassword3" placeholder="請輸入密碼" name="password">
                        </div>
                    </div>
                    <div class="form-group" style="margin: 10px auto;">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox"> 記住我
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group" style="margin: 10px auto;">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-default">登入</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
<script src="/js/jquery.js"></script>
<script src="/js/bootstrap.js"></script>
</html>

簡易首頁

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2018/3/13
  Time: 13:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
      <title>首頁</title>
    </head>
    <body>
        <c:set value="${sessionScope.user.userName}" var="num" scope="session"/>
        <%--<c:out value="${num}" />--%>
        <c:choose>
            <c:when test="${num != null}">
                <h1><span>使用者名稱</span>${sessionScope.user.userName}</h1>
                <br/>
                <h2><a href="/Login/logout.do" style="text-decoration: none;">退出登入</a></h2>
            </c:when>
            <c:otherwise>
                <h1><span>使用者名稱</span>未登入</h1>
            </c:otherwise>
        </c:choose>
        <a href="/Login/index.do">登入1</a>
        <a href="/getList.do">登入2</a>
    </body>
</html>