Answer the question
In order to leave comments, you need to log in
Why, when trying to use @Autowired Spring'a, HttpServlet does not work when going to the page at the address?
Why, when trying to use @Autowired Spring'a, HttpServlet does not work when going to the page with the required address?
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>controller.InitialServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>init</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<properties>
<spring.version>4.3.13.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
public class InitialServlet extends HttpServlet {
private final Logger logger = Logger.getLogger(InitialServlet.class);
private final ControllerFactory controllerFactory = new ControllerFactory();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri = req.getRequestURI();
InternalController controller = controllerFactory.getController(uri);
try {
if (controller == null) {
controller = controllerFactory.getDefaultController();
controller.execute(req, resp);
}
controller.execute(req, resp);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
try {
((ShowErrorController) controllerFactory.getErrorController()).execute(req, resp,e.getMessage());
} catch (Exception e2) {
logger.error("An error has occurred" + e2.getMessage());
e.printStackTrace();
}
}
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
}
Answer the question
In order to leave comments, you need to log in
Because the factory pattern was used, the init method is only distributed by the InitialServlet servlet. This is due to the internal implementation of the initial(ServletConfiguration) method - inside it, the configuration determines which servlet by name and address the bean injection will be distributed to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question