java 用户使用Spring MVC提交表单后如何获取表单数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12158841/
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-10-31 07:50:35  来源:igfitidea点击:

How to get a form's data after the user submitted it with Spring MVC?

javaexceptionspring-mvcforms-authenticationjava.lang.class

提问by devdar

i am getting an error message: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: java.lang.Object cannot be cast to com.crimetrack.business.Login

我收到一条错误消息:org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.ClassCastException: java.lang.Object 不能转换为 com.crimetrack.business.Login

Login.java

登录.java

public class Login {

    private String userName;
    private String password;
    private boolean loggedin;

    public Login(){};

    /**
     * @return the loggedin
     */
    public boolean isLoggedin() {
        return loggedin;
    }

    /**
     * @param loggedin the loggedin to set
     */
    public void setLoggedin(boolean loggedin) {
        this.loggedin = loggedin;
    }

    /**
     * @param userName
     * @param password
     */
    public Login(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

}


@Controller
public class AuthenticationController {

    private final Logger logger = Logger.getLogger(getClass());

    private AuthenticationManager authenticationManager;
    private Login login = new Login();

    String message = "Congrulations You Have Sucessfully Login";
    String errorMsg = "Login Unsucessful";

    @RequestMapping(value="login.htm")
    public ModelAndView onSubmit(Object command) throws ServletException {

        String userName = ((Login)command).getUserName();
        String password = ((Login)command).getPassword();

        login.setUserName(userName);
        login.setPassword(password);

        logger.info("Login was set");

        logger.info("the username was set to " + login.getUserName());
        logger.info("the password was set to " + login.getPassword());

        if (authenticationManager.Authenticate(login) == true){
            return new ModelAndView("main","welcomeMessage", message);
        }

        //return new ModelAndView("main","welcomeMessage", message);
        return new ModelAndView("login","errorMsg", "Error!!!");
    }

}

回答by sp00m

Try this solution:

试试这个解决方案:

JSP

JSP

<form:form action="yourUrl" modelAttribute="login" method="POST">
<% ... %>
</form:form>

Controller

控制器

// your method that prints the form
public ModelAndView onGet(@ModelAttribute Login login) {
    // return ...
}

@RequestMapping(value="login.htm")
public ModelAndView onSubmit(@ModelAttribute Login login) {
    String userName = login.getUserName();
    String password = login.getPassword();
    // ...
}

Explanation

解释

The annotation @ModelAttributedoes exactly the same as model.addAttribute(String name, Object value). For example, @ModelAttribute Login loginis the same as model.addAttribute("login", new Login());.

注释@ModelAttributemodel.addAttribute(String name, Object value). 例如,@ModelAttribute Login login与 相同model.addAttribute("login", new Login());

That said, with the onGetmethod, you passing such an object to your view. Thanks to the attribute modelAttribute="login", the tag <form:form>will look into the model's list of attributes to find one which name is login. If it doesn't find, an exception is thrown.

也就是说,使用该onGet方法,您可以将这样一个对象传递给您的视图。多亏了属性modelAttribute="login",标签<form:form>将查看模型的属性列表以找到名称为 的属性login。如果没有找到,就会抛出异常。

Then, that's the magic part: with the tag <form:input path="userName" />, Spring MVC will automatically set the property userNameof the bean which is in the modelAttribute="login"attribute, i.e. in your case, login. If you had put something like <form:input path="wtf" />, it would have thrown an exception, because the bean Logindoesn't have such a property.

然后,这就是神奇的部分:使用标记<form:input path="userName" />,Spring MVC 将自动设置属性userName中 bean 的modelAttribute="login"属性,即在您的情况下,login. 如果你放了类似的东西<form:input path="wtf" />,它会抛出一个异常,因为 beanLogin没有这样的属性。

So, finally, on your onSubmitmethod (thanks once again the to annotation @ModelAttribute), you can access to the loginbean, previously autobinded by Spring MVC.

因此,最后,在您的onSubmit方法上(再次感谢 to 注释@ModelAttribute),您可以访问login先前由 Spring MVC 自动绑定的bean。

Note

笔记

I personally (almost) never use a ModelAndViewinstance, but proceed as follow:

我个人(几乎)从不使用ModelAndView实例,但按以下步骤操作:

// the methods can have the name you want
// not only onGet, onPost, etc. as in servlets

@RequestMapping("url1.htm")
public String loadAnyJsp(@ModelAttribute Login login) {
    return "path/to/my/views/login";
}

@RequestMapping("url2.htm")
public String redirectToAnotherController(@ModelAttribute Login login) {
    return "redirect:url1.htm";
}

The path to the JSP is specified within your web.xml file, for example:

JSP 的路径在您的 web.xml 文件中指定,例如:

...
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" p:favorPathExtension="true" p:favorParameter="true" p:ignoreAcceptHeader="true" p:defaultContentType="text/html">
    <description>Depending on extension, return html with no decoration (.html), json (.json) or xml (.xml), remaining pages are decoracted</description>
    <property name="mediaTypes">
        <map>
            <entry key="xml" value="application/xml" />
            <entry key="json" value="application/json" />
            <entry key="html" value="text/html" />
            <entry key="action" value="text/html" />
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.xml.MarshallingView" p:marshaller-ref="xstreamMarshaller" />
            <bean class="org.springframework.web.servlet.view.json.MappingHymansonJsonView" />
        </list>
    </property>
    <property name="viewResolvers">
        <list>
            <bean id="nameViewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
                <description>Maps a logical view name to a View instance configured as a Spring bean</description>
            </bean>
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp" />
        </list>
    </property>
</bean>
...

You should read the docto get more information (cf. 16.5 Resolving views).

您应该阅读文档以获取更多信息(参见 16.5 解析视图)。

回答by Alexander Pogrebnyak

In your 'onSubmit' method you are casting commandto Login.

在您的“onSubmit”方法中,您正在转换commandLogin.

Apparently it is not.

显然不是。