开发者

Spring MVC: How to get view-name in JSP?

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 "pr开发者_JS百科ofile";
}


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>


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


Just for people that will search for Thymeleaf solution:

${#httpServletRequest.getServletPath()}


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

${pageContext.request.servletPath}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜