How to get the DispatcherServlet from spring WebApplicationContext? - spring-boot

How to get the DispatcherServlet instance from a spring WebApplicationContext object?
I want to perform a direct request to the the front controller servlet (avoiding the network interface) and check the response from a spring application, e.g. WebApplicationContext instance.
Notice, we are not able to use MockMvc to check the HTML rendered by JSP because: "if you use JSPs, you can verify the JSP page to which the request was forwarded, but no HTML is rendered"(according to MockMvc vs End-to-End Tests)
So maybe if we get the DispatcherServlet instance we could perform the request through its doDispatch method and check the content from response.

When you look at
DispatcherServlet.java, there is a constructor with WebApplicationContext as parameter, but the super constructor from FrameworkServlet.java does only hold the field itself, without any callbacks - so the given web application context will not know the dispatcher servlet.
So I don't think you can resolve the dispatcher servlet by the WebApplicationContext. Of course you could try to inject/autowire the DispatcherServlet - maybe this is also possible inside tests, but I am not sure.
I think the most easiest way to check for JSP outputs would be to test those parts with a real server as described at Testing with a running server . This should give you the complete output and web application behaviour inside your test without any workarounds.

Dispatcher Servlet : It acts as front controller for Spring based web applications. It provides a mechanism for request processing where actual work is performed by configurable, delegate components. It is inherited from HttpServlet, HttpServletBean and FrameworkServlet. It also implements ApplicationContextAware hence it is able to set ApplicationContext.
WebApplicationContext : It is an extension of a plain ApplicationContext. It is web aware ApplicationContext i.e it has Servlet Context information. When DispatcherServlet is loaded, it looks for the bean configuration file of WebApplicationContext and initializes it.
So you can set and get the instance of any ApplicationContext from DispatcherServlet but not vice-versa.
dispatcherServlet.getWebApplicationContext();
Although, you can get an instance of DispatcherServlet but I doubt it will serve your purpose as it's scope is protected.
#Autowired
DispatcherServlet dispatcherServlet;
Code inside DispatcherServlet
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
It is possible to create your own DispatcherServlet and perform actions. You can override the default one created by Spring boot app.
Sample:
public class SampleDispatcherServlet extends DispatcherServlet {
private final Log logger = LogFactory.getLog(getClass());
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
// You can use other implementations of HttpServletRequest and
// HttpServletResponse as per your requirement
// e.g. FormContentRequestWrapper , ResourceUrlEncodingResponseWrapper many more
if (!(request instanceof ContentCachingRequestWrapper)) {
request = new ContentCachingRequestWrapper(request);
}
if (!(response instanceof ContentCachingResponseWrapper)) {
response = new ContentCachingResponseWrapper(response);
}
HandlerExecutionChain handler = getHandler(request);
try {
// Any task to be done
super.doDispatch(request, response);
} finally {
// Some task to be done
}
}
}
HandlerExecutionChain- Handler mapper is used to match current request to appropriated controller. Interceptors are the objects invoked before and after some of dispatching actions
Then we have to register the DispatcherServlet:
#Bean
public ServletRegistrationBean dispatcherRegistration() {
return new ServletRegistrationBean(dispatcherServlet());
}
//The bean name for a DispatcherServlet that will be mapped to the root URL "/"
#Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
return new SampleDispatcherServlet();
}

Related

Setting Request scoped bean in spring mvc

I want to capture some request specific data 'under the covers' for every request coming into my spring controllers and store this in a request scoped bean for use at a lower level in the app , like the DAO layer. I've tried using interceptors, but the request scoped bean is always null in that case. This is my latest attempt using RequestContextListener.
#Configuration
#WebListener
public class MyRequestListener extends RequestContextListener {
#Autowired
RequestContext requestContext;
#Override
public void requestInitialized(ServletRequestEvent sre) {
// requestContext.setHttpRequestId(((HttpServletRequest)sre.getServletRequest()).getSession().getId());
System.out.println(requestContext);
}
}
then in some config class I have this (RequestContext is a simple class with one setter/getter for a piece of String data)
#Bean
#RequestScope
public RequestContext requestContext() {
return new RequestContext();
}
Error in the requestInitialized method now is
"No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request."
What's the idiomatic way of achieving this seemingly simple and surely common requirement ?

How manage tomcat servlets with Spring applications?

I am a litter bit confuse about tomcat and his purples regarding servlets.
Tomcat is a servlet container, so if we implement HttpServlet this instance will be manage by apache tomcat (will make sure to call the method based on the URL request and HTTP verb)
public class ExampleHttpServlet extends HttpServlet
{
private String mymsg;
public void init() throws ServletException {
mymsg = "Http Servlet Demo";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + mymsg + "</h1>");
out.println("<p>" + "Hello Friends!" + "</p>");
}
public void destroy() {
// Leaving empty. Use this if you want to perform
//something at the end of Servlet life cycle.
}
}
So if we will have multiple servlets apache tomcat will find them, and based on the url will call the appropriate servlet.
But how is this working with spring boot and spring mvc if we don't implement any HttpServlet?
Let's say that we have a simple REST api. What will manage tomcat here if we don't implement any HttpServlet, or in this case will not be created any servlets, and tomcat will only forward the request to DispatcherServlet and from here DispatcherServlet identifies the controller and further the handler?
Or maybe is there created a servlet automatically for each Controller?
I found this picture but I don't see from where comes up the intermediat servlets in tomcat that forwards the request to Dispatcher.
I tried to find more details here but with not to much success. Any resource si welcome.
Thanks

How exactly work the HandlerExceptionResolver interface in Spring? Can I show an error page when the user try to access to a not mapped resource?

I am studying how to handle custom exception in Spring on a tutorial that show me this class named ExceptionHandler that implement the HandlerExceptionResolver Spring interface:
#Component
public class ExceptionHandler implements HandlerExceptionResolver {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
#Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
System.out.println("Spring MVC Exception Handling");
logger.error("Error: ", exception);
return new ModelAndView("error/exception","exception","ExceptionHandler message: " + exception.toString());
}
}
And then, into a controller class of the example, it throws this exception in this way:
#RequestMapping(value="/throwRunTimeException", method=RequestMethod.GET)
public void throwException() {
throw new RuntimeException();
}
So I have some doubts about how exactly do this class.
I can't understand if implementing the HandlerExceptionResolver interface I am declaring a new specific exception type or if simply specify a specific behavior that happens when a generic runtime exception is thrown.
It seems me the second situation...I think that, in the previous example, when a generic RuntimeException is thrown it return an exception.jsp page (and the related message that have to be shown into the model object).
So, if the previous assertion is true, can I use this method for the following pourpose?
I think that when a user try to open an URL that is it not mapped to any controller method a RuntimeException is thrown.
So, into the **resolveException()** method, can I extract the required URL from the HttpServletRequest request input parameter and use it to show a specific error message (that indicate that this URL not exist) into the returned view?
I don't think that is possible. When the DispatcherServlet can't find the url mapped in one of your controllers, it will throw a NoHandlerFoundException. This will then be forwarded to your servlet container like Tomcat which handles the error and shows the 404 page for example. You can change this behaviour by adding the following to your web.xml:
`
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/404error.jsp</location>
</error-page>
`
Note that it's not possible yet to configure this in JavaConfig.
For other Exceptions that are thrown you can use the HandlerExceptionResolver to return the desired view.
You could also use the #ExceptionHandler annotation on a method in your controller to catch the exceptions and handle them appropriately. This can be combined with the #ControllerAdvice annotation to enable this for every controller.

Spring Boot - access component inside a servlet

I have a spring boot application that serves my jersey based api. I have a requirement to have the services layer serve blob data to a client as a stream. I wrote a servlet to do that and configured it as follows.
#Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new BlobReaderServlet(),"/blobReader/*");
}
However, in the servlet code I can't seem to inject any components (they are all null). I need to inject a component that actually loads the blob data from the database.
#WebServlet(name = "BlobReaderServlet",
urlPatterns = {"/blobreader"})
#Component
public class BlobReaderServlet extends HttpServlet {
Logger logger = Logger.getLogger(this.getClass().getName());
#Inject
DocumentLoaderComponent blobLoader;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
I strongly suspect the servlet isn't a spring managed component after all and dependency injection isn't working. How can I get access to a component from the context?
UPDATE
It was much simpler than I thought.
#Override
public void init() throws ServletException {
ApplicationContext ac = (ApplicationContext) getServletConfig().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.documentBlob = (DocumentBlob) ac.getBean("documentBlobBean");
}
You are correct that your servlet isn't a Spring managed bean. That is because you are instantiating the instance directly (i.e., calling new BlobReaderServlet() in your bean method). Another solution is to change your configuration class as follows:
#Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(blobReaderServlet(),"/blobReader/*");
}
#Bean
public BlobReaderServlet blobReaderServlet(){
return new BlobReaderServlet();
}
This will allow Spring to manage the instance and perform autowiring on it.

Access Business Object in a servlet inside JSF / Spring application?

Usually, i'm accessing business objects (services) with #ManagedProperty in a main class annotated with #ManagedBean.
Here, i have a Servlet and i want to inject my business objects.
The use of managedProperty doesn't work with the annotation #WebServlet.
When i use WebApplicationContext, it's working.
Does the use of WebApplicationContext is the clean way to do that or is there a cleaner method to do it ?
#WebServlet(urlPatterns ="/Graphic")
public class GraphicServlet extends HttpServlet {
// Method 1 - This is not working ( the usual way in a ManagedBean)
#ManagedProperty(value="#{participantBo}")
private ParticipantBo participantBo; // getters and setters added
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Method 2 - This is working
WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
ParticipantBo participantBo = (ParticipantBo) springContext.getBean("participantBo");
List<Participant> myParticipants = participantBo.findAllParticipant();
for (Participant participant : myParticipants) {
System.out.println(participant.getId_study());
}
}
}
Using WebApplicationContext is one of the ways to access the Spring web context from where you want. In fact, if you are able to reach Spring beans using #ManagedProperty, it means you have tied JSF and Spring frameworks in some way. #ManagedProperty should work only for JSF managed beans. However, being your servlet totally independent from the framework, accessing the Spring context this way is a choice.
See also:
https://stackoverflow.com/a/12244697/1199132
Spring Integration with other frameworks

Resources