首页 > 代码库 > springboot functions

springboot functions

1. spring boot 项目启动,如果不配置项目访问路径,默认为 /

技术分享

2. 表单验证

spring项目:

<properties>           <springframework.version>4.0.6.RELEASE</springframework.version>    <hibernate.validator.version>5.1.2.Final</hibernate.validator.version><javax.validation.version>1.1.0.Final</javax.validation.version></properties>       
<dependency>			<groupId>javax.validation</groupId>			<artifactId>validation-api</artifactId>			<version>${javax.validation.version}</version>		</dependency>		<dependency>			<groupId>org.hibernate</groupId>			<artifactId>hibernate-validator</artifactId>			<version>${hibernate.validator.version}</version>		</dependency>

springboot项目:

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-jpa</artifactId>        </dependency>
import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.validation.constraints.Min;import javax.validation.constraints.NotNull; @NotBlank(message = "这个字段必传")    private String size;   @Min(value = 18, message = "禁止入门")    private Integer age; @NotNull(message = "金额必传")    private Double money;
@PostMapping(value = http://www.mamicode.com/"/girls")    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) {        if (bindingResult.hasErrors()) {            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());        }        girl.setCupSize(girl.getCupSize());        girl.setAge(girl.getAge());        return ResultUtil.success(girlRepository.save(girl));    }
通过@Valid,BindingResult 验证的时候仅限参数为对象

//更新
    @PutMapping(value = "http://www.mamicode.com/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id,
                           @RequestParam("cupSize") String cupSize,
                           @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);

        return girlRepository.save(girl);
    }
由于金额上增加了不能为空,这里同样不能通过。
{
  "code": -1,
  "msg": "未知错误",
  "data": null
}
返回这个错误是应为在@Controller注解实用类上增加了异常处理

3. AOP 获取常用数据

@Aspect@Componentpublic class HttpAspect {    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);    @Pointcut("execution(public * com.imooc.controller.GirlController.*(..))")    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("222222222222");    }    @AfterReturning(returning = "object", pointcut = "log()")    public void doAfterReturning(Object object) {        logger.info("response={}", object.toString());    }

4. 异常处理

import com.imooc.domain.Result;import com.imooc.exception.GirlException;import com.imooc.utils.ResultUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;/** * Indicates the annotated class assists a "Controller". * 2017-01-21 13:59 */@ControllerAdvicepublic class ExceptionHandle {    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);    @ExceptionHandler(value = Exception.class)    @ResponseBody    public Result handle(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, "未知错误");        }    }}

service 中将异常抛到controller,上诉代码在controller中进行处理

public void getAge(Integer id) throws Exception{        Girl girl = girlRepository.findOne(id);        Integer age = girl.getAge();        if (age < 10) {            //返回"你还在上小学吧" code=100            throw new GirlException(ResultEnum.PRIMARY_SCHOOL);        }else if (age > 10 && age < 16) {            //返回"你可能在上初中" code=101            throw new GirlException(ResultEnum.MIDDLE_SCHOOL);        }        //如果>16岁,加钱        //...    }

 

5.springboot test

@RunWith(SpringRunner.class)@SpringBootTestpublic class GirlServiceTest {    @Autowired    private GirlService girlService;    @Test    public void findOneTest() {        Girl girl = girlService.findOne(73);        Assert.assertEquals(new Integer(13), girl.getAge());    }}

 

springboot functions