Simple Spring View Controller

Posted on Posted in Java, Technology Center

Here’s a tip in Spring if you want certain URLs to redirect to specific JSP… For example:

//www.ideyatech.com/magic/login.jspx -> acegi_login.jsp

//www.ideyatech.com/magic/logout.jspx -> acegi_logout.jsp

Since Spring does not allow mapping directly to a jsp page. You need to create a controller to return the appropriate view. Alternatively, you can use URLFilenameViewController but then you’ll be limited to “prefix” and “postfix” append only. What if you wanted the mapping to be explicit as shown in example above?

My solution is to create a generic controller that will do the mapping. To do this, I’ve created a ViewMapController which behaves in almost exact the same manner with URLFilenameViewController except that mapping is explicitly specified with the filename.

In the example below, I’ve mapped /login.jspx to /jsp/acegi-login.jsp and /denied.jspx to /jsp/access-denied.jsp
STEP 1: Declare your mapping with SimpleUrlHandlerMapping

SimpleURLHandlerMapping

STEP 2: Declare your viewMapController with the view mapping. Declare your viewMapController with the view mapping.

SimpleURLHandlerMapping

STEP 3: Create the class ViewMapController.

public class ViewMapController extends AbstractController {
private Map viewMap;
private String defaultView;

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String uri = request.getRequestURI();
String key;
String viewName;

int idx = uri.lastIndexOf(“/”);
if (idx > 0)
key = uri.substring(idx+1);
else
key = uri;
if (viewMap.containsKey(key))
viewName = viewMap.get(key);
else
viewName = defaultView;
return new ModelAndView(viewName);
}

public void setViewMap(Map viewMap) {
this.viewMap = viewMap;
}

public void setDefaultView(String defaultView) {
this.defaultView = defaultView;
}
}

Note: the view will be resolved using your viewResolver. In this case, in order to resolve acegi-login to \jsp\acegi-login.jsp, I’ve declared the viewResolver as:

viewResolver

That’s all folks. You now have a more flexible way to map URLs directly to your JSP pages.

One thought on “Simple Spring View Controller

  1. This is a great tutorial. As someone who’s new to Spring I was amazed at how difficult it is to do something as simple as map a jsp.

    The app I’m trying to update (I inherited it) allows the user to click a link on a menu, which open up a jsp into a seperate frame. You’d think would be pretty simple but it’s not. I tried a lot of different solutions to map the url but since all the jsps are in a folder hierarchy standard Spring wouldn’t work.

    In any event, this did the trick and I thank you for taking the time to post it.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.