一、参数验证
@Min(value = 18 , message = "默认message信息" )
private Integer age;
业务层,@Validated表示要验证,bindingResult验证的信息
@PostMapping(value = "/mans" )
public Object manAdd (@Validated Man man, BindingResult bindingResult){
if (bindingResult.hasErrors()){
return bindingResult.getFieldError().getDefaultMessage();
}
return manRepository.save(man);
}
二、AOP
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-aop</artifactId >
</dependency >
简单的测试before,先写完方法注解就可以提示了。
@Aspect
@Component
public class HttpAspect {
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut ("execution(public * com.imooc.ManController.*(..))" )
public void log (){
}
@Before ("log()" )
public void doBefore (JoinPoint joinpoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("url={}" , request.getRequestURL());
logger.info("method={}" , request.getMethod());
logger.info("ip={}" , request.getRemoteAddr());
logger.info("class_method={}" , joinpoint.getSignature().getDeclaringTypeName() + "." + joinpoint.getSignature().getName());
logger.info("args={}" , joinpoint.getArgs());
}
@After ("log()" )
public void doAfter (){
logger.info("22222222222" );
}
/**
* 返回信息展示,注意实体类需要一个toString方法
* @param object
*/
@AfterReturning (returning = "object" , pointcut = "log()" )
public void doAfterReturning (Object object){
logger.info("respone={}" , object);
}
}
三、统一异常处理
public class GirlException extends RuntimeException {
private Integer code;
public GirlException (Integer code, String msg) {
super (msg);
this .code = code;
}
public GirlException (ResultEnum resultEnum){
super (resultEnum.getMsg());
this .code = resultEnum.getCode();
}
public Integer getCode () {
return code;
}
}
@ControllerAdvice
public class ExceptionHandle {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler (value = Exception.class)
@ResponseBody
public Result handler (Exception e){
if (e instanceof GirlException){
GirlException girlException = (GirlException)e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
} else {
logger.error("【系统错误】" , e);
return ResultUtil.error(-1 , "系统异常" );
}
}
}
public enum ResultEnum {
UNKONW_ERROR(-1 , "未知错误" ),
SUCCESS(0 , "成功" ),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this .code = code;
this .msg = msg;
}
public Integer getCode () {
return code;
}
public String getMsg () {
return msg;
}
}
public class Result<T> {
private Integer code;
private String msg;
private T data;
get /set 方法
}
public class ResultUtil {
public static Result success (Object object ){
Result result = new Result();
result.setCode(0 );
result.setMsg("成功" );
result.setData(object );
return result;
}
public static Result success (){
Result result = new Result();
result.setCode(0 );
result.setMsg("成功" );
result.setData(null );
return result;
}
public static Result error (Integer code, String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(null );
return result;
}
}
使用
return ResultUtil.error(1, “错误msg”); throw new GirlException(ResultEnum.UNKONW_ERROR);
四、单元测试
使用idea自带的:在类里面右键鼠标选择 Go To -> Test 可以快速创建空的junit的测试类 使用junit插件:类内使用alt+ins快速创建junit,不过格式是springmvc的 代码:
@RunWith (SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ManControllerTest {
/**service测试*/
@Autowired
ManRepository manRepository;
@Test
public void testFindById () throws Exception {
Man man = manRepository.findOne(7 );
Assert.assertEquals(new Integer(100 ), man.getAge());
}
/**api测试*/
@Autowired
MockMvc mockMvc;
@Test
public void testManList () throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/mans" ))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("" ));
}
}
mvn clean package 就会自动测试了 跳过测试:mvn clean package -Dmaven.test.skip=true
五、整合jsp
网上找了demo测试了以后jsp可以访问了,这里也记录一下 默认目录是 src/main/webapp 加配置:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
目录结构 代码
@RequestMapping ("/login" )
public String login (){
return "login" ;
}
<dependency >
<groupId > org.apache.tomcat.embed</groupId >
<artifactId > tomcat-embed-jasper</artifactId >
</dependency >
五、多module下整合jsp
将项目改为多模块以后竟然访问不了了,实验了几次以后成功,自定义类继承WebMvcConfigurerAdapter即可
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
/** 指定默认文件的地址,jsp页面引入js和css的时候就不用管项目路径了 */
@Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**" )
.addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/" );
super .addResourceHandlers(registry);
}
/**
* 多模块的jsp访问,默认是src/main/webapp,但是多模块的目录只设置yml文件不行
* @return
*/
@Bean
public InternalResourceViewResolver viewResolver () {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
resolver.setPrefix("/WEB-INF/jsp/" );
resolver.setSuffix(".jsp" );
return resolver;
}
}
打包以后jsp没有包含在jar里面,需要在pom.xml文件增加资源目录
<build >
<resources >
<resource >
<directory > src/main/webapp</directory >
<targetPath > META-INF/resources</targetPath >
<includes >
<include > **/**</include >
</includes >
</resource >
<resource >
<directory > src/main/resources</directory >
<includes >
<include > **/**</include >
</includes >
<filtering > false</filtering >
</resource >
</resources >
</build >