Java – embedded jetty: select an existing spring MVC controller
context
I work on a web application (using the play framework), and I'm trying to migrate to the traditional servlet model using spring MVC I want to run the embedded jetty container in the existing jetty container (netty)
problem
I'm trying to reuse the created spring context (including all application beans, including the newly added spring MVC controller), but the request mapping is not selected
I debugged spring's dispatcher servlet and did not register a map (so it can't handle any paths)
Trying to solve the problem
This is the manual jetty setup code:
@requiredArgsConstructor public class EmbeddedJetty { private final int port; private final AnnotationConfigWebApplicationContext existingContext; @SneakyThrows public void start() { Assert.notNull(existingContext.getBean(UserController.class)); val server = new Server(port); ServletContextHandler handler = new ServletContextHandler(); ServletHolder servlet = new ServletHolder(new DispatcherServlet(existingContext)); handler.addServlet(servlet,"/"); handler.addEventListener(new ContextLoaderListener(existingContext)); server.setHandler(handler); server.start(); log.info("Server started at port {}",port); } }
The controller here is ignored:
@Controller public class UserController { @GetMapping("/users/{userId}") public ResponseEntity<?> getUser(@PathVariable("userId") long userId) { return ResponseEntity.ok("I work"); } }
topic
What do I need to do to get my embedded jetty settings to get existing controller beans and provide mappings?
Solution
static structure
If you are migrating to the servlet model, you may want to be familiar with the normal structure:
. ├── pom.xml ├── README ├── src │ ├── main │ │ ├── java │ │ ├── resources │ │ │ ├── spring │ │ └── webapp │ │ └── WEB-INF │ │ └── web.xml │ └── test │ ├── java │ └── resources
web. XML is the core descriptor used by J2EE server to deploy applications On the web There are some important components in the application defined in XML:
>Filter > servlet > listener
Sever Start
When the server starts, it will set up listeners to monitor the entire application or request life cycle; It will set up filters to filter requests; It sets up the servlet to handle the request
The way of spring
Spring is a lightweight method that integrates many convenient methods / utilities into our applications It's lightweight because it's attached to our project through only two things:
>On the web Define spring's listener in XML for initialization > point all requests to spring (for spring MVC)
proposal
So, back to our question
>Your jetty server starts with servletcontexthandler, which is related to mapping but not listener (i.e. init without spring config) You should start with webappcontext; > At a minimum, you should add Web XML to obtain the existing controller bean and provide mapping;
reference resources
> filter and listener > servletcontexthandler vs webappcontext