Spring MVC Tutorial – Passing Request Parameters via JavaScript | JQuery Example

February 10th, 2013 2 comments

In this post I will show how to pass parameters into a controller via a java script ajax. The parameters will be passed into the Spring MVC controller with Jquery javascript example:

MyController.java

@RequestMapping(value = "/processmyvals", method = RequestMethod.GET)
public void process(@RequestParam(value = "myVal1", required = true) String myVal1, @RequestParam(value = "myVal2", required = true) String myVal2, HttpServletRequest request, HttpServletResponse response) throws Exception {
	System.out.println(myVal1);
	System.out.println(myVal2);
        //...
	//writeResponse tha will be injected into as result in the ajax js below
}

myvals.html


...
My Val1: 
My Val2: 

myjavascript.js

function processMyVals(){
	$.ajax({
		type : 'GET',
		url : "myapp/app/processvals",
		data : { "myVal1":$("#myVal1").val(), "myVal2":$("#myVal2").val()},
		success : function(result) {
			$("#displayArea").html(result);
		}
	});
}

Conclusion
As we constantly see using Spring MVC controllers is very simple and straight forward. creating these kind of Spring MVC Controller | Jquery | Javascript come very handy and I use it a lot.

Spring MVC Tutorial – Controller Example Passing Array of Request Param

January 5th, 2013 No comments

In this post I will show how to pass an array of request param like checkboxes values into a Spring MVC Controller. In previous Spring MVC Tutorial Controller Example I detailed the basics of a Spring MVC 3 Controller.
In this example I will show an example of passing an array of values coming as a Request Param into a Controller:

MyController.java

@RequestMapping(value = "/setmycolors", method = RequestMethod.POST)
public ModelAndView handleMyArrayVals(@RequestParam(value = "myColor", required = true) String[] myColor, HttpServletRequest request, HttpServletResponse response) throws Exception {
	System.out.println(myArraysVals);
        //...
	return new ModelAndView("index");
}

myHtmlForm.html


...
Red Blue Yellow ...

Conclusion
Passing parameters in Spring MVC is very easy. The implicit casting to type and structure avery easy and work as expected.

Spring MVC Tutorial – Spring MVC + JPA Example

December 15th, 2012 2 comments

In this Spring MVC tutorial + JPA post, I will show how to use Spring MVC with JPA.
There are few files needed to implement JPA in Spring MVC project.

  • Java Bean file mapped to a correlated table
  • persistence.xml file for DB to project connection
  • POJO annotated with entity manager
  • Data source related configurations
  • User.java

    @Entity
    public class User{
    
        @Id
        private long id;
        private String firstName;
        private String lastName;
    
        //...getters and setters
    }
    

    In the example above My table name and column names are aligned with the table names. Note that in this example I used Eclipse for generating this JPA entity from a table. I found it very useful even as a quick JPA entity quick start which I later manually update.

    In this example, I use a dao in which I will put my db related methods. This way I separate the view layer from the model, logic layer.
    MyController.java

    package com.my.controllers;
    
    import java.util.Date;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class ApplicationsController extends BasicAbstractController {
            //A @repository bean is injected 
    	@Resource
    	private DaoHandler dao;
    	
    	@RequestMapping(value = "/newapplication", method = RequestMethod.GET)
    	public ModelAndView newApplicationForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
    		ModelAndView mav = new ModelAndView("newapplication");	
                    long userId = 5l;
                    User aUser = dao.retrieveUser(userId);
    		return mav;
    	}	
    }
    

    Dao Class – DbDaoHandler
    Note that this Dao class was injected as a @Resource in the controller above.

    @Repository
    public class DbDaoHandler implements DaoHandler {
    
    	@PersistenceContext
    	private EntityManager entityManager;
            
            public User retrieveUserById(long id){
                User aUser =  entityManager.find(User.class,id);
                return aUser;
            } 
    }
    

    Interface – DaoHandler

    public interface DaoHandler{
           public User retrieveUserById(long id);
    } 
    

    persistence.xml

    
    
    	
    		org.eclipse.persistence.jpa.PersistenceProvider
    		jdbc/PropStoreDataSourceMySql
    		com.model.db.User
    		
    			
    			
    			
    		
    	
    
    

    The spring-servlet below holds configuration for an application. The relevant part for this spring MVC + JPA tutorial are enclosed within JPA comment.
    spring-servlet.xml

    
    
    	
    	
    	
    	
    	
    
            
    	
    
    	
    	
    		
    	
    
    	
    		
    	
    
    	
    	
    
    	
    	
    
    	
    		
    			
    		
    
    	
    
    	
    
    	
    		
    		
    		
    	
    
    	
    		
    		
    			
    				classpath:tc-messages
    				classpath:ValidationMessages
    			
    		
    		
    		
    	
    
    	
    		
    			
    			
    		
    	
    
    	
    		
    	
    
    
    

    Spring MVC Default Controller Name

    November 30th, 2012 No comments

    In post I will show how to set a Spring MVC 3 default controller.

    Add a request mapping to “/”. Other, more specific mapping will “win” while this mappaing will be used as default for example: localhost://myapp.com/ will fall into this method.

    @Controller
    public class MyUserInfoController {
    
    	@RequestMapping(value = "/")
    	public ModelAndView index(HttpServletRequest request,
    			HttpServletResponse response) {
    
    		ModelAndView modelAndView = new ModelAndView("mydefault"); 
    		
    		return modelAndView;
    	}
    ...
    

    Now the create a simple mydefault.jsp file and that will be placed in the viewResolver bean in spring-servlet.xml (where all other jsp file are placed.)

            
    		
    		
    		
    	
    

    In web.xml file set the url pattern to be the root of the application.

    Note that though there is the <mvc:resources mapping=”/resources/**” location=”/resources/”>, for small projects for which I want at least some of the static resources to be under the same web application (images, js and css etc…) I dont set the pattern URL to be “/” but I use something like: “/app/”
    I do that because with certain application servers the resources configuration was not working as expected andI had to work hard on that. Setting a base URL for spring MVC mappings is very convinient, so it may work for you in terms of URL structure. I recommend doing so.

    
    		spring
    		org.springframework.web.servlet.DispatcherServlet
    		1
    	
    	
    		spring
    		/app/*
    	
    

    Enjoy and Good Luck!

    Spring MVC Tutorial – Initializing an Attribute

    November 25th, 2012 No comments

    In this Spring MVC Tutorial example post I’ll inroduce a short code snippet which can be used for initializing a model attribute for the first time. For example, a session attribute may be used in controller methods and need to be initialized first. So,instead of a tedious if-else, one can use the following in a controller and whenever one of the mapped methods in that controller is called, the attribute will be created only if it’s null.

    @Controller
    @SessionAttributes({ "dataHolder" })
    public class LoginController extends CommonControllerActions {
    
            //If dataHolder instance is null it will be created for this session.
    	@ModelAttribute("dataHolder")
    	public SessionDataHolder populateSessionDataHolder() {
    		// populates form for the first time if its null
    		return new SessionDataHolder();
    	}
    
    	@RequestMapping(value = "/user/login", method = RequestMethod.GET)
    	public ModelAndView loginView(@ModelAttribute(value="dataHolder") SessionDataHolder dataHolder, HttpServletRequest request, HttpServletResponse response) {
    
    		dataHolder.parseData();
            }
    }
    

    Conclusion
    Session attributes are very useful. handling a session attribute on a controller level makes and treat it like a parameter makes sense and doing so with a simple annotation is easy and more maintainable. I used it and it work as expected.

    Categories: Spring MVC 3 Tags: ,