可以通過2中方式實現:
方式一,通過註解方式實現;
1、使用Servlet3的註解方式編寫一個Servlet
創建servlet包
編寫MyServlet
package com.springboot.web.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;
@WebServlet(urlPatterns="/myServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = -4134217146900871026L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().print("hello word");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2、在main方法的主類上添加註解:
@ServletComponentScan(basePackages=“com.springboot.web.servlet”)
package com.springboot.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan(basePackages="com.springboot.web.servlet")
public class SpringbootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootWebApplication.class, args);
}
}
測試:
【http://localhost:8080/myServlet】
輸出:my servlet , hello word
運行截圖如下:
方式二,通過Spring boot的配置類實現;
1、編寫一個普通的Servlet(可以看到並沒有配置註解)
package com.springboot.web.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 HeServlet extends HttpServlet {
private static final long serialVersionUID = -4134217146900871026L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().print("hello word");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2、編寫一個Springboot的配置類;
package com.springboot.web.config;
import com.springboot.web.servlet.HeServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** springboot沒有xml , @Configuration可以表示一個spring的配置文件,比如:applicationContext.xml */
@Configuration //一定要加上這個註解,成爲Springboot的配置類,不然不會生效
public class ServletConfig {
@Bean //這個註解就將這個ServletRegistrationBean變成一個Spring的bean類。
public ServletRegistrationBean heServletRegistrationBean(){
ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(), "/heServlet");
return registration;
}
}
測試:
【http://localhost:8080/heServlet】
輸出:he servlet , hello word
運行截圖如下: