作为Spring 3 MVC的一部分,可以将当前登录的用户(Principle)对象注入控制器方法.
例如
@Controller
public class MyController {
@RequestMapping(value="/update", method = RequestMethod.POST)
public String update(ModelMap model, Principal principal) {
String name = principal.getName();
... the rest here
}
}
Run Code Online (Sandbox Code Playgroud)
这是作为Spring 3文档的一部分记录的:http: //static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments.
这适用于生产代码.但是我不知道如何测试这个.当我创建集成测试(也设置了spring安全上下文)并调用控制器句柄方法时,Principal始终为null!
public class FareTypeControllerIntegrationTest extends SpringTestBase {
@Autowired
private MyController controller;
@Autowired
private AnnotationMethodHandlerAdapter handlerAdapter;
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Test
public void testUpdate() throws Exception {
request.setRequestURI("/update");
request.setMethod(HttpMethod.POST.name());
... setup rest of request
ModelAndView …Run Code Online (Sandbox Code Playgroud) model-view-controller integration spring controller principal