您好,登录后才能下订单哦!
今天就跟大家聊聊有关Java项目如何实现前后端分离,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
构建springboot项目
我的目录结构:(结果未按标准书写,仅作说明)
不管用什么IDE,最后我们只看pom.xml里的依赖:
为了尽可能简单,就不连数据库了,登陆时用固定的。
devtools:用于修改代码后自动重启;
jjwt:加密这么麻烦的事情可以用现成的,查看https://github.com/jwtk/jjwt
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JJWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.6.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
登录
这里的加密密钥是:base64EncodedSecretKey
import java.util.Date; import javax.servlet.ServletException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @RestController @RequestMapping("/") public class HomeController { @PostMapping("/login") public String login(@RequestParam("username") String name, @RequestParam("password") String pass) throws ServletException { String token = ""; if (!"admin".equals(name)) { throw new ServletException("找不到该用户"); } if (!"1234".equals(pass)) { throw new ServletException("密码错误"); } token = Jwts.builder().setSubject(name).claim("roles", "user").setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, "base64EncodedSecretKey").compact(); return token; } }
测试token
现在就可以测试生成的token了,我们采用postman:
过滤器
这肯定是必须的呀,当然,也可以用AOP。
过滤要保护的url,同时在过滤器里进行token验证
token验证:
public class JwtFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String authHeader = request.getHeader("Authorization"); if ("OPTIONS".equals(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); chain.doFilter(req, res); } else { if (authHeader == null || !authHeader.startsWith("Bearer ")) { throw new ServletException("不合法的Authorization header"); } // 取得token String token = authHeader.substring(7); try { Claims claims = Jwts.parser().setSigningKey("base64EncodedSecretKey").parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); } catch (Exception e) { throw new ServletException("Invalid Token"); } chain.doFilter(req, res); } } }
要保护的url:/user下的:
@SpringBootApplication public class AuthServerApplication { @Bean public FilterRegistrationBean jwtFilter() { FilterRegistrationBean rbean = new FilterRegistrationBean(); rbean.setFilter(new JwtFilter()); rbean.addUrlPatterns("/user/*");// 过滤user下的链接 return rbean; } public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class, args); } }
UserController
这个是必须经过过滤才可以访问的:
@RestController @RequestMapping("/user") public class UserController { @GetMapping("/success") public String success() { return "恭喜您登录成功"; } @GetMapping("/getEmail") public String getEmail() { return "xxxx@qq.com"; } }
关键测试
假设我们的Authorization错了,肯定是通不过的:
当输入刚才服务器返回的正确token:
允许跨域请求
现在来说前端和后端是两个服务器了,所以需要允许跨域:
@Configuration public class CorsConfig { @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTION"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("DELETE"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } @Bean public WebMvcConfigurer mvcConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "GET", "OPTIONS"); } }; } }
看完上述内容,你们对Java项目如何实现前后端分离有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。