首页 > 代码库 > Servlet_简单实现

Servlet_简单实现

A simple sample:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException{
        PrintWriter out = resp.getWriter();
        out.println("Hello World!");
    }
}

如果一个类要成为servlet,那就需要继承HttpServlet,根据数据的发送方式为GET还是POST, 来选择doGet或doPost或全部。 doGet和doPost方法都有两个参数 HttpServletRequest和HttpServletResponse。HttpServletRequest提供访问信息的方法,它代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中。HttpServletResponse提供用于指定HTTP应答状态,应答头,还提供了向客户端发送数据的PrintWriter,可以通过println语句生成向客户端发送的页面。

doGet和doPost方法都要抛出ServletException和IOException两个异常。

doGet和doPost的区别

doGet transfer data from url, while doPost put data into a package before transfering, so doGet has better performance than doPost, doPost support more security then doGet. doGet has upper limit up to 4Kb on the data size it can transfer, while doPost has no limitation. doGet submit the request by appending the URL while doPost request is submitted via form. 

If we don‘t care about whether the request type is GET or POST, we can just write the implementation in doPost and let doGet call doPost, or verse vice. But if the specific request type is required, then we need to write implementation in the related method.

So in practice, we use GET to get something from the server, and POST to post (insert/update/delete) data or files to the server. GET is idempotent, the same operation applied multitime will return the same result. 

HttpServletRequest对象方法:(摘自http://blog.csdn.net/redarmy_chen/article/details/8157053)

  1. 获取客户端信息常用方法

    getRequestURL方法返回客户端发出请求时的完整URL。

    getRequestURI方法返回请求行中的资源名部分。

    getQueryString 方法返回请求行中的参数部分。

    getRemoteAddr方法返回发出请求的客户机的IP地址

    getRemoteHost方法返回发出请求的客户机的完整主机名

    getRemotePort方法返回客户机所使用的网络端口号

    getLocalAddr方法返回WEB服务器的IP地址。

    getLocalName方法返回WEB服务器的主机名

    getMethod得到客户机请求方式

  2. 获取客户端请求头信息

    getHead(name); getHeader(String name); getHeaderNames()

  3. 获得客户端请求参数

    getParameter(name):获取指定名称的参数值。这是最为常用的方法之一。

    getParameterValues(String name):获取指定名称参数的所有值数组。它适用于一个参数名对应多个值的情况。如页面表单中的复选框,多选列表提交的值。

    getParameterNames():返回一个包含请求消息中的所有参数名的Enumeration对象。通过遍历这个Enumeration对象,就可以获取请求消息中所有的参数名

    getParameterMap():返回一个保存了请求消息中的所有参数名和值的Map对象。Map对象的key是字符串类型的参数名,value是这个参数所对应的Object类型的值数组。

HttpServletResponse对象:(摘自http://blog.csdn.net/redarmy_chen/article/details/8157038)

产生响应状态行:

HTTP响应消息的响应状态行包括HTTP版本、状态代码和一条相关的提示信息:

    HTTP/1.1 200 OK

HttpServletResponse中定义了若干与状态码数值对应的常量,每个常量的名称以前缀SC(Status Code的简写)开头,然后是状态码在HTTP 1.1规范中所表示的状态信息的英文单词的组合,每个单词之间用下划线连接,且所有字母都大写。

    状态码404 对应的常量为HttpServletResponse.SC_NOT_FOUND 

setStatus方法用于设置HTTP响应消息的状态码,并生成响应状态行。

sendError方法用于发送表示错误信息的状态码(一般是404,找不到客户机所请求的资源)到客户端,并清除缓冲区中的内容。

构建响应消息头:

addHeader与setHeader方法

addIntHeader与setIntHeader方法

addDateHeader与setDateHeader方法

setContentLength方法

setContentType方法:用于设置Servlet输出内容的MIME类型,对于HTTP协议来说,就是设置Content-Type响应头字段的值。如“text/html;charset=UTF-8”

setCharacterEncoding方法:用于设置输出内容的MIME声明中的字符集编码,对HTTP协议来说,就是设置Content-Type头字段中的字符编码部分。

使用<meta>标签模拟响应消息头:

HTML语言中专门定义了<meta>标签的http-equiv属性来在HTML文档中模拟HTTP响应消息头,当浏览器读取到HTML文档中具有http-equiv属性的<meta>标签时,它会用与处理WEB服务器发送的响应消息头一样的方式来进行处理。 

getOutputStream和getWriter方法分别用于得到输出二进制数据、输出文本数据的ServletOuputStream、Printwriter对象。

getOutputStream和getWriter这两个方法互相排斥,调用了其中的任何一个方法后,就不能再调用另一方法。 

Servlet程序向ServletOutputStream或PrintWriter对象中写入的数据将被Servlet引擎从response里面获取,Servlet引擎将这些数据当作响应消息的正文,然后再与响应状态行和各响应头组合后输出到客户端。

Serlvet的service方法结束后,Servlet引擎将检查getWriter或getOutputStream方法返回的输出流对象是否已经调用过close方法,如果没有,Servlet引擎将调用close方法关闭该输出流对象。

Forward & Redirect

RequestDispatcher().forward(request, response)

HttpServletResponse‘s sendRedirect(String location)

the forward method will forward the request and response and pass to the path that was specified in getRequestDispatcher(String path). the response will noe be sent back to the client. this method is useful for communicating between server resources (servlet to servlet)

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
    RequestDispatcher rd = req.getRequestDispatcher("pathToResource");
    rd.forward(request,response);
}

sendRedirect method will tell the client that it will send a request to the specified path, the client will build a new request and submit it to the server. 

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
    resp.sendRedirect("pathToResource");
}

So, sendRedirect method should be used if need to transfer control to different domain or to achieve separate task. for other scenarios, forward is efficient to use since it is faster.


这一部分说明了在servlet中的一些基本知识,同时也是面试很可能会被问到的问题,现在整理出来希望自己能加深理解。

同时感谢http://blog.csdn.net/redarmy_chen/article/details/8157053,http://blog.csdn.net/redarmy_chen/article/details/8157038,从中也学到了一些东西。还需要继续提高自己。