资料下载链接:Servlet学习PPT
资料放在电脑里面已经很长时间,每次打开看有160多张确实感觉挺多的,就丢在一旁了今天打开看一看个人感觉还是很有收获的,至少自己也对以前的基础知识复习了一遍。
HTTP – 举例
URL(Uniform Resource Locator,统一资源定位符):协议名+DNS名+请求的文件名
访问:http://www.itu.org/home/index.html
Http请求
浏览器代理用户发出Http请求
地址栏:
http://www.google.cn/
http://www.google.cn/search?complete=1&hl=zh-CN&q=google&meta=
表单提交
请求数据
Get方法与Post方法发送请求示例
Get方法示例:
GET /myapp/loginValidator.jsp?
UserName=tom&Password=123456 HTTP/1.1
Host:
[其它请求头]
BODY
EMPTY
Post方法示例:
POST /ibm-demo/loginValidator.jsp HTTP/1.1
Host
[其它请求头]
BODY
UserName=tom&Password=123456
Http与Servlet:Servlet为了实现基于Http协议的请求和响应,扩展出一个具体的子类HttpServlet,该类专门处理Http协议的请求
基于容器/Servlet的请求与响应过程
Servlet的配置文件
Web.xml是web应用的部署描述文件
Servlet类在web.xml中的配置
容器通过这个配置获取Servlet的信息,从而管理Servlet对象
示例:
WelcomeServlet
WelcomeServlet
WelcomeServlet
servlet.WelcomeServlet
WelcomeServlet
/WelcomeServlet
注意请求url与间的关系:
http://localhost:8080/myapp/WelcomeServlet
/*.action
http://localhost:8080/myapp/ a.action
http://localhost:8080/myapp/b.action
WelcomeServlet代码
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void init() throws ServletException {
System.out.println("WelcomeServlet Servlet init!");
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
System.out.println("WelcomeServlet Servlet destroy!");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
在JSP页面的表单中,通过调用Servlet:
请登录
在js中:
frmManage.submit();
相当于:
http://localhost:8080/myapp/WelcomeServlet?UserName=tom&Password=1123456
public void init(ServletConfig config)throws ServletException
public void service(ServletRequest req,ServletResponse res)
throws ServletException,
java.io.IOException
public void destroy()
public ServletConfig getServletConfig()
public java.lang.String getServletInfo()
抽象类,提供 servlet 接口的基本实现
public abstract class GenericServlet
implements Servlet, ServletConfig, java.io.Serializable
定义以下方法
public init()
public void log(String )
public void log(String,Throwable)
public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException,java.io.IOException
public ServletConfig getServletConfig();
public ServletContext getServletContext();
HttpServletRequest
该类是客户端http请求信息的抽象与封装
请求头相关信息
用户相关数据信息
其它
示例(显示当前所有请求的头名及头信息):
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()){
String headerName = (String) headerNames.nextElement();
out.println(headerName+"=");
out.println((request.getHeader(headerName));
out.println("
");
}
获得http请求头相关信息
CGI的等价物
例QUERY_STRING:getQueryString 方法
示例:
String[][] variables = {{“AUTH_TYPE”,request.getAuthType()},
{“CONTENT_LENGTH”,request.getContentLength(),…};
for(int i=0;i
示例:
http://localhost:8080/demo/login.jsp?name=tom&age=18
http request. getScheme()
Localhost request.getServerName()
request.getServerPort()
/demo request.getContextPath()
/login.jsp request.getServletPath();
/demo/login.jsp request.getRequesURI()
http://localhost:8080/demo/login.jsp request.getRequestURL()
name=tom&age=18 request.getQueryString()
获得用户提交数据
request.getParameter(“name”);//获得名为”name”的参数值
request.getParameterValues(“name”);//获得同名name的一组参数值,返回类型是String[]
request.getRequestDispatcher(String)-RequestDispatcher
请求分派?一个请求由多个web组件完成
ServletA,在ServletB,ServletC的帮助下,完成任务,由ServletA生成响应,include(包含)
ServletA->ServletB->ServletC,由ServletC生成响应,forward(转发)
在ServletAction的doGet(doPost)方法中:
Error error = new Error();
request.setAttribute(“error”,errorObject);
RequestDispatcher rd = request.getRequestDispatcher(“/fail.jsp”);
rd.forward(request,response);
则在fail.jsp中可以获得出错对象,从而显示出错信息:
<%
Error error = (Error) request.getAttribute(“error”);
out.println(“出错信息:”+error.getMessage());
%>
通过HttpServletResponse设定Http响应
首先设置响应头
response.setContentType("text/html; charset=GBK");
获得输出对象
文本:PrintWriter out = response.getWriter();
二进制:ServletOutputStream out = response.getOutPutStream()
:构造输出内容out.println(“…”)
提交输出: out.flush()
关闭out
构造响应示例
在doGet(doPost)方法中:
response.setContentType(“text/html; charset=GBK ”);//1设置响应头
PrintWriter out = response.getWriter();//2.获得输出对象
out.println(“”);//3.构造输出
out.println(" A Servlet ");
out.println(" ");
out.print(" Hello World! ");
out.println(", 欢迎你");
out.println(" ");
out.println("");
out.flush();//4.向容器提交输出
out.close();//5.关闭输出流
Http状态码:用于服务器将请求的状态传送给客户机
100-199: 临时状态码
200-299: 请求成功
300-399:重定向
400-499:客户端错误
500-599:服务器端错误
设置状态码的方法:
setStatus(int sc)
HttpServletResponse中静态变量定义Http状态码:
SC_OK 200
SC_MOVED_TEMPORARILY 302
SC_NOT_FOUND 404
SC_INTERNAL_SERVER_ERROR 500
设置状态码
response.setStatus(int sc)
发送错误消息
response.sendError(int,String)
例
response.sendError(HttpServletResponse.SC_NOT_FOUND,”你所要查找的网页不存在!”)
设置响应头:setHeader(“name”,value);
常见响应报头
Content-Type:定义响应文档的MIME(Multipurpose Internet Mail Extension)类型,由maintype/subtype组成
有专门的方法设置该响应头:setContentType
response.setContentType(“text/html; charset=GBK ”);//最常见形式
response.setContenType(“application/vnd.ms-excel”);//excel文档
response.setHeader("Content-Type",
"application/vnd.ms-excel; charset=GBK");
response.setContenType(“image/jpeg”);//图形图像
重定向
方法一:
设置状态码,如302
设置响应头:location
方法二:
sendRedirect
示例
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location","http://www.csdn.net");
response.sendRedirect("http://www.csdn.net");
告诉浏览器不要缓存页面
response.setHeader(“Cache-control”,”no-cache”);
response.setHeader(“pragma”,”no-cache”);
页面重新刷新
response.setIntHeader(“Refresh”,10);
response.setHeader(“Refresh”,”10 ,url=http://www.csdn.net”);