Results 1 to 5 of 5

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

  1. #1
    Join Date
    Aug 2012
    Posts
    4

    Default 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 at 03:56 AM.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,629

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Aug 2012
    Posts
    4

    Default

    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));
    }
    });
    }

  4. #4
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,629

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  5. #5
    Join Date
    Aug 2012
    Posts
    4

    Default

    thanks, it works

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •