SSM+juery+bootstrap+layer+登录拦截

本文介绍了如何使用Spring、Struts2和MyBatis(SSM)框架,结合jQuery、Bootstrap和Layer组件来实现网页的登录拦截功能。详细讲述了web.xml的配置细节,LoginFilter的实现,以及相关控制器和JSP页面的代码结构和内容,确保静态资源不受拦截。

代码结构如下:
这里写图片描述

web.xml的配置如下(
loginFilter
*.do
)的配置要小心我被卡住过,静态资源被拦截:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1" metadata-complete="true">
    <servlet > 
        <servlet-name>DispatcherServlet</servlet-name >
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class > 
        <init-param>  
            <param-name>contextConfigLocation</param-name > 
            <param-value>classpath:spring/spring-*.xml</param-value > 
        </init-param>
    </servlet> 
    <servlet-mapping> 
        <servlet-name>DispatcherServlet</servlet-name > 
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <!-- 检查用户是否登录过的web.xml配置 -->
    <filter>
        <filter-name>loginFilter</filter-name>
        <filter-class>com.soecode.lyf.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>

    <error-page>
    <error-code>404</error-code>
    <location>/404.jsp</location>
    </error-page>
    <error-page>
    <error-code>500</error-code>
    <location>/500.jsp</location>
    </error-page>

</web-app>

com/soecode/lyf/filter/LoginFilter.java代码如下:

package com.soecode.lyf.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
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 LoginFilter implements Filter{

    @Override
    public void destroy() {


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;  
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String currentURL = request.getRequestURI();
        // 取得根目录所对应的绝对路径
        String targetURL = currentURL.substring(currentURL.indexOf("/", 1),   currentURL.length()); 
        HttpSession session = request.getSession(false);
        // 判断当前页是否是重定向以后的登录页面页面,如果是就不做session的判断,防止出现死循环
        if (!"/index.jsp".equals(targetURL)&&!"/main/checkUser.do".equals(targetURL)) {
            if (session == null || session.getAttribute("loginUser") == null) {  
                // 如果session为空表示用户没有登录就重定向到index.jsp页面  
                response.sendRedirect(request.getContextPath() + "/index.jsp");  
                return;  
            }  
        }

        filterChain.doFilter(request, response); 

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {


    }

}

com/soecode/lyf/web/IUserController.java的代码如下:

package com.soecode.lyf.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.soecode.lyf.dto.Result;
import com.soecode.lyf.entity.IUser;
import com.soecode.lyf.service.IUserService;

@Controller
@RequestMapping("/main")
public class IUserController {

    Logger logger = Logger.getLogger(IUserController.class);

    private static final String main_page="main";
    @Resource
    private IUserService iUserService;

    @Autowired
    private HttpSession session;

    @RequestMapping("/queryById.do")
    public ModelAndView queryById(){
        System.out.println("进入方法、、、、、、、、、、、、、");
        ModelAndView mv = new ModelAndView();

        IUser user = iUserService.queryById(1);
        mv.addObject("user", user);
        mv.setViewName(main_page);

        return mv;

    }

    /**
     * 校验用户是否存在
     * @param iUser
     * @return
     */
    @RequestMapping("/checkUser.do")
    @ResponseBody
    public Result checkUser(IUser iUser){
        logger.debug("进入用户登录校验方法");
        Result result = new Result();
        boolean b = iUserService.checkUser(iUser);
        result.setFlag(b);
        if(!b){
            result.setMsg("用户名或密码错误");
        }else{
            session.setAttribute("loginUser", iUser.getLoginUser());
            session.setAttribute("password", iUser.getPassword());
        }
        return result;
    }

    /**
     * 跳到主页
     * @return
     */
    @RequestMapping("/toMainPage.do")
    public ModelAndView toMainPage(){
        ModelAndView mv = new ModelAndView();
        logger.debug("进入跳转的方法");
        mv.setViewName(main_page);
        return mv;
    }


}

common.jsp代码如下:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!-- <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> -->
<script src='${pageContext.request.contextPath }/static/jquery/jquery-3.0.0/jquery-3.0.0.min.js' type='text/javascript'></script>
<script src='${pageContext.request.contextPath }/static/bootstrap-3.3.7/dist/js/bootstrap.js' type='text/javascript'></script>
<script src='${pageContext.request.contextPath }/static/bootstrap-3.3.7/dist/js/bootstrap.min.js' type='text/javascript'></script>
<script src='${pageContext.request.contextPath }/static/layer-v3.1.0/layer/layer.js' type='text/javascript'></script>
<link rel='Stylesheet' href='${pageContext.request.contextPath }/static/bootstrap-3.3.7/dist/css/bootstrap.css' />

index.jsp代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@include file="common.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的项目</title>
</head>
<body class="gray-bg">
    <div class="middle-box text-center loginscreen  animated fadeInDown">
        <div>
            <div>
                <h1 class="logo-name">+_+</h1>
            </div>
            <h3>欢迎使用我的系统</h3>
            <form class="m-t" action="javascript:login()" id="LoginForm">
                <div class="form-group"  style="margin-left:40%">
                    <input type="text" name="loginUser" class="form-control" style="width:30%"  placeholder="用户名" required="">
                </div>
                <div class="form-group"  style="margin-left:40%">
                    <input type="password"name="password" class="form-control" style="width:30%" placeholder="密码" required="">
                </div>
                <button type="submit"  class="btn btn-primary block full-width m-b" id="btnLogin">登 录</button>
            </form>
        </div>
    </div>
    <script type="text/javascript">
        //登录
        function login() {
            $.post(
                '${pageContext.request.contextPath }/main/checkUser.do',
                $('#LoginForm').serializeArray(),
                function(data) {
                    if(!data['flag']){
                        parent.layer.msg("用户名或密码不正确!");
                    }else{
                        location.href = '${pageContext.request.contextPath }/main/toMainPage.do';
                    }
                })
        }
    </script>
</body>
</html>

jsp/main.jsp的代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>这里是首页</h1>
</body>
</html>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值