10

Is a way to access view name in JSP (profile in example below) or i need to add this name to model ?

@RequestMapping(value="/user/account", method=RequestMethod.GET)
    return "profile";
}

4 Answers 4

15

I ran into this same problem recently. There could be an official way to solve this problem, but I couldn't find it. My solution was to create an interceptor to place the view name into the model.

My interceptor is very simple:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class ViewNameInModelInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {

        if (modelAndView != null) {
            modelAndView.addObject("springViewName", modelAndView.getViewName());
        }
        super.postHandle(request, response, handler, modelAndView);
    }

}

And registering it in the spring config, is also pretty simple (using the namespace configuration):

<mvc:interceptors>
    <beans:bean class="ViewNameInModelInterceptor" />
</mvc:interceptors>
0
9

${requestScope['javax.servlet.forward.servlet_path']}

2
  • This should be flagged as answer !
    – yglodt
    Aug 23, 2013 at 9:55
  • I get requestScope is null, exception message is "cannot index into a null value"
    – cmaduro
    Oct 8, 2014 at 21:07
3

Just for people that will search for Thymeleaf solution:

${#httpServletRequest.getServletPath()}
1
  • Same as @Cyrils answer: Returns path instead of returned view name.
    – dtrunk
    Sep 30, 2015 at 13:43
2

You can get a view name in the jsp page as it shown below:

${pageContext.request.servletPath}
2
  • It doesn't work. It returns: /WEB-INF/pages/profile.jsp, but need profile
    – marioosh
    Sep 9, 2011 at 6:17
  • sorry for that, I do not know an another way except that you already described in your initial message. btw, I always put the view name to the model when I do need it on my view
    – Cyril Deba
    Sep 9, 2011 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.