bind header to controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import lombok.extern.slf4j.Slf4j;
import summer.webserver.util.SummerUtils;

@Slf4j
public class SummerArgumentResolver implements HandlerMethodArgumentResolver {

public SummerArgumentResolver() {
super();
}

@Override
public boolean supportsParameter(MethodParameter parameter) {
return SummerHeader.class.isAssignableFrom(parameter.getParameterType());
}

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
return SummerUtils.getSummerHeader(webRequest.getNativeRequest(HttpServletRequest.class));
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

@Slf4j
public class SummerUtils {
public static SummerHeader getSummerHeader(HttpServletRequest request) {
User user = (User)request.getAttribute("user");
String userName = Objects.isNull(user) ? request.getHeader(USER_NAME) : user.getUserName();
String userId = Objects.isNull(user) ? request.getHeader(USER_ID) : user.getUserId();
SummerHeader summerHeader = SummerHeader.builder()
.userName(userName)
.userId(userId)
.build();

if (log.isDebugEnabled()) {
log.debug(summerHeader.toString());
}
request.setAttribute("summerHeader", summerHeader);
return summerHeader;
}
}

usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14

@Api(tags = "User")
@RestController()
@RequestMapping(ROOT_DOMAIN + "/users")
@Slf4j
public class UserController {
@ApiOperation(value = "delete user")
@DeleteMapping("/{user-id}")
@ResponseStatus(HttpStatus.OK)
public void deleteUser(SummerHeader summerHeader,
@ApiParam(required = true) @Length(max = 10) @PathVariable(value = "user-id") String userId) {
userMapper.deleteById(userId);
}
}

评论