我的代码如下:
package com.snsprj.controller; import com.github.pagehelper.PageInfo; import com.snsprj.common.ServerResponse; import com.snsprj.service.IProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; /** * Created by skh on 2017/6/27. */ @Controller @RequestMapping("/product") @Validated public class ProductController { @Autowired private IProductService iProductService; @RequestMapping("list") @ResponseBody public ServerResponse<PageInfo> getProductList(@Min(0) Integer category_id, @NotNull Integer page_num){ // TODO 若 categoryId=0 则显示所有商品 Byte status = 1; PageInfo page = iProductService.getProductByCategoryId(category_id,status,page_num,1); return ServerResponse.createBySuccess(page); } }
我的问题是怎么设置提示信息呢?比如提示:category_id必须为大于等于0的整数。
我配置了spring全局异常捕获,代码如下:
package com.snsprj.common.exception; import com.snsprj.common.ServerResponse; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import java.io.IOException; /** * Created by skh on 2017/6/29. */ public class DefaultExceptionHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView mv = new ModelAndView(); // handle ConstraintViolationException if(ex instanceof ConstraintViolationException){ // set status code response.setStatus(HttpStatus.OK.value()); // set content type response.setContentType(MediaType.APPLICATION_JSON_VALUE); // set character encoding response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache, must-revalidate"); try { // TODO get detail error message response.getWriter().write("{\"success\":false,\"msg\":\" invalid parameter!\"}"); } catch (IOException e) { e.printStackTrace(); } } return mv; } }