1 复古的玩法,在springboot中集成servlet
之所以称为复古,因为玩springboot都可以直接使用springmvc去用控制器来搞定servlet要做的角色了。
而在学习之初,也可以先学习一下servlet的“组件+容器”的玩法
2 实现的思路
1 方式一:全注解方式
在启动类上加上@ServletComponentScan注解
编写完Servlet后,在组件上加上@WebServlet(name="zfhServletName",urlPattern="/zfhTest")
2 方式二:直接使用java配置类方式
写一个类,然后加上@Configuration注解
在类中注册自己写的servlet组件,也就是bean,并配置相应的url参数即可
3 实现代码
3.1 实现方式1
//启动类上加入Servlet扫描注解
@SpringBootApplication
@ServletComponentScan
public class SpringbootservletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootservletApplication.class, args);
}
}
//编写Servlet类
@WebServlet(name="zfhServlet",urlPatterns = "/zfhTest")
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("fhzheng提醒你 -servlet已经开始运行");
}
}
采用以上方式编写代码后,我们可以使用
http://localhost:8080/test访问servlet了
3.2 实现方式2
@SpringBootApplication
public class SpringbootservletApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootservletApplication.class, args);
}
}
//编写servlet
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("fhzheng提醒你 -servlet已经开始运行");
}
}
//编写configuration类
package com.zfh;
import com.zfh.servlet.TestServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletConfig {
/**
* 多个Servlet 需实例化多个ServletRegistrationBean实例
*/
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new TestServlet());
//Servlet既可以使用 test01也可以使用test02访问
bean.addUrlMappings("/test02");
bean.addUrlMappings("/test01");
return bean;
}
}
-------编写以上代码后,我们可以使用----
http://localhost:8080/test01 访问servlet了
http://localhost:8080/test02 访问servlet了
SpringBoot中集成Servlet的复古玩法
1091

被折叠的 条评论
为什么被折叠?



