博客項目系統的基本增刪改查前端
搭建先後端分離項目的骨架java
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.pony</groupId> <artifactId>springboot_blog</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_blog</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!--項目的熱加載重啓插件--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--化代碼的工具--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mybatis plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <!--mybatis plus 代碼生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <!--freemarker--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
# DataSource Config spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: password mybatis-plus: mapper-locations: classpath*:/mapper/**Mapper.xml
package com.pony.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * @author malf * @description 經過@MapperScan 註解指定要變成實現類的接口所在的包,而後包下面的全部接口在編譯以後都會生成相應的實現類。 * PaginationInterceptor是一個分頁插件。 * @date 2021/5/22 * @project springboot_blog */ @Configuration @EnableTransactionManagement @MapperScan("com.pony.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; } }
建立 Mysql 數據庫表mysql
CREATE TABLE `pony_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(64) DEFAULT NULL, `avatar` varchar(255) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `status` int(5) NOT NULL, `created` datetime DEFAULT NULL, `last_login` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `UK_USERNAME` (`username`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `pony_blog` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL, `title` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `content` longtext, `created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP, `status` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4; INSERT INTO `springboot_blog`.`pony_user` (`id`, `username`, `avatar`, `email`, `password`, `status`, `created`, `last_login`) VALUES ('1', 'pony', 'https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg', NULL, '96e79218965eb72c92a549dd5a330112', '0', '2021-05-20 10:44:01', NULL);
代碼生成器:CodeGeneratorgit
package com.pony; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author malf * @description 執行 main 方法,在控制檯輸入模塊表名回車自動生成對應項目目錄 * @date 2021/5/22 * @project springboot_blog */ public class CodeGenerator { /** * 讀取控制檯內容 */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("請輸入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("請輸入正確的" + tip + "!"); } public static void main(String[] args) { // 代碼生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("pony"); gc.setOpen(false); // gc.setSwagger2(true); 實體屬性 Swagger2 註解 gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // 數據源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/springboot_blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("password"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(null); pc.setParent("com.pony"); mpg.setPackageInfo(pc); // 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { } }; // 若是模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 若是模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會被優先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 若是 Entity 設置了先後綴,此處注意 xml 的名稱會跟着發生變化 return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix("pony_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
測試當前步驟正確及數據庫鏈接正常web
package com.pony.controller; import com.pony.service.UserService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * <p> * 前端控制器 * </p> * * @author pony * @since 2021-05-22 */ @RestController @RequestMapping("/user") public class UserController { @Resource UserService userService; @GetMapping("/{id}") public Object test(@PathVariable("id") Long id) { return userService.getById(id); } }
運行項目,訪問地址 http://localhost:8080/user/1
redis
package com.pony.common; import lombok.Data; import java.io.Serializable; /** * @author malf * @description 用於異步統一返回的結果封裝。 * @date 2021/5/22 * @project springboot_blog */ @Data public class Result implements Serializable { private String code; // 是否成功 private String message; // 結果消息 private Object data; // 結果數據 public static Result success(Object data) { Result result = new Result(); result.setCode("0"); result.setData(data); result.setMessage("操做成功"); return result; } public static Result success(String message, Object data) { Result result = new Result(); result.setCode("0"); result.setData(data); result.setMessage(message); return result; } public static Result fail(String message) { Result result = new Result(); result.setCode("-1"); result.setData(null); result.setMessage(message); return result; } public static Result fail(String message, Object data) { Result result = new Result(); result.setCode("-1"); result.setData(data); result.setMessage(message); return result; } }
考慮到後面可能須要作集羣、負載均衡等,因此就須要會話共享,而Shiro的緩存和會話信息,咱們通常考慮使用Redis來存儲數據,因此,咱們不只須要整合Shiro,也須要整合Redis。spring
<dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis-spring-boot-starter</artifactId> <version>3.2.1</version> </dependency> <!-- hutool工具類--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.3</version> </dependency> <!-- jwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
第一步:生成和校驗jwt的工具類,其中有些jwt相關的密鑰信息是從項目配置文件中配置的sql
package com.pony.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ @Slf4j @Data @Component @ConfigurationProperties(prefix = "pony.jwt") public class JwtUtils { private String secret; private long expire; private String header; /** * 生成jwt token */ public String generateToken(long userId) { Date nowDate = new Date(); // 過時時間 Date expireDate = new Date(nowDate.getTime() + expire * 1000); return Jwts.builder() .setHeaderParam("typ", "JWT") .setSubject(userId + "") .setIssuedAt(nowDate) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public Claims getClaimByToken(String token) { try { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } catch (Exception e) { log.debug("validate is token error ", e); return null; } } /** * token是否過時 * * @return true:過時 */ public boolean isTokenExpired(Date expiration) { return expiration.before(new Date()); } }
第二步:自定義一個JwtToken,來完成shiro的supports方法數據庫
package com.pony.shiro; import org.apache.shiro.authc.AuthenticationToken; /** * @author malf * @description shiro默認supports的是UsernamePasswordToken,咱們如今採用了jwt的方式, * 因此這裏自定義一個JwtToken,來完成shiro的supports方法。 * @date 2021/5/22 * @project springboot_blog */ public class JwtToken implements AuthenticationToken { private String token; public JwtToken(String token) { this.token = token; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return token; } }
第三步:登陸成功以後返回的一個用戶信息的載體apache
package com.pony.shiro; import lombok.Data; import java.io.Serializable; /** * @author malf * @description 登陸成功以後返回的一個用戶信息的載體 * @date 2021/5/22 * @project springboot_blog */ @Data public class AccountProfile implements Serializable { private Long id; private String username; private String avatar; }
第四步:shiro進行登陸或者權限校驗的邏輯所在
package com.pony.shiro; import cn.hutool.core.bean.BeanUtil; import com.pony.entity.User; import com.pony.service.UserService; import com.pony.util.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @author malf * @description shiro進行登陸或者權限校驗的邏輯所在 * @date 2021/5/22 * @project springboot_blog */ @Slf4j @Component public class AccountRealm extends AuthorizingRealm { @Resource JwtUtils jwtUtils; @Resource UserService userService; @Override public boolean supports(AuthenticationToken token) { return token instanceof JwtToken; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { JwtToken jwt = (JwtToken) token; log.info("jwt----------------->{}", jwt); String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject(); User user = userService.getById(Long.parseLong(userId)); if (user == null) { throw new UnknownAccountException("帳戶不存在!"); } if (user.getStatus() == -1) { throw new LockedAccountException("帳戶已被鎖定!"); } AccountProfile profile = new AccountProfile(); BeanUtil.copyProperties(user, profile); log.info("profile----------------->{}", profile.toString()); return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName()); } }
第五步:定義jwt的過濾器JwtFilter
package com.pony.shiro; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.pony.common.Result; import com.pony.util.JwtUtils; import io.jsonwebtoken.Claims; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExpiredCredentialsException; import org.apache.shiro.web.filter.authc.AuthenticatingFilter; import org.apache.shiro.web.util.WebUtils; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author malf * @description 定義jwt的過濾器JwtFilter。 * @date 2021/5/22 * @project springboot_blog */ @Component public class JwtFilter extends AuthenticatingFilter { @Resource JwtUtils jwtUtils; @Override protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { // 獲取 token HttpServletRequest request = (HttpServletRequest) servletRequest; String jwt = request.getHeader("Authorization"); if (StringUtils.isEmpty(jwt)) { return null; } return new JwtToken(jwt); } @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { HttpServletRequest request = (HttpServletRequest) servletRequest; String token = request.getHeader("Authorization"); if (StringUtils.isEmpty(token)) { return true; } else { // 判斷是否已過時 Claims claim = jwtUtils.getClaimByToken(token); if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) { throw new ExpiredCredentialsException("token已失效,請從新登陸!"); } } // 執行自動登陸 return executeLogin(servletRequest, servletResponse); } @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { HttpServletResponse httpResponse = (HttpServletResponse) response; try { //處理登陸失敗的異常 Throwable throwable = e.getCause() == null ? e : e.getCause(); Result r = Result.fail(throwable.getMessage()); String json = JSONUtil.toJsonStr(r); httpResponse.getWriter().print(json); } catch (IOException e1) { } return false; } /** * 對跨域提供支持 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = WebUtils.toHttp(request); HttpServletResponse httpServletResponse = WebUtils.toHttp(response); httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域時會首先發送一個OPTIONS請求,這裏咱們給OPTIONS請求直接返回正常狀態 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } }
第六步:Shiro 配置類
package com.pony.config; import com.pony.shiro.AccountRealm; import com.pony.shiro.JwtFilter; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import javax.servlet.Filter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * @author malf * @description shiro 啓用註解攔截控制器 * @date 2021/5/22 * @project springboot_blog */ @Configuration public class ShiroConfig { @Resource JwtFilter jwtFilter; @Bean public SessionManager sessionManager(RedisSessionDAO redisSessionDAO) { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(redisSessionDAO); return sessionManager; } @Bean public DefaultWebSecurityManager securityManager(AccountRealm accountRealm, SessionManager sessionManager, RedisCacheManager redisCacheManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(accountRealm); securityManager.setSessionManager(sessionManager); securityManager.setCacheManager(redisCacheManager); /* * 關閉shiro自帶的session,詳情見文檔 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); securityManager.setSubjectDAO(subjectDAO); return securityManager; } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/**", "jwt"); // 主要經過註解方式校驗權限 chainDefinition.addPathDefinitions(filterMap); return chainDefinition; } @Bean("shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, ShiroFilterChainDefinition shiroFilterChainDefinition) { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager); Map<String, Filter> filters = new HashMap<>(); filters.put("jwt", jwtFilter); shiroFilter.setFilters(filters); Map<String, String> filterMap = shiroFilterChainDefinition.getFilterChainMap(); shiroFilter.setFilterChainDefinitionMap(filterMap); return shiroFilter; } // 開啓註解代理(默認好像已經開啓,能夠不要) @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); return creator; } }
第七步:配置文件
shiro-redis: enabled: true redis-manager: host: 127.0.0.1:6379 pony: jwt: # 加密祕鑰 secret: f4e2e52034348f86b67cde581c0f9eb5 # token有效時長,7天,單位秒 expire: 604800 header: token
第八步:熱部署配置(若是添加了 devtools 依賴)
resources/META-INF/spring-devtools.properties
restart.include.shiro-redis=/shiro-[\\w-\\.]+jar
目前爲止,shiro就已經完成整合進來了,而且使用了jwt進行身份校驗。
package com.pony; import com.pony.common.Result; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.ShiroException; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.io.IOException; /** * @author malf * @description 全局異常處理 * @ControllerAdvice表示定義全局控制器異常處理,@ExceptionHandler表示針對性異常處理,可對每種異常針對性處理。 * @date 2021/5/22 * @project springboot_blog */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { // 捕捉shiro的異常 @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(ShiroException.class) public Result handle401(ShiroException e) { return Result.fail("401", e.getMessage(), null); } /** * 處理Assert的異常 */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = IllegalArgumentException.class) public Result handler(IllegalArgumentException e) throws IOException { log.error("Assert異常:-------------->{}", e.getMessage()); return Result.fail(e.getMessage()); } /** * 校驗錯誤異常處理 */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = MethodArgumentNotValidException.class) public Result handler(MethodArgumentNotValidException e) throws IOException { log.error("運行時異常:-------------->", e); BindingResult bindingResult = e.getBindingResult(); ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get(); return Result.fail(objectError.getDefaultMessage()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(value = RuntimeException.class) public Result handler(RuntimeException e) throws IOException { log.error("運行時異常:-------------->", e); return Result.fail(e.getMessage()); } }
RuntimeException:捕捉其餘異常
一、表單數據提交的時候,前端的校驗可使用一些相似於jQuery Validate等js插件實現,然後端可使用Hibernate validatior來作校驗。
@NotBlank(message = "暱稱不能爲空") private String username; private String avatar; @NotBlank(message = "郵箱不能爲空") @Email(message = "郵箱格式不正確") private String email;
二、@Validated註解校驗實體
/** * 測試實體校驗 * @param user * @return */ @PostMapping("/save") public Object testUser(@Validated @RequestBody User user) { return user.toString(); }
package com.pony.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author malf * @description 全局跨域處理 * @date 2021/5/22 * @project springboot_blog */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
登陸帳號密碼實體
package com.pony.common; import lombok.Data; import javax.validation.constraints.NotBlank; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ @Data public class LoginDto { @NotBlank(message = "暱稱不能爲空") private String username; @NotBlank(message = "密碼不能爲空") private String password; }
登陸退出入口
package com.pony.controller; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.pony.common.LoginDto; import com.pony.common.Result; import com.pony.entity.User; import com.pony.service.UserService; import com.pony.util.JwtUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; /** * @author malf * @description 登陸接口 * 接受帳號密碼,而後把用戶的id生成jwt,返回給前段,爲了後續的jwt的延期,把jwt放在header上 * @date 2021/5/22 * @project springboot_blog */ public class AccountController { @Resource JwtUtils jwtUtils; @Resource UserService userService; /** * 默認帳號密碼:pony / 111111 */ @CrossOrigin @PostMapping("/login") public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) { User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername())); Assert.notNull(user, "用戶不存在"); if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) { return Result.fail("密碼錯誤!"); } String jwt = jwtUtils.generateToken(user.getId()); response.setHeader("Authorization", jwt); response.setHeader("Access-Control-Expose-Headers", "Authorization"); // 用戶能夠另外一個接口 return Result.success(MapUtil.builder() .put("id", user.getId()) .put("username", user.getUsername()) .put("avatar", user.getAvatar()) .put("email", user.getEmail()) .map() ); } // 退出 @GetMapping("/logout") @RequiresAuthentication public Result logout() { SecurityUtils.getSubject().logout(); return Result.success(null); } }
ShiroUtils
package com.pony.util; import com.pony.shiro.AccountProfile; import org.apache.shiro.SecurityUtils; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ public class ShiroUtils { public static AccountProfile getProfile() { return (AccountProfile) SecurityUtils.getSubject().getPrincipal(); } }
博客操做入口
package com.pony.controller; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Assert; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pony.common.Result; import com.pony.entity.Blog; import com.pony.service.BlogService; import com.pony.util.ShiroUtils; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.time.LocalDateTime; /** * <p> * 前端控制器 * </p> * * @author pony * @since 2021-05-22 */ @RestController public class BlogController { @Resource BlogService blogService; @GetMapping("/blogs") public Result blogs(Integer currentPage) { if (currentPage == null || currentPage < 1) currentPage = 1; Page page = new Page(currentPage, 5); IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created")); return Result.success(pageData); } @GetMapping("/blog/{id}") public Result detail(@PathVariable(name = "id") Long id) { Blog blog = blogService.getById(id); Assert.notNull(blog, "該博客已刪除!"); return Result.success(blog); } @RequiresAuthentication @PostMapping("/blog/edit") public Result edit(@Validated @RequestBody Blog blog) { System.out.println(blog.toString()); Blog temp = null; if (blog.getId() != null) { temp = blogService.getById(blog.getId()); Assert.isTrue(temp.getUserId() == ShiroUtils.getProfile().getId(), "沒有權限編輯"); } else { temp = new Blog(); temp.setUserId(ShiroUtils.getProfile().getId()); temp.setCreated(LocalDateTime.now()); temp.setStatus(0); } BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status"); blogService.saveOrUpdate(temp); return Result.success("操做成功", null); } }
接口測試
目前爲止,後端接口的開發基本完成。