java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'category' available as request attribute

耗尽温柔 提交于 2019-11-28 10:20:58
Sotirios Delimanolis

If you're getting to index.jsp through something like http://localhost:8080/yourapp, I'll assume you have a <welcome-file> for it.

This means that the index.jsp generates the HTML without any pre-processing by Spring. You're trying to render this

<form:form method="POST" commandName="category" modelAttribute="category" action="search_category">
    <form:input path="category_name" /> 
    <input type="submit" value="Submit">  
</form:form>

where <form:form> is from Spring's tag library. First, note that you are using both commandName and modelAttribute. This is redundant. Use one or the other, not both. Second, when you specify either of these, the tag implementation looks for a HttpServletRequest attribute with the name specified. In your case, no such attribute was added to the HttpServletRequest attributes. This is because the Servlet container forwarded to your index.jsp directly.

Instead of doing that, create a new @Controller handler method which will added an attribute to the model and forward to the index.jsp view.

@RequestMapping(value = "/", method = RequestMethod.GET)
public String welcomePage(Model model) {
    model.addAttribute("category", new Category()); // the Category object is used as a template to generate the form
    return "index";
}

You can get rid of this

<!--  Set the default page as index.jsp -->
<mvc:view-controller path="/" view-name="index"/>

Also, move any mvc configuration from your applicationContext.xml file to your servlet-context.xml file. That's where it belongs. Here's why.

Ashneet

This error usually occurs when your form input ids are not bound properly meaning that the name/id used in form tags different from the bean.

This works for me!

<form method="POST" action="employee.do">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" name="name" /></td> 
        </tr>
        <tr>
            <td>Age</td>
            <td><input type="text" name="age" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Add Employee"/>
            </td>
        </tr>
    </table>    
</form>

Controller

@RequestMapping(value = "/employee", method = RequestMethod.POST)
    private ModelAndView addemployee(Employee emp, ModelAndView model, 
            @RequestParam String name, 
            @RequestParam String age) {

        emp.setAge(age);
        emp.setName(name);
        employeeService.persistEmployee(emp);

        return new ModelAndView("redirect:/employee.do");

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!