Servlet3.0要点小结
1. 注解配置Servlet
@WebServlet
name属性: servlet名称
value属性或urlPatterns属性: servlet映射路径, 可配置多个
initParams属性: 初始化参数, 配合@WebInitParam一起使用
loadOnStartup属性: 为1表示web容器启动时就初始化servlet
测试代码:
1 /** 2 * Created by IntelliJ IDEA. 3 * 4 * @Auther: ShaoHsiung 5 * @Date: 2018/9/5 16:36 6 * @Title: 01 演示@WebServlet的使用 7 * @Description: name, urlpatterns, initparams(配合@WebInitParam使用), loadOnStartup 8 */ 9 @WebServlet(name = "MyWebServlet", urlPatterns = {"/servlet/MyWebServlet", "/servlet/WebServlet"}, 10 initParams = { @WebInitParam(name = "Site :", value = "http://roseindia.net"), 11 @WebInitParam(name = "Rose", value = "India", description = "detail-info")}, loadOnStartup = 1) 12 public class MyWebServlet extends HttpServlet { 13 @Override 14 public void init(ServletConfig config) throws ServletException { 15 Enumeration<String> initParameterNames = config.getInitParameterNames(); 16 while (initParameterNames.hasMoreElements()) { 17 String name = initParameterNames.nextElement(); 18 String value = config.getInitParameter(name); 19 System.out.println("该Servlet的初始化参数为: " + name + "=" + value); 20 } 21 } 22 23 @Override 24 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 25 26 // 通知浏览器读取格式 27 resp.setContentType("text/html;charset=utf-8"); 28 29 Writer out = resp.getWriter(); 30 31 out.write("测试Servlet3.0!!!"); 32 } 33 34 @Override 35 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 36 doGet(req, resp); 37 } 38 }
2. 注解配置监听器
1. Servlet监听器本质?
实现监听器接口的Java程序, 如实现ServletContextListener接口的Java程序
2. 如何使用注解配置监听器
@WebListener
在Servlet监听器上添加@WebListener
测试代码:
1 /** 2 * Created by IntelliJ IDEA. 3 * 4 * @Auther: ShaoHsiung 5 * @Date: 2018/9/5 20:24 6 * @Title: 7 * @Description: 8 */ 9 @WebListener 10 public class MyWebListener implements ServletContextListener { 11 @Override 12 public void contextInitialized(ServletContextEvent servletContextEvent) { 13 System.out.println("监听器初始化"); 14 } 15 16 @Override 17 public void contextDestroyed(ServletContextEvent servletContextEvent) { 18 System.out.println("监听器销毁"); 19 } 20 }
3. 注解配置过滤器
@WebFilter
filterName属性: 监听器名称
value属性或urlpatterns属性: 过滤器拦截的url映射, 可配置多个
测试代码:
1 /** 2 * Created by IntelliJ IDEA. 3 * 4 * @Auther: ShaoHsiung 5 * @Date: 2018/9/5 17:01 6 * @Title: 02 演示@WebFilter的使用 7 * @Description: filterName属性: 过滤器的名称; value或urlpatterns属性: 过滤器拦截的url映射 8 */ 9 @WebFilter(filterName = "MyWebFilter", value = "/servlet/MyWebServlet") 10 public class MyWebFilter implements Filter { 11 @Override 12 public void init(FilterConfig filterConfig) throws ServletException { 13 System.out.println("过滤器初始化"); 14 } 15 16 @Override 17 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 18 System.out.println("过滤器执行"); 19 // 放行 20 filterChain.doFilter(servletRequest, servletResponse); 21 } 22 23 @Override 24 public void destroy() { 25 System.out.println("过滤器销毁"); 26 } 27 }
4. 原生文件上传
1. 原生文件上传原理: servlet3.0将multipart/form-data的post请求封装成part对象, 开发者通过part对象来对上传的文件进行操作.
2. @MultipartConfig的作用:
标识servlet支持原生文件上传
测试代码:
1 /** 2 * Created by IntelliJ IDEA. 3 * 4 * @Auther: ShaoHsiung 5 * @Date: 2018/9/5 17:07 6 * @Title: 03 演示servlet3.0原生文件上传 7 * @Description: 原生文件上传原理: servlet3.0将multipart/form-data的post请求封装成part对象, 8 * 开发者通过part对象来对上传的文件进行操作. 9 */ 10 @WebServlet(urlPatterns = {"/servlet/fileupload"}) 11 @MultipartConfig // 标识servlet支持原生文件上传 12 public class FileUploadServlet extends HttpServlet { 13 @Override 14 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 16 // 字符编码设置 17 req.setCharacterEncoding("utf-8"); 18 resp.setCharacterEncoding("utf-8"); 19 resp.setContentType("text/html;charset=utf-8"); 20 21 // 获取out对象 22 PrintWriter out = resp.getWriter(); 23 24 // 获取上传文件存储路径 25 String realPath = req.getServletContext().getRealPath("/WEB-INF/upload"); 26 File file = new File(realPath); 27 if (!file.exists()) { 28 file.mkdirs(); 29 System.out.println("目录创建成功!"); 30 } 31 // 通过request对象获取part 32 Collection<Part> parts = req.getParts(); 33 if (parts.size() == 1) { // 单文件上传 34 // 通过input标签的name属性获取上传文件 35 Part part = req.getPart("file1"); 36 // 从请求头中解析文件名称 37 String header = part.getHeader("content-disposition"); 38 String fileName = getFileName(header); 39 // 保存文件 40 part.write(realPath + File.separator + fileName); 41 } else { // 多文件上传 42 // 迭代parts 43 for (Part part : parts) { 44 // 获取到part对象之后, 操作步骤与单文件上传相同 45 String header = part.getHeader("content-disposition"); 46 String fileName = getFileName(header); 47 part.write(realPath + File.separator + fileName); 48 } 49 } 50 51 out.println("上传成功!"); 52 out.close(); 53 } 54 55 /** 56 * 从请求头中解析上传文件名 57 * @param header part的请求头 58 * @return 上传文件名 59 */ 60 public String getFileName(String header) { 61 String[] tempArr1 = header.split(";"); 62 String[] tempArr2 = tempArr1[2].split("="); 63 64 String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", ""); 65 return fileName; 66 } 67 }
要点:
1) part对象代表一个上传文件
2) 通过request对象获取part对象
3) 由于servlet3.0没有提供直接获取文件名称的方法, 所以文件名称可以通过part对象获取请求头后, 自己解析.