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

时间:2012-08-28 12:04:26

标签: java exception spring-mvc forms-authentication java.lang.class

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

Login.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!!!");
    }

}

2 个答案:

答案 0 :(得分:2)

试试这个解决方案:

<强> JSP

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

<强>控制器

// 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();
    // ...
}

<强>解释

注释@ModelAttributemodel.addAttribute(String name, Object value)完全相同。例如,@ModelAttribute Login loginmodel.addAttribute("login", new Login());相同。

也就是说,使用onGet方法,将这样的对象传递给视图。由于属性modelAttribute="login",标记<form:form>将查看模型的属性列表,以查找名称为login的属性。如果找不到,则抛出异常。

然后,这是神奇的部分:使用标记<form:input path="userName" />,Spring MVC将自动设置userName属性中bean的属性modelAttribute="login",即在你的情况下,login。如果你输入<form:input path="wtf" />之类的东西,它会引发异常,因为bean Login没有这样的属性。

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

注意

我个人(几乎)从不使用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";
}

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.MappingJacksonJsonView" />
        </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>
...

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

答案 1 :(得分:1)

在“onSubmit”方法中,您将command投射到Login

显然不是。