SpringMVC里拦截器preHandle里的参数究竟是什么意思

时间:2025-02-24 07:39:13

今天我的update接口老是报错,请求和处理方法和create一模一样。

create接口:

 @RequestMapping(value = "/oftenTraveller/create", method = {})
    public ResponseEntity<Response<OftenTravellerDTO>> createOftenTraveller(HttpServletRequest request, HttpServletResponse response,
                                                              @RequestBody OftenTravellerParam newContent) {

        TokenInMemcached token = getTokenInMemcached(request);

        String userId = ().getId();
        (userId);


        Response<OftenTravellerDTO> resp = new Response<>();
        ("create OftenTraveller :{}", newContent);

        OftenTravellerDTO dto = (newContent);

        (Result.SUCCESS_RESULT);
        // to dto
        (dto);

        return new ResponseEntity<>(resp, );
    }

update接口:

  @RequestMapping(value = "/oftenTraveller/update/{id}", method = {})
    public ResponseEntity<Response<OftenTravellerDTO>> updateOftenTraveller(HttpServletRequest request, HttpServletResponse response,
                                                              @PathVariable Long id, @RequestBody OftenTravellerParam updateContent) throw Exception{
        Response<OftenTravellerDTO> resp = new Response<>();
        ("update OftenTraveller id:{} to {}", id, updateContent);
        OftenTraveller entity = (id);
        if (entity == null) {
            ("OftenTraveller id:{} not found", id);
            (Result.FAIL_RESULT);
            return new ResponseEntity<>(resp, HttpStatus.BAD_REQUEST);
        }
        (id);
        try {
            (entity, updateContent);
        } catch (Exception e) {
            ((), e);
            throw new BusinessException((),e);
        }

        (entity);

        // to dto
        OftenTravellerDTO dto = (entity, );
        (dto);
        (Result.SUCCESS_RESULT);
        return new ResponseEntity<>(resp, );
    }

程序在每次的request拦截器里都会被拦截报错:

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String handlerValue = ();
		String[] methodStringArray = (handlerValue);
		String methodName = methodStringArray[ - 1];
		String apiName = (methodName);//在这儿报错
		……
		

报错内容是空指针;
而我把handler里面的内容打印出来,发现:
create:

public <<>> .(,,)

update:

public <<>> .(,,,) throws 

联系上文:

String apiName = (methodName);//在这儿报错

查看了下(methodName)

public static String getShortMethodName(String fullName) {
		int openBracketIdx = ("(");
		String methodNameWithoutParam = (0, openBracketIdx);
		String[] arrays = ("\\.");
		int length = ;
		return arrays[length - 2] + "." + arrays[length - 1];
	}

最后的“throws ”有问题

在controller里面去掉update后的抛异常的部分,问题解决。

在此,明白了。拦截器里面的三个参数:
request : 是指经过spring封装的请求对象, 包含请求地址, 头, 参数, body(流)等信息.
response:是指经过spring封装的响应对象, 包含输入流, 响应body类型等信息.
handler,是指controller的@Controller注解下的"完整"方法名, 是包含exception等字段信息的.