Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法从控制器中的请求获取令牌_Java_Spring_Token - Fatal编程技术网

Java 无法从控制器中的请求获取令牌

Java 无法从控制器中的请求获取令牌,java,spring,token,Java,Spring,Token,我试图在Spring中测试loginController,但无法从请求中获取令牌。 在我的测试中 private CsrfToken token; HttpServletRequest request = new MockHttpServletRequest(); @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this);

我试图在Spring中测试loginController,但无法从请求中获取令牌。 在我的测试中

   private CsrfToken token; 
   HttpServletRequest request = new MockHttpServletRequest();

     @Before
     public void setUp() throws Exception {        
         MockitoAnnotations.initMocks(this);
         this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();        
         token = new DefaultCsrfToken("1", "a", "b"); 
         request.setAttribute(CsrfToken.class.getName(), token); 
     }

    @Test
    public void testCtrlCorrecltyHandlesPassword() throws Exception {         
        CsrfToken token2 = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

        MvcResult result = this.mockMvc.perform(get("/rest/login")
                .param("name", name)
                .param("password", password)
                .param("request", request.toString())
                //.sessionAttr("request", request)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();
    }
当我调试时,我看到token2已经成功创建,并且我从请求中获得了它的值,但当我尝试使用完全相同的方法时,它在控制器中

CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
是空的

我还尝试将.sessionatrrequest、request和@ModelAttributerequestHttpServletRequest作为控制器中的参数,但不起作用

最终

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("token", token);

    MvcResult result = this.mockMvc.perform(get("/rest/login").session(session)
            .header("X-Csrf-Token", "")
            .requestAttr(CsrfToken.class.getName(), token)
            .param("name", name)
            .param("password", password)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

我更新了我的问题,以防有人能在这方面帮助我,谢谢