“J2EE高级编程”笔记(三)

上节回顾和零碎知识

ServletHttpServlet的几个重要函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public interface Servlet {
init()
destroy()
getServletConfig()
service(ServletRequest req, ServletResponse res)
throws ServletException, IOException()
}
public interface HttpServlet {
public void service(HttpServletRequest req, HttpServletResonpse res)
throws IOException, ServletException {
String method = req.getMethod();
if("POST".equals(method)) {
doPost(req, res);
} else if("GET".equals(method)) {
doGet(req, res);
}
......
//若不指定ContentType,默认为 text/plain,即纯文本
res.setContentType("text/html");
......
}
}

有关MIME:点击查看

get默认缓存,post默认不缓存,但客户端和服务端都可以设置。

迭代器要好好复习一下。


今天所学的几个重要函数与接口

HttpServlet中的service, doGet, doPost, …
HttpServletRequest中的getParameter
HttpServletResponse中的getWriter, getOutputStream, setHeader, addCookie, getCookies
Servlet中的ServletConfig, ServletContext, HttpSession, RequestDispatcher

若下文未提到,需要翻阅文档自学。
以下这串代码没有实际的应用意义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.abc.servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
//可以不抛出异常,但最好还是加上
public void doGet(HttpServletResponse res,
HttpServletResponse res)
throws ServletException, IOException {
//全局变量、数据都放ServletContext
ServletConfig config = getServletConfig();
ServletContext application =
config.getServletContext();
//也可以这样直接获得ServletContext,更快捷
ServletContext sc = getServletContext();
//类似功能的函数:setHeader()
res.setContentType("text/html;charset=utf-8");
//getWriter()的返回类型为 PrintWriter
res.getWriter().println("hello world");
//传文件时用getOutputStream(),返回OutputStream
//读取客户端提交的参数
String wd = req.getParameter("wd");
//还有 getParameterNames(),获取参数名,返回迭代器
//参数值可能有很多(如多选题)abc=25&abc=&abc=123
String[] abc = req.getParameterValues("abc");
HttpSession session = res.getSession();
session的内容可以存在客户端的cookie,或者url重写
}
}