spring RequestMapping 在没有 ModelAttribute 的情况下无法工作

spring RequestMapping not working without ModelAttribute

我的控制器 class 具有以下请求映射方法。

控制器方法。

@RequestMapping(value="/",method=RequestMethod.GET) 
     public String appStart(@ModelAttribute("tempAdmin") Admin tempAdmin) {
    return "login.jsp";
}

@RequestMapping(method = RequestMethod.POST,name="doLogin")
public ModelAndView doLogin(@ModelAttribute("tempAdmin") Admin tempAdmin, HttpServletRequest request) {

    ModelAndView mvc = new ModelAndView();

    /*
        Buisness logic
    */

    mvc.setViewName("home.jsp");

    return mvc;
}

@RequestMapping("doLogout")
public String logout(HttpServletRequest request) {

    HttpSession session = request.getSession(false);
    if(session != null){
        session.invalidate();
    }

    return "login.jsp";
}

login.jsp

    <form:form action="doLogin" modelAttribute="tempAdmin" cssClass="form-horizontal">
      <div class="form-group">
          <label for="username" class="col-sm-2 control-label">Username</label>
       <div class="col-sm-10">
          <form:input cssClass="form-control" path="adminId" placeholder="username" />
        </div>
     </div>
    <div class="form-group">
         <label for="passwd" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
         <form:password path="password" cssClass="form-control" id="passwd" placeholder="password" />
    </div>
   </div>  
    <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Sign in</button>
     </div>
   </div>
   </form:form>

堆栈跟踪。

Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'tempAdmin' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)

我会告诉你如何改变你的控制器,以避免绑定结果问题。试试这个:

@RequestMapping(method = RequestMethod.POST,name="doLogin")
public String doLogin(@ModelAttribute("tempAdmin") Admin tempAdmin, HttpServletRequest request,Model model) {
    model.addAttribute("tempadmin",new Admin());
    // business logic
    return "home";
}

试一试,如果您有任何其他 类,则也添加 model.addAttribute。你也可以 post 你的 JSP 吗?