廖师兄springboot学习笔记二(增加IDEA单模块jsp和多模块jsp引入)

一、参数验证

  • 实体类,一下表示最小18,大于18会报错
@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(); // 返回默认message
    }
    return manRepository.save(man);
}

二、AOP

  • 加入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • 简单的测试before,先写完方法注解就可以提示了。
@Aspect     // 切面
@Component      // 加入spring的依赖
public class HttpAspect {
    // spring内置是使用logback,引入的是 import org.slf4j.Logger; 这个log的jar包
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    //如果拦截所有该类中的方法public * com.imooc.ManController.*(..)
    //如果拦截所有类 * public * com.imooc.*.*(..),但是多类有requestMapping的话会算两次

    @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();
        // url
        logger.info("url={}", request.getRequestURL());
        // method
        logger.info("method={}", request.getMethod());
        // ip
        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;
    }
}
  • spring的异常处理类
@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 // api测试需要这个
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"))  // get post put delete
                .andExpect(MockMvcResultMatchers.status().isOk()) // isOK 是 200
                .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>
    <!--<scope>provided</scope>-->
</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/"); // jsp目录
        resolver.setSuffix(".jsp");
        return resolver;
    }
}
  • 打包以后jsp没有包含在jar里面,需要在pom.xml文件增加资源目录
<build>
      <resources>
          <!-- 打包时将jsp文件拷贝到META-INF目录下-->
          <resource>
              <!-- 指定resources插件处理哪个目录下的资源文件 -->
              <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>
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值