Skip to content
JackSparrow414
Go back

Lessons from Using Spring MVC at Work (Part 2)

Table of contents

Open Table of contents

Article body

The problem:

Today, while implementing a reference lookup, I needed to return a view. In everyday development, I usually use getJspPagePath() and append the path of the view to display. However, this only locates views in the same directory as the current JSP path. If an action needs to return a view in another directory, I cannot use getJspPagePath() this way.

Working through the solution:

  1. My first thought was to redirect with ModelAndView: ModelAndView(“redirect:/project/portal.jsp”);. I was tripped up by something I thought I knew well. When learning JSP, I had learned the difference between redirect and forward: a redirect causes the client to send another request to the server, while a forward stays within one request. I had forgotten that redirect involves two requests. That new request is intercepted by Spring MVC’s DispatcherServlet, which asks HandlerMapping to find a handler. Since I had no matching request mapping, it inevitably returned a 404.

  2. I only wanted to return the desired view from the current action’s request mapping, so I tried specifying the JSP path directly: ModelAndView(“/project/portal.jsp’);. But I still got a 404. Why? The view resolver in the project’s springMvc.xml already had a suffix configured, so I did not need to include that suffix in the view name.

Spring MVC view resolver configured with the /WEB-INF/jsp/ prefix and .jsp suffix

Adding .jsp again to portal therefore prevented the view from being found. I had made the same suffix mistake in the redirect above.

After making this change, I could locate JSP views in any directory.

My takeaway:

Use the second approach when you want to select a view directly.

Remember: redirect makes another request. The value that follows it is the request mapping to call, and should not be treated as a view name.

Clearly, I still need a deeper understanding of Spring MVC!


Share this post:

Previous Post
Learning Linux (Part 1)
Next Post
Spring in Development (Part 1)

Comments

Questions, corrections, and experiences are welcome. Sign in with GitHub to comment; both language versions share this discussion.

Comments are available on the live site only.