spring boot中添加自己的Servlet有两种方法,代码注册Servlet和注解自动注册
一、代码注册通过ServletRegistrationBean、 FilterRegistrationBean 和 ServletListenerRegistrationBean 获得控制。
也可以通过实现 ServletContextInitializer 接口直接注册。
二、在 SpringBootApplication [email protected] 注解后,Servlet、Filter、Listener 可以直接通过 @[email protected]@WebListener 注解自动注册,无需其他代码。
代码注册Servlet
DemoApplication.java
package cn.wuyang.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import cn.wuyang.springboot.servlet.MyServlet;
@SpringBootApplication
public class DemoApplication {
/**
* 使用代码注册Servlet([email protected])
*
*/
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MyServlet(), "/myservlet");// ServletName默认值为首字母小写,即myServlet
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
MyServlet.java
package cn.wuyang.springboot.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns="/myservlet")
public class MyServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(">>>>>>>>>>doGet()<<<<<<<<<<<");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(">>>>>>>>>>doPost()<<<<<<<<<<<");
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>大家好,我的名字叫Servlet</h1>");
out.println("</body>");
out.println("</html>");
}
}
注解注册Servlet
DemoApplication.java
package cn.wuyang.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import cn.wuyang.springboot.servlet.MyServlet;
@SpringBootApplication
@ServletComponentScan //加上这个就可以了
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
MyServlet.java 不变
效果展示
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/11264.html