Announcement Announcement Module
Collapse
No announcement yet.
How Work's @ModelAttribute? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How Work's @ModelAttribute?

    Hi, im new in springsource MVC, and im getting troubles with the @ModelAttribute.
    From the doc's and a few tutorials and post's in forums i suppose the use of @ModelAttribute like the following:

    HomeController
    Code:
    @Controller
    public class HomeController {
    @ModelAttribute("centro")
    	public String getCentro(){
    		return new String();
    	}
    @RequestMapping(value = "/", method = RequestMethod.GET)
    	public String home(Locale locale, Model model) {
    
    		String centro = "00";
    		model.addAttribute("centro",centro);		
    		return "home";
    	}
    @RequestMapping(value = "/home", method = RequestMethod.POST)
    	public String home(@ModelAttribute("centro") String centro,BindingResult result, Model model) {
    		
    		model.addAttribute("centro",centro+"#");		
    		return "home";
    	}
    }
    home.jsp
    Code:
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page session="false" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="<c:url value="/resources/estilos.css" />" />
    	<title>CE</title>
    </head>
    <body>
    <form:form  modelAttribute="centro" method="POST" action="home" >
    <h1>
    	Consumos Eléctricos  
    </h1>
    <a href="usuarios">Usuarios</a> 
    <p> <a href="centros">Centros</a> </p>
    <input name="Centro" value="${centro}"/>
    <input type="submit" name="submit" value="Submit!" /> 
    </form:form>
    </body>
    </html>
    But when i get the POST on Controller the String variable "centro", not back filled with the user input.
    Im missing something??

    Thank's for your time.

  • #2
    I respond me, for all ppl has the same issue.
    You need to use <form:hidden path="*" /> where * is the model property wants to be propagated.

    if model is "centro" and has a field called "fieldcentro":
    Code:
    <form:form  model="centro" method="POST" action="home" >
    <form:hidden path="fieldcentro"/>
    if model contain Lists(model has a .getList() property), varStatus contains your index:
    Code:
    ...
    <c:forEach items="${command.getLf()}" var="fmam" varStatus="status">
    			<tr align="center">
    				<!-- <td>  	<c:out value="${fmam.id}"/></td> -->
    			   
    				<td><c:out value="${fmam.centro}" />
    		<form:hidden path="Lf[${status.index}].centro"/>
    ....

    Comment

    Working...
    X