如何将参数从过滤器发送到控制器?

How can I send a parameter from a filter to a controller?

我需要将用户名对象从过滤器传递到控制器。控制器是为这两个参数设计的,但是参数不能过滤掉帖子。

过滤器中的方法:

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    /*send object to controller*/
    Username username = value; 
    response.sendRedirect("/create-bank-profile");
}

在控制器中:

@RequestMapping(value = "/create-bank-profile", method = RequestMethod.POST)
public ModelAndView register(
    HttpSession session,
    HttpServletRequest request, 
    @RequestParam(required = false, value = "bank-info-check", defaultValue = "false") Boolean isBankCustomer,
    @RequestParam("accessKey") Long accessKey, 
    @RequestParam("secretKey") Long secretKey
) {
     /* access the username object's two fields: aceesskey and secretKey */

}

我想我必须把这个值要求。

您的 create-bank-profile 是一种 POST 方法,无法使用 response.sendRedirect() 发送 POST 请求。

您或许可以从这些选项中检查一些内容:

  • 使用RequestDispatcher

    request.setAttribute("param", "param value");
    RequestDispatcher dispatcher = servletContext().getRequestDispatcher(required_url);
    
  • 在请求中设置需要的参数并使用:

    response.setStatus(307);
    response.addHeader("Location", "required URL");
    

下面注释的代码无效。

    //RequestDispatcher rd=request.getRequestDispatcher("./test1");
    //rd.forward(request, response);
    //chain.doFilter(request, response);

然后我尝试如下。它工作正常。请试试这个。它应该可以正常工作。

我已经使用 servlet 测试了以下代码。我添加了“./test1”。

对于你的场景,你不需要提到“./”你可以只说"required url"

        request.setAttribute("anil", "anil123");
        RequestDispatcher rd= ((HttpServletRequest)request).getRequestDispatcher("./test1");
        rd.forward(request, response);

request.getRequestDispatcher("URL").forward(请求, 响应);