Search code examples
javaspringliferay-6spring-portlet-mvc

Unable to make Spring MVC portlet with annotations make work


This is my controller

@Controller
@RequestMapping("VIEW")
public class SearchController {

    private static final Log LOGGER = LogFactoryUtil.getLog(SearchController.class);

    @RenderMapping
    public String render() {

        return "view";
    }

    @ActionMapping(params = "action = getResults")
    public void getResults(@ModelAttribute("search") Search search, ActionRequest actionRequest,    ActionResponse actionResponse) {
        String keyword = search.getKeyword();
        LOGGER.info("Keyword: " + keyword);
    }

}

and my bean,

public class Search {

    private String keyword;

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

}

and my view.jsp

<%@page import="org.springframework.web.bind.annotation.RequestMethod"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<portlet:defineObjects />

<portlet:actionURL var = "getResultsURL">
    <portlet:param name="action" value="getResults"/>
</portlet:actionURL>

<form:form action="${getResultsURL}" commandName="search" method="POST">
    <form:input path="keyword"/>
    <input type="submit" value="Search">
</form:form>

and I am getting the following exception

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

It is working fine if I place @ModelAttribute("search") as a parameter in render method, but I know it was absolutely wrong(correct me)

Any suggestions?


Solution

  • You get this exception when the JSP page is rendered, right?

    Spring MVC tells you that it cannot find "search" attribute in the current request. And indeed, your controller doesn't put any instance of Search class to the Spring MVC model.

    Two options:

    1. Create getter for Search class instance with @ModelAttribute annotation:

      @ModelAttribute public Search getSearch() { return new Search(); }

    2. Put Search class instance to the Spring model in the render method:

      @RenderMapping public String render(Model model) { model.addAttribute("search", new Search()); return "view"; }

    This way the form tag will find the model under the given command name.