一个值得练手的demo
部分代码
User实体
package com.hello.model;
import java.io.Serializable;
/**
* 用户实体类
*/
public class User implements Serializable{
private String name;
private String password;
private int age;
private String address;
public String getName() {
return name;
}
public User(){}
public User(String name,int age,String address){
this.name=name;
this.age=age;
this.address=address;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
登录参数实体
package com.hello.params;
import org.hibernate.validator.constraints.NotEmpty;
/**
* 用户登录参数实体类
*/
public class LoginParam {
/**
* 用户登录名称
*/
@NotEmpty(message = "loginName不能为空")
private String loginName;
/**
* 登录密码
*/
@NotEmpty(message = "密码不能为空")
private String password;
/**
* 验证码
*/
private String veriCode;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVeriCode() {
return veriCode;
}
public void setVeriCode(String veriCode) {
this.veriCode = veriCode;
}
}
UserServiceImpl 片段
@Override
public User login(String loginName,String pwd){
if(StringUtils.isEmpty(loginName)||StringUtils.isEmpty(pwd)){
throw new RuntimeException("参数缺失");
}
if("jianglei".equals(loginName)&&"123".equals(pwd)){
User loginUser= new User();
loginUser.setName(loginName);
loginUser.setAge(26);
loginUser.setAddress("ShangHai JiaDing");
return loginUser;
}
return null;
}
UserController 片段
@RequestMapping(value = "/login",method = RequestMethod.POST)
public ResultResponse login(@RequestBody @Valid LoginParam loginParam){
try{
User loginUser=userService.login(loginParam.getLoginName(),loginParam.getPassword());
if(loginUser!=null){
return new ResultResponse().success("success").data(loginUser);
}else{
return new ResultResponse().fail("用户名或密码错误");
}
}catch (Exception e){
return new ResultResponse().fail(e.getMessage());
}
}
ExceptionAdvice
package com.hello.advice;
import com.hello.common.ResultResponse;
import com.hello.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.ValidationException;
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
Logger LOG= LoggerFactory.getLogger(ExceptionAdvice.class);
/**
* 验证信息异常处理
* @param e
* @return
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public ResultResponse handleValidationException(ValidationException e) {
LOG.error("参数验证失败 {}", e);
return new ResultResponse().fail("params validation fail");
}
/**
* 业务异常处理
* @param e
* @return
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BusinessException.class)
public ResultResponse handlerBusinessException(BusinessException e){
LOG.error("业务处理异常 errorMsg:{}",e.getMessage());
return new ResultResponse().fail(e.getMessage());
}
/**
* 系统未知异常处理
* @param e
* @return
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public ResultResponse handlerException(Exception e){
LOG.error("系统未知异常 errorMsg:{}",e.getMessage());
return new ResultResponse().fail(e.getMessage());
}
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResultResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
LOG.error("系统不支持当前请求方法 {}", e);
return new ResultResponse().fail("not supported method");
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResultResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception){
//解析原错误信息,封装后返回,此处返回非法的字段名称,错误信息
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
return new ResultResponse().fail(error.getDefaultMessage());
}
return new ResultResponse().fail("参数校验失败");
}
}
Bean Config
package com.hello.bconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
@Configuration
public class BeanConfig {
@Bean
public MethodValidationPostProcessor getMethodValidationPostProcessor(){
return new MethodValidationPostProcessor();
}
}
结果:
https://github.com/dingjianglei/spring-restful-demo