Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spring-mvc

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";
}
like image 771
marioosh Avatar asked Aug 30 '11 10:08

marioosh


People also ask

What is view name in Spring MVC?

The view is a component of MVC architecture that is used to return a user interface output to the user in response to the user request. A View page can be any HTML or JSP file. Spring MVC internally uses a view resolver to fetch the requested view to the user.

How pass data from controller JSP in Spring MVC?

Spring MVC exposes a utility class called ModelMap which implicitly extends a LinkedHashMap. In order to pass data from controller to JSP, all you have to do is add a ModelMap argument to your controller method and then populate it inside your method body using the generic addAttribute() method.

What is a JSP view?

View is your JSP/HTML whatever you are using for representation. In case of simple MVC pattern, you can redirect view(i.e., jsp) from a controller (i.e., servlet) using below code : ServletContext context = getServletContext(); RequestDispatcher dispatcher = context. getRequestDispatcher("/viewPage. jsp"); dispatcher.


2 Answers

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>
like image 143
JPoetker Avatar answered Sep 28 '22 01:09

JPoetker


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

like image 25
Cemo Avatar answered Sep 28 '22 03:09

Cemo