赞
踩
1.添加自定义的Servlet
@WebServlet(name = "FirstServlet", urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("FirstServlet running ...");
PrintWriter out = resp.getWriter();
out.write("success ...");
out.flush();
out.close();
}
}
2.在启动类中添加扫描注解
@SpringBootApplication
// 在SpringBoot 启动的时候回自动去扫描WebServlet注解
@ServletComponentScan
public class GpDblSpringbootServletApplication {
public static void main(String[] args) {
SpringApplication.run(GpDblSpringbootServletApplication.class, args);
}
}
3.启动测试
1.创建自定义的Servlet,不需要添加@WebServlet
package com.dbl.springboot.servlet.demo.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * descrription: * <p> * Create by DbL on 2020/10/25 0025 22:36 */ public class SecondServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("SecondServlet running ..."); PrintWriter out = resp.getWriter(); out.write("success ..."); out.flush(); out.close(); } }
2.在启动类中显示在注册
@SpringBootApplication // 在SpringBoot 启动的时候回自动去扫描WebServlet注解 @ServletComponentScan public class GpDblSpringbootServletApplication { public static void main(String[] args) { SpringApplication.run(GpDblSpringbootServletApplication.class, args); } @Bean public ServletRegistrationBean getRegistrationBean(){ // 将要添加的servlet封装成为一个ServletRegistrationBean ServletRegistrationBean registrationBean = new ServletRegistrationBean(new SecondServlet()); // 设置映射信息 registrationBean.addUrlMappings("/second"); return registrationBean; } }
3.测试
1.直接在过滤器中添加@WebFilter注解
package com.dbl.springboot.servlet.demo.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * descrription: * <p> * Create by DbL on 2020/10/26 0026 7:23 */ @WebFilter(urlPatterns = "/first") public class FirstFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("-----init-----"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("----------First过滤器执行之前-------"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("----------First过滤器执行之后-------"); } @Override public void destroy() { System.out.println("*****destory*****"); } }
2.在启动器中添加@ServletCompoenentScan
3.测试
1.创建自定义的过滤器,不需要添加@WebFilter注解
package com.dbl.springboot.servlet.demo.filter; import javax.servlet.*; import java.io.IOException; /** * descrription: * <p> * Create by DbL on 2020/10/26 0026 7:37 */ public class SecondFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("-----init-----"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("----------Second过滤器执行之前-------"); filterChain.doFilter(servletRequest, servletResponse); System.out.println("----------Second过滤器执行之后-------"); } @Override public void destroy() { System.out.println("*****destory*****"); } }
2.在启动类中显示的注册
package com.dbl.springboot.servlet.demo; import com.dbl.springboot.servlet.demo.filter.SecondFilter; import com.dbl.springboot.servlet.demo.servlet.SecondServlet; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; @SpringBootApplication // 在SpringBoot 启动的时候回自动去扫描WebServlet注解 @ServletComponentScan public class GpDblSpringbootServletApplication { public static void main(String[] args) { SpringApplication.run(GpDblSpringbootServletApplication.class, args); } @Bean public ServletRegistrationBean getRegistrationBean() { // 将要添加的servlet封装成为一个ServletRegistrationBean ServletRegistrationBean registrationBean = new ServletRegistrationBean(new SecondServlet()); // 设置映射信息 registrationBean.addUrlMappings("/second"); return registrationBean; } @Bean public FilterRegistrationBean getRegistractionBean() { FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter()); bean.addUrlPatterns("/second"); return bean; } }
3.测试
1.创建自定义的Listener
package com.dbl.springboot.servlet.demo.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * descrription: * <p> * Create by DbL on 2020/10/26 0026 7:59 */ @WebListener public class FirstListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("FirstListener:初始化了..."); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("FirstListener:销毁了..."); } }
2.添加扫描注解
3.启动测试
1.创建自定义Listener
package com.dbl.springboot.servlet.demo.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * descrription: * <p> * Create by DbL on 2020/10/26 0026 8:05 */ 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.显示的在启动类中注册
@Bean
public ServletListenerRegistrationBean getListenerRegistrationBean(){
ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondListener());
return bean;
}
3.测试
1.创建提交的表单
<!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>
2.服务处理上传请求
package com.dbl.springboot.servlet.demo.file; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * descrription: * <p> * Create by DbL on 2020/10/27 0027 7:36 */ @RestController public class UserController { @RequestMapping("/user/upload") public String upload(MultipartFile upload, String username) throws IOException { System.out.println("userName:" + username + " 文件名称:" + upload.getOriginalFilename()); upload.transferTo(new File("d:/" ,upload.getOriginalFilename())); return "success ..."; } }
3.配置相关的上传参数
spring.servlet.multipart.enabled=true
# 设置单个文件上传的大小
spring.servlet.multipart.max-file-size=200MB
# 设置一次上传文件总的大小
spring.servlet.multipart.max-request-size=200MB
4.测试
1.页面提供一个下载按钮
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>文件上传案例</h1> <h2><a href="/user/download">文件下载</a></h2> <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>
2.服务端处理下载请求
@RequestMapping("/user/download") public void downloadFile(HttpServletRequest request, HttpServletResponse response){ File file = new File("d://Hydrangeas.jpg"); // 设置响应的头和客户端保存的文件名 response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName()); InputStream in = null; ServletOutputStream out = null; try { // 文件的复制 in = new FileInputStream(file); out = response.getOutputStream(); // 循环读取 byte[] b = new byte[1024]; int length = 0; while((length = in.read(b)) > 0){ out.write(b,0,length); } }catch (Exception e){ e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
3.测试
1.添加对应的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.添加一个自定义的控制器
package com.dbl.springboot.servlet.demo.freemarker.controller; import com.dbl.springboot.servlet.demo.freemarker.bean.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList; import java.util.List; /** * descrription: * <p> * Create by DbL on 2020/10/28 0028 6:56 */ @Controller("/freemarker") public class UserController { @RequestMapping("/showUser") public String showUser(Model model) { List<User> list = new ArrayList<>(); list.add(new User(1, 22, "zhangsan")); list.add(new User(2, 23, "lisi")); list.add(new User(3, 24, "wangwu")); model.addAttribute("list", list); return "user"; } }
3.属性文件配置
spring.freemarker.suffix=.ftl
4.模板页面
<html> <head> <title>用户信息</title> <meta charset="UTF-8"> </head> <body> <table border="1" align="center" width="50%"> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> </tr> <#list list as user> <tr> <td>${user.id}</td> <td>${user.userName}</td> <td>${user.age}</td> </tr> </#list> </table> </body> </html>
5.测试
1.添加相关的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.创建自定义的控制器
package com.dbl.springboot.servlet.demo.thymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * descrription: * <p> * Create by DbL on 2020/10/28 0028 7:44 */ @Controller("/thymeleaf") public class UserController { @RequestMapping("/show") public String showInfo(Model model) { model.addAttribute("msg", "Thymeleaf Hello ... "); return "index"; } }
3.创建对应的模板页面
Thymeleaf的模板页面的后缀是.html
和我们讲的html页面的后缀是一样,但可以写标签
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Thymeleaf整合</h1>
<hr>
<span th:text="${msg}"></span>
</body>
</html>
4.测试
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
package com.dbl.springboot.demo.test.service;
/**
* descrription:
* <p>
* Create by DbL on 2020/11/4 0004 6:33
*/
public interface IUserService {
public String query();
}
package com.dbl.springboot.demo.test.impl; import com.dbl.springboot.demo.test.service.IUserService; /** * descrription: * <p> * Create by DbL on 2020/11/4 0004 6:33 */ public class UserServiceImpl implements IUserService { @Override public String query() { return "UserService 单元测试 ... "; } }
package com.dbl.springboot.demo; import com.dbl.springboot.demo.test.service.IUserService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest class GpDblSpringbootServletApplicationTests { @Autowired private IUserService userService; @Test void contextLoads() { System.out.println(userService.query()); } @BeforeEach public void testBefor(){ System.out.println("befor ... "); } @AfterEach public void testAfter(){ System.out.println("after ... "); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。