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";
}
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.
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.
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.
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With