java添加request请求参数错误,Java Spring-如何处理缺少的必需请求参数

Consider the following mapping:

@RequestMapping(value = "/superDuperPage", method = RequestMethod.GET)

public String superDuperPage(@RequestParam(value = "someParameter", required = true) String parameter)

{

return "somePage";

}

I want to handle the missing parameter case by not adding in required = false. By default, 400 error is returned, but I want to return, let's say, a different page. How can I achieve this?

解决方案

If a required @RequestParam is not present in the request, Spring will throw a MissingServletRequestParameterException exception. You can define an @ExceptionHandler in the same controller or in a @ControllerAdvice to handle that exception:

@ExceptionHandler(MissingServletRequestParameterException.class)

public void handleMissingParams(MissingServletRequestParameterException ex) {

String name = ex.getParameterName();

System.out.println(name + " parameter is missing");

// Actual exception handling

}

I want to return let's say a different page. How to I achieve this?

Much like standard controller methods annotated with a @RequestMapping

annotation, the method arguments and return values of

@ExceptionHandler methods can be flexible. For example, the

HttpServletRequest can be accessed in Servlet environments and the

PortletRequest in Portlet environments. The return type can be a

String, which is interpreted as a view name, a ModelAndView object, a

ResponseEntity, or you can also add the @ResponseBody to have the

method return value converted with message converters and written to

the response stream.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值