In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to integrate Servlet in Springboot. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
First, springboot entry Spring Boot design is designed to simplify the initial construction and development process of new Spring applications. Embedded Tomcat does not need to deploy the WAR file Spring Boot is not an enhancement to Spring functionality, but provides a quick way to use Spring.
POM.xml
An org.springframework.boot spring-boot-starter-parent 2.1.9.RELEASE org.springframework.boot spring-boot-starter-web springBoot initiator is actually a collection of jar packages. SprigBoot provides a total of 44 initiators. 1 spring-boot-starter-web supports full-stack web development, including jar 2 spring-boot-starter-jdbc such as romcat and springMVC. The collection of jar packages that support spring to operate databases in jdbc mode 3 spring-boot-starter-redis supports database operations for redis key-value storage
Controller
Package com.lee.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestControllerpublic class HelloWorld {@ RequestMapping ("/ hello") public Map hello () {Map resultMap = new HashMap (); resultMap.put ("msg", "hello world"); return resultMap;}}
Startup class
Package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringbootApplication {public static void main (String [] args) {SpringApplication.run (SpringbootApplication.class, args);}} @ SpringBootApplication contains @ SpringBootConfiguration, @ EnableAutoConfiguration, @ ComponentScan, @ Configuration and other annotations. It is a configuration class that scans all files under the current package and all subpackages under the current package.
Results: http://localhost:8080/hello
{"msg": "hello world"} II. Springboot integrates Servlet
There are two ways to complete the registration of components:
1. Complete the registration of the component through annotation scanning
FirstServlet
Package com.lee.servlet;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException / * the first way for springboot to integrate servlet: * originally * * firstServlet * com.lee.FirstServlet * firstServlet * / firstServlet * * / @ WebServlet (name= "firstServlet", urlPatterns = "/ firstServlet") public class FirstServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost (req,resp) @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println ("firstServlet.");}}
Startup class:
Package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;// this annotation scans @ WebServlet,// under the current package and its subpackages and instantiates @ ServletComponentScan@SpringBootApplicationpublic class SpringbootApplicationServlet1 {public static void main (String [] args) {SpringApplication.run (SpringbootApplicationServlet1.class,args);}} when the startup class starts.
Results: http://localhost:8080/firstServlet
FirstServlet.2, complete the registration of the component through the method
SecondServlet
Package com.lee.servlet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class SecondServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {this.doPost (req, resp);} @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println ("secondServlet....") }}
Startup class
Package com.lee;import com.lee.servlet.SecondServlet;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class SpringbootApplicationServlet2 {public static void main (String [] args) {SpringApplication.run (SpringbootApplicationServlet2.class,args);} / register scondServlet to servletRegistrationBean @ Bean public ServletRegistrationBean secondServlet () {ServletRegistrationBean bean = new ServletRegistrationBean () Bean.setServlet (new SecondServlet ()); bean.addUrlMappings ("/ secondServlet"); return bean;}}
Results: http://localhost:8080/secondServlet
SecondServlet.... III. Springboot integrates Filter
Two ways to complete the registration of components
1. Complete the registration of the component through annotation scanning
FirstFilter
Package com.lee.filter;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException / * FirstFilter * com.lee.filter.FirstFilter * FirstFilter * / firstServlet * * / / @ WebFilter (filterName = "firstFilter", urlPatterns = {"* .do", "* .action"}) @ WebFilter (filterName = "firstFilter", urlPatterns = "/ firstServlet") public class FirstFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {System.out.println ("first filter init") } @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println ("enter first filter"); filterChain.doFilter (servletRequest, servletResponse); System.out.println ("leave first filter");} @ Override public void destroy () {System.out.println ("first filter destroy");}}
Startup class
Package com.lee;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.ServletComponentScan;// this annotation scans @ WebServlet @ WebFilter and so on under the current package and its subpackages, / / and instantiates @ ServletComponentScan@SpringBootApplicationpublic class SpringbootApplicationFilter1 {public static void main (String [] args) {SpringApplication.run (SpringbootApplicationFilter1.class,args);}} when the startup class starts.
Results: http://localhost:8080/firstServlet
First filter initenter first filterfirstServlet.leave first filter2, complete the registration of the component through the method
SecondFilter
Package com.lee.filter;import javax.servlet.*;import java.io.IOException;public class SecondFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {System.out.println ("second filter init");} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println ("enter second filter"); filterChain.doFilter (servletRequest, servletResponse); System.out.println ("leave second filter") } @ Override public void destroy () {System.out.println ("second filter destroy");}}
Startup class
Package com.lee;import com.lee.filter.SecondFilter;import com.lee.servlet.SecondServlet;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;@SpringBootApplicationpublic class SpringbootApplicationFilter2 {public static void main (String [] args) {SpringApplication.run (SpringbootApplicationFilter2.class,args) } / / Register scondServlet into servletRegistrationBean @ Bean public ServletRegistrationBean secondServlet () {ServletRegistrationBean bean = new ServletRegistrationBean (); bean.setServlet (new SecondServlet ()); bean.addUrlMappings ("/ secondServlet"); return bean;} @ Bean public FilterRegistrationBean secondFilter () {FilterRegistrationBean bean = new FilterRegistrationBean (); bean.setFilter (new SecondFilter ()); bean.addUrlPatterns ("/ secondServlet") Return bean;}}
Results:
Second filter initenter second filtersecondServlet....leave second filter IV. SpringBoot integrates Interceptor
Interceptors have been used before in "springboot uses redis and ThreadLocal for single sign-on". If you are interested, you can take a look.
1. POM org.springframework.boot spring-boot-starter-web2, custom interceptor public class MyInterceptor implements HandlerInterceptor {private final Logger logger = LoggerFactory.getLogger (this.getClass (). GetCanonicalName ()); @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {logger.info ("{}: call before request processing (before Controller method call)", this.getClass (). GetSimpleName (); return true / / execution will not continue until true is returned, returning false to cancel the current request} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {logger.info ("{}: called after the request is processed, but before the view is rendered (after the Controller method is called)", this.getClass () .getSimpleName ()) } @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {logger.info ("{}: called after the end of the whole request, that is, after DispatcherServlet renders the corresponding view (mainly for resource cleanup)", this.getClass () .getSimpleName ()) 3. Add interceptor @ Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter {@ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new MyInterceptor ()) .addPathPatterns ("/ *") / / used to add interception rules / / multiple interceptors to form an interceptor chain / / excludePathPatterns users exclude interception}} this is the end of sharing on how to integrate Servlet in Springboot. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.