SprintBoot学习笔记(3):简单登录功能

来源:互联网 发布:网络电视包月怎么取消 编辑:程序博客网 时间:2024/05/17 04:55

在实际开发中,我们经常会遇到某些页面需要登录才能查看的情况。下面使用拦截器实现该功能,在用户没有登录的情况下,将网站的所有访问都指向登录页面。

一:创建一个拦截器,若用户没有登录(session中没有用户信息)则跳转至登录页面

/** * 登录拦截器 * 判断用户是否已经登录 * @author lim */public class LoginInterceptor implements HandlerInterceptor{    @Override    public void afterCompletion(HttpServletRequest arg0,            HttpServletResponse arg1, Object arg2, Exception arg3)            throws Exception {        // TODO Auto-generated method stub    }    @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response,            Object arg2, ModelAndView arg3) throws Exception {        // TODO Auto-generated method stub    }    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,            Object arg2) throws Exception {        //获取session        HttpSession session = request.getSession(true);        //判断用户ID是否存在,不存在就跳转到登录界面        if(null == session.getAttribute("userName") || session.getAttribute("userName").equals("")){            response.sendRedirect("/core/login");            return false;        }        return true;    }}

二:创建的拦截器需要进行配置后才能使用

/** * 拦截器配置 * @author lim */@Configuration@EnableWebMvc@ComponentScanpublic class WebConfig extends WebMvcConfigurerAdapter{    public WebConfig(){        super();    }    //配置拦截器    @Override    public void addInterceptors(InterceptorRegistry registry) {        InterceptorRegistration addInterceptor = registry.addInterceptor(new LoginInterceptor());        //排除配置        addInterceptor.excludePathPatterns("/error");        addInterceptor.excludePathPatterns("/core/login");        addInterceptor.excludePathPatterns("/core/doLogin");        //拦截配置        addInterceptor.addPathPatterns("/**");    }}

1、项目可配置多个拦截器,配置方法和配置单个拦截器相同。
2、在addInterceptors()方法中配置允许访问的路径和拦截过滤的地址。本例中拦截所有url,登录页url和验证登录url除外。
3、拦截器需要进行配置才能调用,否则不生效。
4、拦截器的调用在controller之后,只有配置了映射关系的url才能被拦截。否则提示无法找到页面。

三:登录控制器

配置映射关系

@Controller@RequestMapping("/core")public class LoginController {    @RequestMapping("/login")    public String login(HashMap<String, Object> map) {        map.put("hello","html");        return "core/login";    }    @RequestMapping("/doLogin")    @ResponseBody    public String doLogin(HttpServletRequest request, HttpServletResponse response) {        //String userId=request.getParameter("userId");        String userName=request.getParameter("userName");        //String password=request.getParameter("password");        //String checkcode=request.getParameter("checkcode");        //登录成功        if(null != userName && userName.equals("li")){            HttpSession session = request.getSession(true);            session.setAttribute("userName", userName);            return "1@#@login success";        }else{//登录失败            return "2@#@login failed";        }    }    @RequestMapping("/loginSuccess")    public String loginSuccess(HttpServletRequest request, HttpServletResponse response) {        return "/core/loginsuccess";    }}

采用RestFul接口,登录成功则返回“1@#@login success”,并把用户名存入session。登录失败则返回“2@#@login failed”。

四:登录页面(core/login.html)

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>login</title>    <script type="text/javascript" src="../../static/js/jquery/jquery-1.11.1.min.js"></script></head><body>    <p>用户名:<input id="userName" name="userName" type="text"/></p>    <p>密码:<input id="password" name="password" type="password"/></p>    <p>验证码:<input id="checkcode" name="checkcode" type="text"/></p>    <p><input id="doLogin" name="doLogin" type="button" value="登录"/>        <input id="reset" name="reset" type="button" value="重置" onclick="reset()"/></p></body><script>    $(function() {        //alert("1111");    })    function reset(){        $("#userName").val("");        $("#password").val("");        $("#checkcode").val("");    }    $("#doLogin").click(function(){        $.ajax({            type:"POST",            url:"/core/doLogin",            data:{                "userName":$("#userName").val(),                "password":$("#password").val(),                "checkcode":$("#checkcode").val()            },            success: function(result){                if(result=="1@#@login success"){                    window.location.href="/core/loginSuccess";                 }else{                          reset();                }            }        })    }) </script></html>

页面采用ajax技术实现数据传输,点击登录后将“用户名”、“密码”、“验证码”传输到后台。之后根据后台返回值进行进行下一步处理。

五:登录成功页面(core/loginsuccess.html)
此页面也登录成功后显示页面。

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"><head>    <title>login</title>   <script type="text/javascript" src="../../static/js/jquery/jquery-1.11.1.min.js"></script></head><body><h1 th:inline="text">login success</h1><p><input id="index" name="index" type="button" value="首页"/></p></body><script>    $("#index").click(function(){        window.location.href="/index";      }) </script></html>

至此,登录功能就模拟部分就完成了,在浏览器输入localhost:8080/login/core即可进行登录,或在没有登录的情况下输入已配置好映射关系的url也会直接跳转到登录页面,如localhost:8080/login/loginsuccess。
为了方便,我配置了一条映射关系以消除404错误,这样在某种程度上可以减少地址错误带来的麻烦。但同样也可能带来很多不变,这个根据具体需求进行配置。

    //配置拦截项目下所有url    @RequestMapping("/*")    public String gobal() {        return "core/login";
原创粉丝点击