千峰JAVA逆战班Day49

Day49

*下载文件案例:就是使用IO传输数据
    private String resourceLocation = "D:\\Users\\t\\nginx-1.17.2\\html\\a.png";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = new FileInputStream(resourceLocation);
        String fileName = "图标.png";

        byte[] b = new byte[1024];
        int length = -1;
        //处理中文文件名下载时,浏览器显示乱码问题
        String cnFileName = URLEncoder.encode(fileName, "utf-8");
        //下载需要设置头信息
        resp.setHeader("Content-Disposition","attachment; filename="+cnFileName);

        ServletOutputStream os = resp.getOutputStream();
        while ((length = is.read(b)) != -1){
            os.write(b,0,length);
        }
        os.flush();
        os.close();
    }
*生命周期:从出生到死亡

​ I. init() 和 destr() 方法:初始化和销毁

//loadOnStartup后面的数字表示,当有多个servlet都有loadOnStartup时,该数字越小(必须是正数),启动的越早
@WebServlet(value = "/lifecycle",loadOnStartup = 1,name = "LifeCycle")
public class LifeCycle extends HttpServlet {
    //1.首次访问时,调用该方法,servlet的生命周期的开始,只会被调用一次
    //2.当加上了LoadOnStartup之后,那么在Tomcat启动的时候,就会调用该方法,则它的生命周期就开始了
    //作用:启动的时候,加载一些配置信息
    @Override
    public void init() throws ServletException {
        System.out.println("servlet init");
    }
    //servlet 销毁时,会调用该方法,该servlet的生命周期结束
    //作用:销毁该servlet
    @Override
    public void destroy() {
        System.out.println("servlet destroy");
    }

​ II. 使用init方法 加载配置文件。案例:从config.properties文件中读取信息(跟以前写DBUtil 类时差不多,但是获取IO流的方式不一样)

    //使用init的重载的方法
    @Override
    public void init(ServletConfig config) throws ServletException {
        /*
        * ServletContext是Servlet中一个非常重要的类
        * 1.可以获取应用的名字
        * 2.可以获取项目中所有文件的绝对路径
        * */
        ServletContext servletContext = config.getServletContext();
        System.out.println(servletContext.getContextPath());//获取应用的名字
        //获取config.properties的绝对路径
        String realPath = servletContext.getRealPath("WEB-INF\\classes\\config.properties");
        //然后就是使用IO流和properties对象读取里面的value值
    }
*servlet是单实例的,多线程并发访问时,会存在线程安全问题,需要使用同步代码块来保证线程安全。
*JSP:

​ I. JSP就是可以编写java代码的html页面

​ II. 案例:在页面显示20个hello,this is a welcome page

  <body>
    <%
      for (int i = 0; i < 20; i++){
    %>
      hello,this is a welcome page<br>
    <%
      }
    %>
  </body>

​ III. JSP的访问流程图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值