JAVAEE课程(五)

第六次课

outline & assignment 1 review

outline

Listener

assignment 1 review

package io.github.medioqrity;

public class FindServlet {
    // absolute path vs relative path
    String wrongPath = "/WEB-INF/contact/a.txt"; // still absolute path
    String rightPath = context.getRealPath("/WEB-INF/contact/a.txt"); // transform to the real absolute path using relative path
    
    // file reading
    FileInputStream fis = new FileInputStream(rightPath):
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    BufferedReader br = new BufferedReader(isr);

    String temp = null;
    while ((temp = br.readLine()) != null) {
        
    }
}

缓存文件到内存中

publc static InputStream readFile(String file) {
    File f = new File(fileName);
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = BufferedInputStream(fis);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buffer = new byte[8 * 1024];
    int r = 0;
    while ((r = fis.read(buffer)) != -1) {
        baos.write(buffer, 0, r);
    }
    bis.close(); fis.close();
    buffer = baos.toByteArray();
    return new ByteArrayInputStream(buffer);
}

war文件

Web ARchive,网站归档文件。实际上就是一个压缩包,可以高效存储小文件,同时还可以检测是否有文件在传输过程中损坏。

使用getServletContext().getResourceAsStream("/WEB-INF/c.txt"),可以方便地读取资源。

ClassLoader也是很不错的。

分页

因为分页这件事情要跨越多次访问过程,所以应该使用Session来存储。

HttpSession session = request.getSession();
session.setAttribute("result", result);

Listener

Event Listener

Button b = new Button(); 
ActionEven
ActionListener

产生了一个事件之后会广播给所有听众,因为并不清楚哪个听众会处理哪个事件。

把生死看破,(咦)所以对象的创建和销毁都是重大事件

@WebListener
public class ApplicationInitializer implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        // something
    }
}

部署

<listener>
    <listener-class>ApplicationInitializer</listener-class>
</listener>

回去自己看其他listener。其实基本都不难。

JSP

java server page。用来解决类似于out.println("<td>" + data + "</td>")这种垃圾代码。

可以直接用%来分割java代码和html代码:

<h1><%= new java.util.Date() %></h1>

其实jsp等价于servlet。上述语句实际上被转换为:

out.write("<h1>");
out.println(new java.util.Date());

部署

<servlet>
    <servlet-name>a<servlet-name>
    <jsp-file>/WEB-INF/jsps/a.jsp</jsp-file>
</servlet>

jsp语法

<%@ page import="java.util.*", "java.io.*" 
    pageEncoding="utf-8"
    isErrorPage="true|false"
    errorPage="/error.jsp"
    session="true"
    %>

其中的isErrorPage表示当前页面是否是出错页面。

errorPage代表如果当前页面出错则应该访问的页面。

不必担心抛出异常。所有的语句都会被放在一个巨大的try catch块里。

剩下的自己学去。(jsp implicit object)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值