在servlet目录下创建个servlet类,示例代码如下:
package com.bjpowernode.springboot.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;public class HeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("he springboot servlet"); resp.getWriter().flush(); resp.getWriter().close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); }}
编写配置类:
package com.bjpowernode.springboot.config;import com.bjpowernode.springboot.servlet.HeServlet;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.servlet.ServletRegistration;@Configurationpublic class ServletConfig { @Bean public ServletRegistrationBean heServletRegisterBen() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean( new HeServlet(), "/servlet/heservlet" ); return servletRegistrationBean; }}
注意需要加的两个注解:@Configuration 还有@Bean
然后就可以启动springboot项目访问地址:http://localhost:8080/servlet/heservlet
进行测试了。