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>

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/79610181
今日推荐