spring项目篇13 --- 网上商城之登陆注册
Posted 灬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring项目篇13 --- 网上商城之登陆注册相关的知识,希望对你有一定的参考价值。
首先我们这次使用的是jwt来实现的登陆认证,首先看一下需要引入的jar包
尤其是commons-codec这个包,一定要引入,否则会报binary那个包的错误,因为找不到方法,另外不要使用那个结尾是20... 就是那个最新的这个包,会出错,找了好半天这个错误。。。
首先说一下基本思想,就是通过拦截器将我们的login以及rgister与静态文件放行,其余的检测是否携带token,并对token进行检测,合格之后在进行放行。
接下来直接看源码
首先看一下我们的spring配置补充的,因为没有使用redis,因此注释掉,补充了一个拦截器,并将静态文件做了修改
<!--配置注解扫描--> <context:component-scan base-package="com.yang" /> <!--因为配置了静态文件,spring不会自动为我们加载HandlerMapping与HandlerAdapter,因此需要进行初始化--> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!--配置静态文件--> <mvc:resources location="/static" mapping="/static/**" /> <!-- <mvc:resources location="/static/js" mapping="/js/**" />--> <!-- <mvc:resources location="/static/css" mapping="/css/**" />--> <!--上传文件配置--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="5120" /> </bean> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> <!--配置拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截所有请求--> <mvc:mapping path="/" /> <!--不拦截登陆--> <mvc:exclude-mapping path="/login" /> <!--不拦截注册--> <mvc:exclude-mapping path="/register" /> <!--不拦截静态文件--> <mvc:exclude-mapping path="/static/**" /> <!--指定我们的拦截器--> <bean class="com.yang.interceptor.LoginInterceptor" /> </mvc:interceptor> </mvc:interceptors>
虽然配置了静态文件访问,按照理论来讲会实现我们的基地·既定的计划,静态文件直接迁移static里面查找,但是会报错404,找不到,因此在web.xml中将这个路径不再使用我们指定的拦截器,而是使用默认的,问题解决。
<!-- 设置静态文件访问 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/**</url-pattern> </servlet-mapping>
看一下我们的token类
package com.yang.util; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Date; import java.util.HashMap; import java.util.Map; public class TokenUse { // 设置过期时间 private static final long overDeuTime = 1440 * 60 * 1000; // 设置秘钥 private static final String tokenSecret = "fde35b32-0f47-46be-ae2a-49bcb7ed7d7f"; // 生成token public static String sign(String username, Integer userId) { // 设置过期时间 Date data = new Date(System.currentTimeMillis() + overDeuTime); // 使用token私钥加密 Algorithm algorithm = Algorithm.HMAC256(tokenSecret); // 设置头部信息 Map<String, Object> requestHeader = new HashMap<>(2); requestHeader.put("Type", "Jwt"); requestHeader.put("alg", "HS256"); // long dt = new Date().getTime(); // 返回带有用户信息的签名 try{ return JWT.create().withHeader(requestHeader) .withClaim("username", username) .withClaim("userId", userId) .withExpiresAt(data) .sign(algorithm); }catch (Exception e){ System.out.println(e.getMessage()); e.printStackTrace(); return null; } } // 验证token是否正确,返回boolean值 public static boolean tokenVerify(String token){ try{ Algorithm algorithm = Algorithm.HMAC256(tokenSecret); JWTVerifier verifier = JWT.require(algorithm).build(); // 验证 DecodedJWT decodedJWT = verifier.verify(token); return true; }catch (Exception e){ e.printStackTrace(); return false; } } // 获取登陆用户token中的用户ID public static int getUserID(String token){ try{ Algorithm algorithm = Algorithm.HMAC256(tokenSecret); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT jwt = verifier.verify(token); return jwt.getClaim("userId").asInt(); }catch (Exception e){ return 0; } } }
接下来看一下我们的拦截器
package com.yang.interceptor; import com.yang.util.TokenUse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { @Override //当处理器方法执行之前调用 //返回值: true 放行 false 不放行 就执行不了处理器方法 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle当处理器方法执行之前调用"); response.setCharacterEncoding("utf-8"); String token = request.getHeader("token"); if(token != null){ // 判断是否携带token,并进行验证 return TokenUse.tokenVerify(token); } return false; } @Override //当处理器方法执行之后会自动调用调用 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle当处理器方法执行之后会自动调用调用"); } @Override //请求处理完毕之后, 会调用 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion请求处理完毕之后,会调用"); } }
看一下我们的user控制器
package com.yang.controller; import com.yang.domain.User; import com.yang.service.IUserService; import com.yang.util.TokenUse; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { @Autowired private IUserService iUserService; // 返回登陆页面 @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(){ return "login"; } // 返回注册页面 @RequestMapping(value = "/register", method = RequestMethod.GET) public String register(){ return "register"; } // 用户登陆认证 @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(String username, String password){ User user = iUserService.get(username); if(user != null && user.getPassword().equals(password)){ // 创建token String token = TokenUse.sign(username, user.getId()); if(token != null){ return token; } } return "fail"; } // 用户登陆认证 @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST) public String register(User u){ User user = iUserService.get(u.getUsername()); if(user != null){ return "exit"; } boolean result = iUserService.save(u); if(result){ return "ok"; }else{ return "fail"; } } }
接下来看一下login页面
<%-- Created by IntelliJ IDEA. User: yangshixiong Date: 2020/1/27 Time: 下午09:45 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html lang="en"> <head> <meta charset="utf-8"> <title>用户登陆中心</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap core CSS --> <link href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="${pageContext.request.contextPath}/static/css/font-awesome.min.css" rel="stylesheet"> <!-- ionicons --> <link href="${pageContext.request.contextPath}/static/css/ionicons.min.css" rel="stylesheet"> <!-- Simplify --> <link href="${pageContext.request.contextPath}/static/css/simplify.min.css" rel="stylesheet"> </head> <body class="overflow-hidden light-background"> <div class="wrapper no-navigation preload"> <div class="sign-in-wrapper"> <div class="sign-in-inner"> <div class="login-brand text-center"> <i class="fa fa-database m-right-xs"></i> 用户 <strong class="text-skin">登陆</strong> </div> <form> <div class="form-group m-bottom-md"> <input type="text" id="username" class="form-control" placeholder="用户名"> </div> <div class="form-group"> <input type="password" id="password" class="form-control" placeholder="密码"> </div> <div class="m-top-md p-top-sm"> <div href="#" id="login" class="btn btn-success block">登陆</div> </div> <div class="m-top-md p-top-sm"> <div class="font-12 text-center m-bottom-xs">没有账号?</div> <a href="${pageContext.request.contextPath}/register" class="btn btn-default block">创建账号</a> </div> </form> </div><!-- ./sign-in-inner --> </div><!-- ./sign-in-wrapper --> </div><!-- /wrapper --> <a href="" id="scroll-to-top" class="hidden-print"><i class="icon-chevron-up"></i></a> <!-- Jquery --> <script src="${pageContext.request.contextPath}/static/js/jquery-1.11.1.min.js"></script> <!-- Bootstrap --> <script src="${pageContext.request.contextPath}/static/js/bootstrap.min.js"></script> <!-- Slimscroll --> <script src=\'${pageContext.request.contextPath}/static/js/jquery.slimscroll.min.js\'></script> <!-- Popup Overlay --> <script src=\'${pageContext.request.contextPath}/static/js/jquery.popupoverlay.min.js\'></script> <!-- Modernizr --> <script src=\'${pageContext.request.contextPath}/static/js/modernizr.min.js\'></script> <!-- Simplify --> <script src="${pageContext.request.contextPath}/static/js/simplify/simplify.js"></script> <script type="application/javascript"> $(function () { $(\'#login\').click(function () { let username = $(\'#username\').val(); let password = $(\'#password\').val(); console.log(username, password) if(username === "" || password === ""){ alert("用户名或密码不能为空!"); return false; } $.ajax({ type:"post", url:"${pageContext.request.contextPath}/login", data:{username,password}, success:function (data) { if(data === "fail"){ alert("用户名或密码有误,请修改!"); return false; } sessionStorage.setItem("token", data); }, error:function (err) { console.log(err); alert("服务器异常,请稍后再试!") } }) }) }) </script> </body> </html>
register页面
<%-- Created by IntelliJ IDEA. User: yangshixiong Date: 2020/1/23 Time: 下午10:45 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html lang="en"> <head> <meta charset="utf-8"> <title>Simplify Admin</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap core CSS --> <link href="${pageContext.request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="${pageContext.request.contextPath}/static/css/font-awesome.min.css" rel="stylesheet"> <!-- ionicons --> <link href="${pageContext.request.contextPath}/static/css/ionicons.min.css" rel="stylesheet"> <!-- Simplify --> <link href="${pageContext.request.contextPath}/static/css/simplify.min.css" rel="stylesheet"> </head> <body class="overflow-hidden light-background"> <div class="wrapper no-navigation preload"> <div class="sign-in-wrapper"> <div class="sign-in-inner"> <div class="login-brand text-center"> <i class="fa fa-database m-right-xs"></ispring项目篇12---网上商城之配置以及工具类的编写Spring Cloud Alibaba商城实战项目基础篇(day02)