JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化

1.JavaBean 什么是JavaBean:符合某些设计规范的类
为什么使用?避免代码重复的问题 起到功能重复使用的问题
【JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化】JavaBean的规范
1.类必须是使用 public 修饰
2.必须有公共的无参数构造器
3.包含属性的操作方法
简单的JavaBean domain dao service
复杂的JavaBean Panel Window
JavaBean包含的成员
1.方法
2.时间
3.属性

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
Javabean JavaBean的内省机制(自省机制)
目的:通过内省机制,获取和操作JavaBean中的成员信息(方法,事件,属性)

package cn.icanci.test1; import java.util.Objects; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.test1 * @Date: Created in 2020/2/7 16:58 * @ClassAction: */ public class User { private String name; private int age; private String password; private String email; private String phone; public String getName() { return name; }public void setName(String name) { this.name = name; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }public String getPassword() { return password; }public void setPassword(String password) { this.password = password; }public String getEmail() { return email; }public void setEmail(String email) { this.email = email; }public String getPhone() { return phone; }public void setPhone(String phone) { this.phone = phone; }@Override public boolean equals(Object o) { if (this == o){ return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return age == user.age && Objects.equals(name, user.name) && Objects.equals(password, user.password) && Objects.equals(email, user.email) && Objects.equals(phone, user.phone); }@Override public int hashCode() { return Objects.hash(name, age, password, email, phone); }@Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", password='" + password + '\'' + ", email='" + email + '\'' + ", phone='" + phone + '\'' + '}'; } }

package cn.icanci.test1; importjava.beans.PropertyDescriptor; import java.beans.*; import java.lang.reflect.Method; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.test1 * @Date: Created in 2020/2/7 16:58 * @ClassAction: */ public class JavaBeanTest { public static void main(String[] args) { try { BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : propertyDescriptors){ //属性名称 System.out.println(prop.getName()); //属性类型 Class propertyType = prop.getPropertyType(); //获取getter 和 setter 方法 Method readMethod = prop.getReadMethod(); Method writeMethod = prop.getWriteMethod(); System.out.println(propertyType); System.out.println(readMethod); System.out.println(writeMethod); System.out.println(); } } catch (IntrospectionException e) { e.printStackTrace(); } } }

打印
age int public int cn.icanci.test1.User.getAge() public void cn.icanci.test1.User.setAge(int)email class java.lang.String public java.lang.String cn.icanci.test1.User.getEmail() public void cn.icanci.test1.User.setEmail(java.lang.String)name class java.lang.String public java.lang.String cn.icanci.test1.User.getName() public void cn.icanci.test1.User.setName(java.lang.String)password class java.lang.String public java.lang.String cn.icanci.test1.User.getPassword() public void cn.icanci.test1.User.setPassword(java.lang.String)phone class java.lang.String public java.lang.String cn.icanci.test1.User.getPhone() public void cn.icanci.test1.User.setPhone(java.lang.String)

EL的基本使用
目的:从作用域中获取指定属性的共享数据
语法:${属性名}
EL存取变量数据的方法很简单,例如:${username}。它的意思是取出某一范围中名称为username的变量
因为我们并没有指定哪一个范围的username,所以它会依序从Page、Request、Session、Application范围查找 假如途中找到username,就直接回传,不再继续找下去,但是假如全部的范围都没有找到时,就回传 ""
属性范围 EL中的名称
Page PageScope
Request RequestScope
Session SessionScope
Application ApplicationScope
JSP 表达式语言定义可在表达式中使用的以下文字

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
JSP的语言定义
JSP 表达式语言提供以下操作符

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
image.png
JSP 表达式语言定义了一组隐式对象
pageContext
JSP 页的上下文。它可以用于访问 JSP 隐式对象,如请求、响应、会话、输出、servletContext 等。例如,${pageContext.response} 为页面的响应对象赋值。
还提供几个隐式对象,允许对以下对象进行简易访问

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
还提供几个隐式对象,允许对以下对象进行简易访问 JSTL表达式
使用JSTL的准备
加入pom.xml依赖
javax.servlet.jsp.jstl jstl-api 1.2 taglibs standard 1.1.2

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
JSTL标签库的使用方法 JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
具体的标签 2.Filter 过滤器
web过滤器可以对所有的请求和响应做拦截过滤
1.以常规的方式调用资源(Servket/JSP)
2.利用修改过的请求信息调用资源
3.调用资源之后,但是响应在客户端之前,对响应做出修改
4.阻止当前资源调用,代之转到其他资源
过滤器在开发中的运用
1.对登陆的请求进行编码
2.登陆验证过滤器
3,敏感字(非法文字)过滤
4.做MVC框架的前端控制器(处理所有共同请求操作,然后再分发)

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
Servlet和Filter开发
Filter的映射细节

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
Filter的映射细节
如果有多个过滤器需要执行,filter-mapping中的顺序就是过滤的顺序
JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
字符编码过滤器 敏感字过滤
package cn.icanci.web.filter; import org.apache.commons.io.filefilter.FileFilterUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web.filter * @Date: Created in 2020/2/8 15:52 * @ClassAction: */ public class MyWrapper extends HttpServletRequestWrapper { public MyWrapper(HttpServletRequest request) { super(request); }/** * 覆盖 * @param name * @return */ @Override public String getParameter(String name) { if ("title".contains(name)||"context".equals(name)){ //里面处理过滤的逻辑 //然后再设计一个过滤器类 通过过滤器继续 //装饰设计模式 然后把req修饰一下,然后再从传递给Servlet // } return super.getParameter(name); } }

敏感字过滤的图解

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
敏感字过滤的图解 获取初始化参数有问题的可以看这篇 @getInitParameter() 解释
3.Listener Web的另一 大组件:Listener (监听器).
Web中的监听器,主要用于监听作用域对象的创建,监听作用域对象属性的添加/删除/替换:
1):监听作用域对象的创建和销毁.
ServletRequestListener:监听请求对象的创建和销毁.
HttpSessionListener:监听会话对象(session)的创建和销毁.ServletContextListener :监听应用的创建和销毁.
2):监听作用域对象的属性的添加/删除/替换.
ServletRequestAttributeListener:监听request作用域中属性的添加/删除/替换.Ht tpSessionAttributeListener :监听session作用域中属性的添加/删除/替换.
ServletContextAttributeListener :监听application作用域中属性的添加/删除/替换.
属性监听器
package cn.icanci.web.listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web.listener * @Date: Created in 2020/2/8 20:29 * @ClassAction: */ public class DemoListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent event) { System.out.println("属性添加的监听"); System.out.println(event.getName() + " " + event.getValue()); }@Override public void attributeRemoved(ServletContextAttributeEvent event) { System.out.println("属性删除的监听"); System.out.println(event.getName() + " " + event.getValue()); }@Override public void attributeReplaced(ServletContextAttributeEvent event) { System.out.println("属性修改的监听"); System.out.println(event.getName() + " " + event.getValue()+" "+event.getServletContext().getAttribute(event.getName())); } }

web.xml配置文件 一般的 web.xml配置三大组件的顺序 监听器 -> 过滤器 -> Servlet
cn.icanci.web.listener.ContextLoaderListener cn.icanci.web.listener.DemoListener

4.文件上传 文件上传的准备工作
1.文件上传的控件的所在表单的method必须为POST 因为文件上传GET方式只能上传2kb.POST没有限制
2.上传控件需要使用type的file类型
enctype="multipart/form-data"

3.获取文件上传的名字 任何浏览器都ok
FilenameUtils.getName(fileItem.getName());

文件上传pom.xml依赖
commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.5

文件上传
- 锐客网
username:
password:
image:

package cn.icanci.web; import java.io.File; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; 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; import java.util.List; import java.util.UUID; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web * @Date: Created in 2020/2/7 21:40 * @ClassAction: */ @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解析请求 boolean multipartContent = ServletFileUpload.isMultipartContent(req); if (!multipartContent) { return; }try { //1.创建File表单的封装 DiskFileItemFactory factory = new DiskFileItemFactory(); //创建文件上传处理器 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //3.解析请求 List fileItems = servletFileUpload.parseRequest(req); System.out.println(fileItems.size()); //4.迭代每个item for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { // 普通表单控件 //获取表单属性参数值 String value = https://www.it610.com/article/fileItem.getString("UTF-8"); System.out.println(name + " " + value); } else { //文件控件 String fileNameUUID = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName()); String realPath = req.getServletContext().getRealPath("/headImages"); System.out.println("文件路径为:" + realPath +"\\"+ fileNameUUID); System.out.println(realPath + "\\" + fileNameUUID); fileItem.write(new File(realPath, fileNameUUID)); System.out.println(req.getServletContext().getContextPath()); } } } catch (Exception e) { e.printStackTrace(); }resp.sendRedirect("success.jsp"); return; } }

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
上传文件路径
但是如此设置每次启动服务器文件都没了,所以需要选择以下配置

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
热部署配置
JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
热部署配置
配置之后上传的文件会在target对应目录下

JavaWeb|JavaWeb [2] Filter+Listener+文件上传下载+国际化
文章图片
target对应目录下 文件上传的控制
1.文件名字处理
1.IE6问题.通过 fileItem.getName(); 获取的上传文件的名称或带有路径
使用 FilenameUtils.getExtension(fileItem.getName())获取文件名称 名称使用UUID生成随机唯一名字:
String fileNameUUID = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName());

上传文件的目录,一般保存在应用里面
2.缓存大小和临时目录
超过多少大小就不存放在内存了(缓存大小) 默认是10kb
不放在内存,会放在临时目录:默认是Tomcat/temp中
//设置缓存大小 默认大小是 10240字节 也就是10kb factory.setSizeThreshold(20 * 1024); //设置临时目录 factory.setRepository();

文件上传类型的约束
package cn.icanci.web; import java.io.File; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; 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; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.UUID; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web * @Date: Created in 2020/2/7 21:40 * @ClassAction: */ @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * 允许接收的图片类型 */ private static final String ALLOWED_IMAG_TYPE = "png; gif; jpg; jpeg"; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解析请求 String path = null; boolean multipartContent = ServletFileUpload.isMultipartContent(req); if (!multipartContent) { return; }try { //1.创建File表单的封装 DiskFileItemFactory factory = new DiskFileItemFactory(); //创建文件上传处理器 //设置缓存大小 默认大小是 10240字节 也就是10kb factory.setSizeThreshold(20 * 1024); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //3.解析请求 List fileItems = servletFileUpload.parseRequest(req); System.out.println(fileItems.size()); //4.迭代每个item for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { // 普通表单控件 //获取表单属性参数值 String value = https://www.it610.com/article/fileItem.getString("UTF-8"); System.out.println(name + " " + value); } else {//拿到上传文件的MIME类型 String mimeType = super.getServletContext().getMimeType(fileItem.getName()); System.out.println(mimeType); //上传文件的拓展名字 String extension = FilenameUtils.getExtension(fileItem.getName()); String[] allowed = ALLOWED_IMAG_TYPE.split("; "); if (!Arrays.asList(allowed).contains(extension)){ //图片格式不在允许和格式之内 req.setAttribute("errorMeg","请上传图片文件"); req.getRequestDispatcher("/index.jsp").forward(req,resp); //结束方法 return ; } //文件控件 String fileNameUUID = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName()); String realPath = req.getServletContext().getRealPath("/headImages"); System.out.println("文件路径为:" + realPath + "\\" + fileNameUUID); System.out.println(realPath + "\\" + fileNameUUID); fileItem.write(new File(realPath, fileNameUUID)); System.out.println(req.getServletContext().getContextPath()); path = "/headImages/" + fileNameUUID; System.out.println(path); fileItem.getName(); } } } catch (Exception e) { e.printStackTrace(); }req.getSession().setAttribute("path", path); req.getRequestDispatcher("success.jsp").forward(req, resp); return; } }

抽取FileUtils工具类
抽取异常
package cn.icanci.Exception; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.Exception * @Date: Created in 2020/2/8 10:51 * @ClassAction: 业务逻辑异常 */ public class LogicException extends RuntimeException { /** * 构造器 * @param message 异常信息 * @param cause 异常的根本原因 */ public LogicException(String message, Throwable cause) { super(message, cause); }public LogicException(String message) { super(message); } }

文件上传工具类
package cn.icanci.utils; import cn.icanci.Exception.LogicException; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.utils * @Date: Created in 2020/2/8 10:48 * @ClassAction: 文件上传的约束 */ public class FileUtil {/** * 允许接收的图片类型 */ private static final String ALLOWED_IMAG_TYPE = "png; gif; jpg; jpeg"; public static void upload(HttpServletRequest req) throws ServletException, IOException { //解析请求 String path = null; boolean multipartContent = ServletFileUpload.isMultipartContent(req); if (!multipartContent) { return; }try { //1.创建File表单的封装 DiskFileItemFactory factory = new DiskFileItemFactory(); //创建文件上传处理器 //设置缓存大小 默认大小是 10240字节 也就是10kb factory.setSizeThreshold(20 * 1024); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //3.解析请求 List fileItems = servletFileUpload.parseRequest(req); System.out.println(fileItems.size()); //4.迭代每个item for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { // 普通表单控件 //获取表单属性参数值 String value = https://www.it610.com/article/fileItem.getString("UTF-8"); System.out.println(name + " " + value); } else {//拿到上传文件的MIME类型 String mimeType = req.getServletContext().getMimeType(fileItem.getName()); System.out.println(mimeType); //上传文件的拓展名字 String extension = FilenameUtils.getExtension(fileItem.getName()); String[] allowed = ALLOWED_IMAG_TYPE.split("; "); if (!Arrays.asList(allowed).contains(extension)) { //图片格式不在允许和格式之内 throw new LogicException("请上传图片文件"); } //文件控件 String fileNameUUID = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName()); String realPath = req.getServletContext().getRealPath("/headImages"); System.out.println("文件路径为:" + realPath + "\\" + fileNameUUID); System.out.println(realPath + "\\" + fileNameUUID); fileItem.write(new File(realPath, fileNameUUID)); System.out.println(req.getServletContext().getContextPath()); path = "/headImages/" + fileNameUUID; System.out.println(path); fileItem.getName(); } } } catch (LogicException e) { //继续抛出异常 给调用者 throw e; }catch (Exception ex){ ex.printStackTrace(); }} }

package cn.icanci.web; import java.io.File; import cn.icanci.Exception.LogicException; import cn.icanci.utils.FileUtil; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; 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; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.UUID; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web * @Date: Created in 2020/2/7 21:40 * @ClassAction: */ @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws LogicException, ServletException, IOException { try { FileUtil.upload(req); } catch (ServletException e) { e.printStackTrace(); } catch (LogicException e) { e.printStackTrace(); System.out.println(e.getMessage()); //输出给界面 String message = e.getMessage(); } } }

4.设置文件上传的大小
1.单个文件
//设置文件上传大小的限制 1024<<11 2M
servletFileUpload.setSizeMax(1024 << 11);
2.总数据大小
servletFileUpload.setSizeMax(1024 << 10 * 3);
5.使用Map封装数据然后给JavaBean对象
package cn.icanci.utils; import cn.icanci.Exception.LogicException; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.utils * @Date: Created in 2020/2/8 10:48 * @ClassAction: 文件上传的约束 */ public class FileUtil {/** * 允许接收的图片类型 */ private static final String ALLOWED_IMAG_TYPE = "png; gif; jpg; jpeg"; public static void upload(HttpServletRequest req, Map map) throws ServletException, IOException { //解析请求 String path = null; boolean multipartContent = ServletFileUpload.isMultipartContent(req); if (!multipartContent) { return; }try { //1.创建File表单的封装 DiskFileItemFactory factory = new DiskFileItemFactory(); //创建文件上传处理器 //设置缓存大小 默认大小是 10240字节 也就是10kb factory.setSizeThreshold(20 * 1024); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //设置文件上传大小的限制 1024<<11 2M servletFileUpload.setSizeMax(1024 << 11); //3.解析请求 List fileItems = servletFileUpload.parseRequest(req); System.out.println(fileItems.size()); //4.迭代每个item for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { // 普通表单控件 //获取表单属性参数值 String value = https://www.it610.com/article/fileItem.getString("UTF-8"); System.out.println(name + " " + value); map.put(name,value); } else {//拿到上传文件的MIME类型 String mimeType = req.getServletContext().getMimeType(fileItem.getName()); System.out.println(mimeType); //上传文件的拓展名字 String extension = FilenameUtils.getExtension(fileItem.getName()); String[] allowed = ALLOWED_IMAG_TYPE.split("; "); if (!Arrays.asList(allowed).contains(extension)) { //图片格式不在允许和格式之内 throw new LogicException("请上传图片文件"); } //文件控件 String fileNameUUID = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName()); String realPath = req.getServletContext().getRealPath("/headImages"); System.out.println("文件路径为:" + realPath + "\\" + fileNameUUID); System.out.println(realPath + "\\" + fileNameUUID); fileItem.write(new File(realPath, fileNameUUID)); System.out.println(req.getServletContext().getContextPath()); path = "/headImages/" + fileNameUUID; System.out.println(path); fileItem.getName(); map.put(name,"/headImages/" + fileNameUUID); } } } catch (LogicException e) { //继续抛出异常 给调用者 throw e; } catch (Exception ex) { ex.printStackTrace(); }} }

package cn.icanci.web; import java.io.File; import cn.icanci.Exception.LogicException; import cn.icanci.domain.Upload; import cn.icanci.utils.FileUtil; import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; 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; import java.util.HashMap; import java.util.Map; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web * @Date: Created in 2020/2/7 21:40 * @ClassAction: */ @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws LogicException, ServletException, IOException { try { Upload upload = new Upload(); //封装普通表单的数据 Map map = new HashMap<>(); FileUtil.upload(req, map); System.out.println(map); upload.setUsername(map.get("username")); upload.setPassword(map.get("password")); upload.setHeadImg(map.get("headImg")); System.out.println(upload); } catch (ServletException e) { e.printStackTrace(); } catch (LogicException e) { e.printStackTrace(); System.out.println(e.getMessage()); //输出给界面 String message = e.getMessage(); } catch (Exception ex) { ex.printStackTrace(); } } }

5.文件下载
- 锐客网 下载资源列表
four
第四季javaweb笔记
shiro资料笔记与核心单词

package cn.icanci.web; import org.apache.taglibs.standard.tag.common.core.UrlSupport; import java.net.URLEncoder; import java.nio.file.Paths; 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; import java.nio.file.Files; /** * @Author: icanci * @ProjectName: javaweb * @PackageName: cn.icanci.web * @Date: Created in 2020/2/8 11:27 * @ClassAction: */ @WebServlet("/download") public class FiledownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.权限检查 //2.获取被下载的资源文件名称 String fileName = req.getParameter("fileName"); System.out.println(fileName); //如果乱码,则需要更改 //String s = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); //3.从服务器找到被下载的资源的绝对路径 String realPath = req.getServletContext().getRealPath("/WEB-INF/download/" + fileName); //============= System.out.println(req.getHeader("User-Agent")); //设置编码 if (req.getHeader("User-Agent").contains("MSIE") ||req.getHeader("User-Agent").contains("AppleWebKit")) { //IE fileName = URLEncoder.encode(fileName, "UTF-8"); } else { //非 ie fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); }//1.应该设置下载文件的建议名称 resp.setHeader("Content-Disposition", "attachment; filename=" + fileName); //2.不要直接打开文件 ,建立路径applicatoin/octet-stream resp.setContentType("application/zip"); //============= //4.把磁盘的文件 --> 程序中 --> 浏览器 拷贝操作 Files.copy(Paths.get(realPath), resp.getOutputStream()); } }

6.国际化 可以参考此博客 @深入学习Java国际化

    推荐阅读