如何更改Spring MVC commandName名称?

时间:2014-10-04 19:24:45

标签: jsp spring-mvc

我在Spring MVC中编写Web应用程序,如下所示

@Controller
public class LoginFormController {

    @RequestMapping(value = "/login.html", method = RequestMethod.GET)
    public Login handler(){ 

        Login login = new Login();

        return login;
    }

    @RequestMapping(value = "/login.html", method = RequestMethod.POST)
    public ModelAndView onSubmit(Login login){ 

        String name = login.getUsername();

        Map<String, Object> model = new HashMap<String, Object>();

        model.put("name", name);

        return new ModelAndView("success", "model", model);
    }
}

这是jsp:

<%@ include file="/WEB-INF/views/include.jsp" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
<title>Spring Sample - Login Page</title>
</head>
<body>
    <h3>Login Page</h3><br/>
    <form:form commandName="login" method="POST"> 
        Username:<form:input path="username"/> 
        <font color="red"><form:errors path="username"/></font><br/><br/> 
        Password:<form:password path="password"/> 
        <font color="red"><form:errors path="password"/></font><br/><br/> 
        <input type="submit" value="Login"/> 
    </form:form>
</body>
</html>

此代码工作正常,但如果我想更改commandName =&#34; login&#34;登录到2,如下:

@Controller 公共类LoginFormController {

@RequestMapping(value = "/login.html", method = RequestMethod.GET)
public Login handler(){ 

    Login login2 = new Login();

    return login2;
}

@RequestMapping(value = "/login.html", method = RequestMethod.POST)
public ModelAndView onSubmit(Login login2){ 

    String name = login2.getUsername();

    Map<String, Object> model = new HashMap<String, Object>();

    model.put("name", name);

    return new ModelAndView("success", "model", model);
}

}

我收到此错误:

BindingResult和bean名称&gt; login2&#39;都没有普通的目标对象。可用作请求属性。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

添加以下内容:

@ModelAttribbute("login") Login login2 

到你的处理程序方法,如下所示:

@RequestMapping(value = "/login.html", method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribbute("login") Login login2){ 

    String name = login2.getUsername();

    Map<String, Object> model = new HashMap<String, Object>();

    model.put("name", name);

    return new ModelAndView("success", "model", model);
}

错误的原因是,你是说你正在从表单中提交一个名为“login”的对象,但在处理程序方法中,你的对象名是“login2”,所以如果在中添加@ModelAttribute annotaion handler方法,可以指定commandName的名称。

希望有助于。