Announcement Announcement Module
Collapse
No announcement yet.
I am confused about submitting forms- some help would be awesome Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • I am confused about submitting forms- some help would be awesome

    I am pretty new to spring MVC and I can't overcome a problem.

    here is the addFriend.jsp:

    Code:
    <c:if test="${!empty USERS}">
        <form:form method="post" action="requestForFriends.html" commandName="user">
            <form:select path="userName">
                <c:forEach items="${USERS}" var="user">
                    <form:option value="${user.userName}"></form:option>
                </c:forEach>
            </form:select>
    
            <input type="submit" value="Send freindship request" />
        </form:form>
    </c:if>
    The ${USERS} is a List that contains many existing User entity instances, each with userName, id, and email.
    Here is the Controller's relevant part:

    Code:
    @RequestMapping("/toAddFriend")
    	public ModelAndView toAddNewFriend() {
    		Map<String, Object> model = new HashMap<String, Object>();
    		model.put("USERS", userService.getUsers());
    		ModelAndView ret=new ModelAndView("addFriend", model);
    		ret.addObject("user", new User());
    		
    		return ret;
    	}	
    	
    	@RequestMapping(value = "/requestForFriends", method = RequestMethod.POST)
    	public ModelAndView requestNewFriend(@ModelAttribute("user") User user, BindingResult result) {
    		System.out.println(user.getUserName());
    		System.out.println(user.getEmail());
    		Map<String, Object> model = new HashMap<String, Object>();
    		model.put("USERS", userService.getUsers());
    		ModelAndView ret=new ModelAndView("addFriend", model);
    		ret.addObject("user", new User());
    		
    		return ret;
    		
    	}
    My problem is whenever I submit the form a new User instance is created and used. This new instance will have the same userName as one of the existing instance but it is still a different object and all it's fields are null.
    I do not want that. Instead of creating every time a new one I want to chose one of the existing User instance from the jsp's select and use that. How should I modify my code to acheive this?

    Any help is highly appreciated-
    Last edited by pr123; Aug 21st, 2012, 04:56 AM.

  • #2
    This question has been answered numerous times before so I suggest a forum search and a read of the reference guide, especially the part about data binding.

    In short you want a PropertyEditor/Converter that uses the username to retrieve the User from the database. use a @InitBinder method to register it for your controller.

    Comment


    • #3
      Thanks, I added this. But something is still missing. The method is never called.

      Code:
      @InitBinder
          protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
              binder.registerCustomEditor(User.class, new PropertyEditorSupport() {            
                  @Override
                  public void setAsText(String userName) {
                      setValue(userService.getUserByName(userName));
                  }
              });
          }
      and adding "userName" as parameter does not help either

      Code:
      @InitBinder
      protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
      binder.registerCustomEditor(User.class, "userName", new PropertyEditorSupport() { 
      @Override
      public void setAsText(String userName) {
      setValue(userService.getUserByName(userName));
      }
      });
      }

      Comment


      • #4
        My bad that isn't going to work (should post at the end of the day). It will only work if your User was part of another form object, however here your User is the form object. Rewrite your controller to something like this.

        Code:
        @ModelAttribute
        public void fillUsers(Model model) {
        	model.put("USERS", userService.getUsers());
        }
        
        @ModelAttribute
        public void getUser(@RequestParam(required=false) String userName, Model model) {
        	User user = new User()
        	if (userName != null) {
        		user = userService.getUserByName(userName);
        	}
        	model.put("user", user);
        }
        
        @RequestMapping("/toAddFriend")
        public String toAddNewFriend() {
        	return "addFriend";
        	return ret;
        }	
        
        @RequestMapping(value = "/requestForFriends", method = RequestMethod.POST)
        public String requestNewFriend(@ModelAttribute("user") User user) {
        	System.out.println(user.getUserName());
        	System.out.println(user.getEmail());
        	return "addFriend";
        	
        }
        Use a couple of @ModelAttribute annotated methods to fill your model.

        Comment


        • #5
          thanks, it works

          Comment

          Working...
          X