Java 在 Spring MVC 中重定向期间传递模型属性并在 URL 中避免相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24301114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:22:15  来源:igfitidea点击:

Passing model attribute during redirect in spring MVC and avoiding the same in URL

javaspring-mvcjspredirect

提问by Chandni

My objective is to pass model attributes from controller to JSP page during a redirect and avoid the attribute being displayed in URL. The source code below is validating login from datastore using java data objects.

我的目标是在重定向期间将模型属性从控制器传递到 JSP 页面,并避免该属性显示在 URL 中。下面的源代码使用 java 数据对象验证来自数据存储的登录。

Controller:

控制器:

@Controller
public class LoginController {
    int count;
    PersistenceManager pm = PMF.get().getPersistenceManager();

    //Instance of data class
        User user;
    ModelAndView modelAndView=new ModelAndView();

    @RequestMapping(value="/Login",method = RequestMethod.POST)
    public ModelAndView loginValidate(HttpServletRequest req){

        //Getting login values
        String uname=req.getParameter("nameLogin");
        String pswd1=req.getParameter("pswdLogin");
        count=0;


        user=new User();

        //Generating Query
        Query q = pm.newQuery(User.class);
        q.setFilter("userName == userNameParam");
        q.declareParameters("String userNameParam");

        try{
            List<User> results = (List<User>) q.execute(uname);  
            for (User u: results) {

                String userName=u.getUserName();

                if(userName.equals(uname)){

                    System.out.println(u.getPassword());

                    if(u.getPassword().equals(pswd1)){
                        count=count+1;
                        modelAndView.setViewName("redirect:welcome");
                        modelAndView.addObject("USERNAME",uname);
                        return modelAndView;

                    }
         //rest of the logic 
    }

JSP:

JSP:

 <h1>Welcome ${USERNAME} </h1>

My current URL is /welcome?USERNAME=robin
My goal is to display it as /welcome
Also, my page is supposed to display "Welcome robin" whereas it displays only Welcome.

我当前的 URL 是/welcome?USERNAME=robin
我的目标是将它显示为/welcome
另外,我的页面应该显示“Welcome robin”,而它只显示 Welcome。

采纳答案by Serge Ballesta

RedirectAttributes only work with RedirectView, please follow the same

RedirectAttributes 仅适用于 RedirectView,请遵循相同的规则

@RequestMapping(value="/Login",method = RequestMethod.POST)
public RedirectView loginValidate(HttpServletRequest req, RedirectAttributes redir){
...

    redirectView= new RedirectView("/foo",true);
    redir.addFlashAttribute("USERNAME",uname);
    return redirectView;
}

Those flash attributesare passed via the session (and are destroyed immediately after being used - see Spring Reference Manual for details). This has two interests :

这些flash 属性通过会话传递(并在使用后立即销毁 - 有关详细信息,请参阅 Spring 参考手册)。这有两个利益:

  • they are not visible in URL
  • you are not restricted to String, but may pass arbitrary objects.
  • 它们在 URL 中不可见
  • 您不仅限于字符串,还可以传递任意对象。

回答by DhafirNz

You need to be careful here because I think what are you trying to do is not supported for a good reason. The "redirect"directive will issue a GETrequest to your controller. The GETrequest should only retrieve existing state using request parameters, this is the method contract. That GETrequest should notrely on a previous interaction or on any object stored some where in the session as a result of it. GETrequest is designed to retrieve existing (persisted) state. Your original (POST) request should have persisted everything you need for you GETrequest to retrieve a state.

你在这里需要小心,因为我认为你想要做的事情有充分的理由不被支持。在“重定向”指令将发出GET请求控制器。的GET请求只应使用请求参数检索现有状态,这是该方法的合同。该GET请求不应依赖于先前的交互或因此而存储在会话中某个位置的任何对象。GET请求旨在检索现有(持久)状态。您的原始 ( POST) 请求应该保留了您GET请求检索状态所需的一切。

RedirectAttributesare not designed to support you in this case, and even if you managed to correctly use it it will only work once and then they will be destroyed. If you then refresh the browser you will get an application error because it cannot find your attributes anymore.

在这种情况下,RedirectAttributes并不是为支持您而设计的,即使您设法正确使用它,它也只能工作一次,然后它们将被销毁。如果您随后刷新浏览器,您将收到一个应用程序错误,因为它无法再找到您的属性。

回答by devutkarsh

All the objects that are send using redirect can be passed in URL itself from controller as -

使用重定向发送的所有对象都可以从控制器作为 URL 本身传递 -

String message = "Hi Hello etc etc"
return new ModelAndView("redirect:" + "welcome", "message", message);

This message variable will be available in URL as a GET request -

此消息变量将在 URL 中作为 GET 请求提供 -

http://localhost:8080/Demo/welcome?message=Hi Hello etc etc

You can now access the variable on your JSP through Scriptlet -

您现在可以通过 Scriptlet 访问 JSP 上的变量 -

<%= request.getParameter("message") %>