Search code examples
springspring-mvcjsp-tagsspring-form

spring model attribute inside jsp 2.0 tag


In my view I have a simple form like this which works :

<form:form modelAttribute="user" >
        <form:input path="lastName"/> <br/>
    </form:form>

I am trying to make a tag to generate my form like this :

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<%@ attribute name="model" required="true" type="com.myObject"%>
    <form:form modelAttribute="model" >

        <form:input path="lastName"/> <br/>

    </form:form>

called like this :

<%@ taglib prefix="ahead" tagdir="/WEB-INF/tags" %>
<ahead:form model="${user}"></ahead:form>

But it throw an exception : Neither BindingResult nor plain target object for bean name 'model' available as request attribute

If in my tag I write this :

<form:form modelAttribute="user" >

it works because I guess it finds the attribute "user" in the model

But I want to use the attribute "model" :

<%@ attribute name="model" required="true" type="com.myObject"%>

because it won't always be called the same in the model.

How can I achieve that ?

thanks


Solution

  • <form:form modelAttribute="model" >
    

    Your current implementation of the tag has a hard-coded name for the modelAttribute property it will always be model regardless of the value of the passed in attribute is.

    To make it dynamic use an expression instead of a hard-coded value.

    <form:form modelAttribute="${model}" >
    

    This will replace the expression with the value of the passed in attribute named model.