0%

SpringMVC的WebArgumentResolver注入当前登录用户

UserArgumentResolver.java

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
package cn.joinhealth.interview.web.root.resolver;

import cn.joinhealth.interview.common.core.constant.SystemConstant;
import cn.joinhealth.interview.module.manage.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;

/**
* UserArgumentResolver
*
* @author jlin
* @date 2019/4/3 14:05
* @Description
*/
public class UserArgumentResolver implements WebArgumentResolver {

@Override
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {
if (methodParameter.getParameterType() != null
&& methodParameter.getParameterType().equals(User.class)) {
// 判断controller方法参数有没有写当前用户,如果有,这里返回即可,通常我们从session里面取出来
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
Object currentUser = request.getSession().getAttribute(SystemConstant.CLOUD_FOLLOWUP_KEY);
return currentUser;
}
return UNRESOLVED;
}
}

spring-mvc.xml

使用

1
2
3
4
5
6
7
@RequestMapping(value = "list", method = RequestMethod.GET)
@ResponseBody
public SimpleResult list(User user) throws Exception {
SimpleResult result = new SimpleResult();
result.addModel("permissionList", permissionService.list(user.getHospCode()));
return result;
}