Web学习笔记 - 第010天

反射

通过反射可以设置类的私有属性
        Field f1 = Student.class.getDeclaredField("name");
        f1.setAccessible(true);
        f1.set(stu1, "Li zxc");
        Field f2 = Student.class.getDeclaredField("age");
        f2.setAccessible(true);
        f2.set(stu1, 20);
通过反射可以使用类的方法
        String methodName = "eat";
        Method m = Student.class.getDeclaredMethod(methodName);
        m.invoke(stu1);

文件上传

MySQL

文件类型为 longblob

jsp

如果要向服务器传文件,需要在form属性添加enctype="multipart/form-data"

<form action="add_emp.do" method="post" enctype="multipart/form-data">

input类型是file
比如说:照片

照片: <input type="file" name="photo">

Servlet

支持文件上传

在以前,处理文件上传是一个很痛苦的事情,大都借助于开源的上传组件,诸如commons fileupload等。
现在Servlet 3.0文件上传支持。以前的HTML端上传表单不用改变什么,还是一样的multipart/form-data MIME类型。
让Servlet支持上传,需要做两件事情
1.需要添加MultipartConfig注解

@MultipartConfig

2.从request对象中获取Part文件对象,并通过part的输入流将文件写入到buffer缓冲区

        Part part = req.getPart("photo");
        byte[] buffer = new byte[(int) part.getSize()];
        part.getInputStream().read(buffer);

字符串日期转换为Date类型

一般使用SimpleDateFormat 创建一个格式器来格式化字符串日期为Date类型,最好把这种方法封装到工具类里面

    private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";

    public static Date stringToDate(String pattern, String dateStr) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        try {
            return formatter.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static Date stringToDate(String dateStr) {
        return stringToDate(DEFAULT_DATE_PATTERN, dateStr);
    }

解决重复代码

当A类继承B类,有许多类似A类中都要实现相同的方法,如果要解决这些相同的重复代码,可以考虑建一个C类继承B类,把重复方法写在C类,属性设为protected,让A类继承C类,这样就不用每个类似A类的类都要写这种重复的方法。

例子:

public class BaseServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    protected DeptService getDeptService() {
        return (DeptService) ServiceFactory.factory(DeptService.class);
    }

    protected EmpService getEmpService() {
        return (EmpService) ServiceFactory.factory(EmpService.class);
    }
}

jsp显示图片

数据库图片存放的是longblob,byte数组

例子:根据员工编号拿到photo
1.第一步  html

<i*m*g src="show_photo.do?eno=${emp.id}" width="150px" height="200px">

如果支持多文件上传input添加属性multiple

  1. 第二步 实现dao层byte[] findPhotoById(int id)方法
    public byte[] findPhotoById(int id) {
        try (ResultSet rs = DbSessionFactory.openSession().executeQuery(
                "select photo from tb_emp where eno=?", id)) {
            if (rs.next()) {
                return rs.getBytes("photo");
            }
            return null;
        }
        catch (SQLException e) {
            e.printStackTrace();
            throw new DbException("处理结果集异常", e);
        }
    }   

3.第三步 实现biz业务层BufferedImage getEmpPhoto(int empId)方法,通过dao层findPhotoById()方法得到字节数组,然后通过ByteArrayInputStream流读取buffer到输入流,最后通过ImageIO类的read()方法传入输入流返回BufferedImage

    public BufferedImage getEmpPhoto(int empId) {
        byte[] buffer = empdao.findPhotoById(empId);
        if (buffer != null && buffer.length > 0) {
            try (InputStream in = new ByteArrayInputStream(buffer)) {
                return ImageIO.read(in);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

4.第四步 创建servlet,根据业务层方法得到缓冲图片,如果不为空,用ImageIO.write()输出

@WebServlet(urlPatterns="/show_photo.do", loadOnStartup=1)
public class GetEmpPhotoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest rep, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/jpeg");
        String enoStr = rep.getParameter("eno");
        if (enoStr != null) {
            int empId = Integer.parseInt(enoStr);
            BufferedImage photo = getEmpService().getEmpPhoto(empId);
            if (photo != null) {
                ImageIO.write(photo, "JPG", resp.getOutputStream());
            }
        }
    }
    
    private EmpService getEmpService() {
        return (EmpService) ServiceFactory.factory(EmpService.class);
    }
}

注意:

需要先设置输出流内容格式为图片格式 resp.setContentType("image/jpeg");

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,576评论 11 349
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,745评论 18 399
  • 这部分主要是与Java Web和Web Service相关的面试题。 96、阐述Servlet和CGI的区别? 答...
    杂货铺老板阅读 5,288评论 0 10
  • 一. Java基础部分.................................................
    wy_sure阅读 9,312评论 0 11
  • 涉及的aws云服务 Quicksight Quicksight 是AWS提供的一个高效商业智能数据分析工具。 今天...
    zhujp阅读 4,771评论 2 2

友情链接更多精彩内容