目录
SpringBoot整合Servlet
整合方式一
1.1 创建servlet
1.2启动类中配置
1.3 启动测试
整合方式二
2.1创建servlet
2.2 修改启动类
2.3 启动程序测试
SpringBoot整合Filter
整合方式一
1.创建过滤器
2.创建启动类
3.启动测试
整合方式二
1.创建过滤器
2.创建启动类
3.启动测试
SpringBoot整合Listener
整合方式一
1.创建Listener
2.创建启动器
3.启动测试
整合方式二
文件上传和下载
上传操纵
下载操纵
SpringBoot整合Freemarker
SpringBoot整合Thymeleaf
Thymeleaf基本使用
SpringBoot整合Servlet
整合方式一
1.1 创建servlet
在src对应的目录下创建一个servlet,添加相关的get方法,设置@WebServlet注解,如下:
- @WebServlet(name = "FirstServlet",urlPatterns = "/first")
- public class FirstServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("--doGet方法执行了----");
- PrintWriter out = resp.getWriter();
- out.write("success");
- out.flush();
- out.close();
- }
- }
复制代码 1.2启动类中配置
在启动类的头部我们通过@ServletComponentScan注解来加载自界说的Servlet
- @SpringBootApplication
- //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
- @ServletComponentScan()
- public class Springboot01ServletApplication {
- public static void main(String[] args) {
- SpringApplication.run(Springboot01ServletApplication.class, args);
- }
- }
复制代码 1.3 启动测试
通过启动类启动程序访问:http://localhost:8080/first 如下
success
整合方式二
2.1创建servlet
第二种整合servlet的方式不必要在servlet的头部添加@WebServlet注解。
- public class SecondServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("--doGet方法执行了----");
- PrintWriter out = resp.getWriter();
- out.write("success second");
- out.flush();
- out.close();
- }
- }
复制代码 2.2 修改启动类
必要在启动类中单独注册servlet,创建一个新的启动类,具体如下:
- @SpringBootApplication
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class,args);
- }
- @Bean
- public ServletRegistrationBean getServletRegistrationBean(){
- // 直接获取ServletRegistrationBean对象 并关联自定义的servlet
- ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
- // 设置servlet对应的 UrlMapping
- bean.addUrlMappings("/second");
- return bean;
- }
- }
复制代码 2.3 启动程序测试
通过新创建的App启动类启动程序,访问测试 http://localhost:8080/second
success second
SpringBoot整合Filter
整合方式一
1.创建过滤器
创建Filter,而且通过@WebFilter注解配置过滤信息,具体如下:
- @WebFilter(urlPatterns = "/first")
- public class FirstFilter implements Filter {
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
- System.out.println("First过滤器:firstServlet 执行之前");
- filterChain.doFilter(servletRequest,servletResponse);
- System.out.println("First过滤器:firstServlet 执行之后");
- }
- @Override
- public void destroy() {
- }
- }
复制代码 2.创建启动类
启动类和我们前面整合Servlet的第一种方式是一样的。
- @SpringBootApplication
- //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
- @ServletComponentScan()
- public class Springboot01ServletApplication {
- public static void main(String[] args) {
- SpringApplication.run(Springboot01ServletApplication.class, args);
- }
- }
复制代码 3.启动测试
通过启动器启动程序测试如下
整合方式二
1.创建过滤器
创建新的过滤器,不消配置@WebFilter注解,我们同样在启动类中注册过滤器。
- @WebFilter(urlPatterns = "/first")
- public class FirstFilter implements Filter {
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
- System.out.println("First过滤器:firstServlet 执行之前");
- filterChain.doFilter(servletRequest,servletResponse);
- System.out.println("First过滤器:firstServlet 执行之后");
- }
- @Override
- public void destroy() {
- }
- }
复制代码 2.创建启动类
添加获取FilterRegistrationBean对象的方法,并在该方法中注册Filter及配置拦截的请求的URL
- @SpringBootApplication
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class,args);
- }
- @Bean
- public ServletRegistrationBean getServletRegistrationBean(){
- // 直接获取ServletRegistrationBean对象 并关联自定义的servlet
- ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
- // 设置servlet对应的 UrlMapping
- bean.addUrlMappings("/second");
- return bean;
- }
- /**
- * 获取FilterRegistrationBean 对象
- * 注册过滤器并设置拦截的请求地址
- * @return
- */
- @Bean
- public FilterRegistrationBean getFilterRegistrationBean(){
- FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
- // 配置要拦截的请求
- bean.addUrlPatterns("/second");
- return bean;
- }
- }
复制代码
3.启动测试
通过App启动类启动程序,访问测试如下:
SpringBoot整合Listener
整合方式一
1.创建Listener
创建一个自界说的Listener,监听ServletContext的初始化和销毁的行为,具体如下:
- @WebListener
- public class FisrtListener implements ServletContextListener {
- @Override
- public void contextInitialized(ServletContextEvent sce) {
- System.out.println("FirstListener:Servlet容器初始化...");
- }
- @Override
- public void contextDestroyed(ServletContextEvent sce) {
- System.out.println("FirstListener:Servlet容器被销毁了");
- }
- }
复制代码 2.创建启动器
启动还是和之前一样,没什么区别。
- @SpringBootApplication
- //在 springBoot 启动时会扫描@WebServlet,并将该类实例化
- @ServletComponentScan()
- public class Springboot01ServletApplication {
- public static void main(String[] args) {
- SpringApplication.run(Springboot01ServletApplication.class, args);
- }
- }
复制代码 3.启动测试
通过启动类启动程序,观察控制台。
整合方式二
1.创建Listener
创建自界说的监听器,不要添加@WebListener注解
- package com.edu.listener;
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- public class SecondListener implements ServletContextListener {
- @Override
- public void contextInitialized(ServletContextEvent sce) {
- System.out.println("SecondListener : 初始化了....");
- }
- @Override
- public void contextDestroyed(ServletContextEvent sce) {
- System.out.println("SecondListener : 销毁了....");
- }
- }
复制代码 2.创建启动器
创建启动类,同时创建注册Listener的方法,如下
- @SpringBootApplication
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class,args);
- }
- /**
- * 注册自定义的监听器
- * @return
- */
- @Bean
- public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
- ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
- return bean;
- }
- }
复制代码 3.启动测试
启动程序,观察控制台的输出。
输出效果看到不但第二个Listener触发了,而且前面的Listener也触发了。搞定~
文件上传和下载
上传操纵
表单页面
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <h1>文件上传案例:</h1>
- <form action="/user/upload" method="post" enctype="multipart/form-data">
- <label>账号:</label><input type="text" name="username"><br/>
- <label>照片:</label><input type="file" name="upload"><br>
- <input type="submit" value="提交">
- </form>
- </body>
- </html>
复制代码
控制层处理
添加控制器处理上传的文件信息
- @RestController
- @RequestMapping("/user")
- public class UserController {
- @RequestMapping("/upload")
- public String upload(MultipartFile upload,String username) throws IOException {
- System.out.println("账号:"+username+" "+upload.getOriginalFilename());
- upload.transferTo(new File("c:/tools/",upload.getOriginalFilename()));
- return "success:上传成功";
- }
- }
复制代码 设置上传参数
在application.properties中添加配置参数,此处要注意SpringBoot2.x版本的参数和1.x版本的参数设置有区别,必要注意
- # SpringBoot 2.0 版本
- spring.servlet.multipart.enabled=true
- # 设置单个文件上传大小
- spring.servlet.multipart.max-file-size=200MB
- # 设置一次上传请求的文件的总大小
- spring.servlet.multipart.max-request-size=200MB
- # SpringBoot 1.5.9 版本
- #spring.http.multipart.enabled=true
- #spring.http.multipart.max-file-size=10MB
- #spring.http.multipart.max-request-size=100MB
复制代码 测试即可
下载操纵
- @RequestMapping("/exportExcel")
- public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException{
- File file = new File("d://owned.xls");
- //设置响应头和客户端保存文件名
- response.setCharacterEncoding("utf-8");
- response.setContentType("multipart/form-data");
- response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
- try {
- //打开本地文件流
- InputStream inputStream = new FileInputStream(file);
- //激活下载操作
- OutputStream os = response.getOutputStream();
- //循环写入输出流
- byte[] b = new byte[2048];
- int length;
- while ((length = inputStream.read(b)) > 0) {
- os.write(b, 0, length);
- }
- // 这里主要关闭。
- os.close();
- inputStream.close();
- } catch (Exception e){
-
- throw e;
- }
- }
复制代码
SpringBoot整合Freemarker
添加依靠
我们必要额外添加freemarker的依靠,如下:
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-freemarker</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
复制代码
创建controller
创建一个平凡的控制器,跳转到ftl中。
- @Controller
- public class UserController {
- /*
- * 处理请求,产生数据
- */
- @RequestMapping("/showUser")
- public String showUser(Model model){
- List<User> list = new ArrayList();
- list.add(new User(1,"张三",20));
- list.add(new User(2,"李四",22));
- list.add(new User(3,"王五",24));
- //需要一个 Model 对象
- model.addAttribute("list", list);
- //跳转视图
- return "user";
- }
- }
复制代码 创建ftl文件
注意:springBoot 要求模板形式的视图层技能的文件必须要放到 src/main/resources 目录下必须要一个名称为 templates
ftl代码
- <html>
- <head>
- <title>展示用户数据</title>
- <meta charset="utf-9"></meta>
- </head>
- <body>
- <table border="1" align="center" width="50%">
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Age</th>
- </tr>
- <#list list as user >
- <tr>
- <td>${user.userid}</td>
- <td>${user.username}</td>
- <td>${user.userage}</td>
- </tr>
- </#list>
- </table>
- </body>
- </html>
复制代码
属性文件中添加后缀
spring.freemarker.suffix=.ftl
|
测试
创建启动类,然后启动访问测试。
- @SpringBootApplication
- public class Springboot03FreemarkerApplication {
- public static void main(String[] args) {
- SpringApplication.run(Springboot03FreemarkerApplication.class, args);
- }
- }
复制代码
SpringBoot整合Thymeleaf
添加相关的依靠
- <!-- 添加父类的依赖 -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.4.RELEASE</version>
- </parent>
- <dependencies>
- <!-- 添加相关的启动器 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- </dependencies>
复制代码
- 创建存放视图的templates目录以及application.properties
目录位置:src/main/resources/templates
templates:该目录是安全的。意味着该目录下的内容是不允许外界直接访问的。
Thymeleaf基本使用
1.Thymeleaf 特点:
thymeleaf是一种模板语言,可以动态大概静态显示文本内容,Thymelaef 是通过他特定语法对 html 的标志做渲染。具体语法介绍下篇文章单独介绍
2.编写controller
- @Controller
- public class DemoController {
- @RequestMapping("/show")
- public String showInfo(Model model){
- model.addAttribute("msg","Thymeleaf入门案例...");
- return "index";
- }
- }
复制代码
创建视图页面
在我们刚刚创建的templates目录下创建index.html页面,在头部引入
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
- <!DOCTYPE html>
- <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
- <head>
- <meta charset="UTF-8">
- <title>Thymeleaf入门案例</title>
- </head>
- <body>
- <h1>Thymeleaf入门案例:</h1>
- <span th:text="hello"></span>
- <hr>
- <span th:text="${msg}}"></span>
- </body>
- </html>
复制代码
创建启动类
在com.dpb.springboot目录下创建启动类
- @SpringBootApplication
- public class Start {
- public static void main(String[] args) {
- SpringApplication.run(Start.class,args);
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |