使用HttpServlet开发web应用

 一、介绍HttpServlet

它是抽象类,全限定名为 javax.servlet.http.HttpServlet,它是GenericServlet的子类,专门用于创建使用HTTP协议的Servlet。

二、源码:

public abstract class HttpServlet extends GenericServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_post_not_supported");
        if (protocol.endsWith("1.1")) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        }
    }
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        String method = req.getMethod();

        if (method.equals(METHOD_GET)) {
            long lastModified = getLastModified(req);
            if (lastModified == -1) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                } catch (IllegalArgumentException iae) {
                    // Invalid date header - proceed as if none was set
                    ifModifiedSince = -1;
                }
                if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

        } else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsg, errArgs);

            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
        }
    }
    @Override
    public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException(lStrings.getString("http.non_http"));
        }
        service(request, response);
    }
}

通过分析HttpServlet的源代码片段,发现HttpServlet主要有两大功能,第一是根据用户请求方式的不同,定义相应的doXxx()方法处理用户请求。例如,与GET请求方式对应的doGet()方法,与POST方式对应的doPost()方法。第二是通过service()方法将HTTP请求和响应分别强转为HttpServletRequest和HttpServletResponse类型的对象。
需要注意的是,由于HttpServlet类在重载的service()方法中,为每一种HTTP请求方式都定义了对应的doXxx()方法,因此,当定义的类继承HttpServlet后,只需根据请求方式,重写对应的doXxx()方法即可,而不需要重写service()方法。 

三、动手体验

1、编写RequestMethodServlet类、编译、其class文件拷贝到tomcat

 	package cn.itcast.firstapp.servlet;
 	import java.io.*;
 	import javax.servlet.*;
 	import javax.servlet.http.*;
 	public class RequestMethodServlet extends HttpServlet {
 		public void doGet(HttpServletRequest request, 
 	                          HttpServletResponse response)
 				throws ServletException, IOException {
 			PrintWriter out = response.getWriter();
 			out.write("this is doGet method");
 			}
 		public void doPost(HttpServletRequest request, 
 	                            HttpServletResponse response)
 				throws ServletException, IOException {
 			PrintWriter out = response.getWriter();
 			out.write("this is doPost method");
 		}
 	}

2、在web.xml中配置RequestMethodServlet

	<servlet>
		<servlet-name>RequestMethodServlet</servlet-name>
		<servlet-class>cn.itcast.firstapp.servlet.RequestMethodServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>RequestMethodServlet</servlet-name>
		<url-pattern>/RequestMethodServlet</url-pattern>
	</servlet-mapping>

3、启动tomcat,浏览器中输入下面地址

http://localhost:8080/chapter03/RequestMethodServlet

  4、在如下位置创建form.html,体验post请求

内容如下:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
<title>体验post</title>
</head>
<body>
 	<body>
 	<form action="/chapter03/RequestMethodServlet" method="post">
 	         评论:     <br/>
 	   <textarea cols="60"  rows="5">
 	         评论时,请注意文明用语。
 	   </textarea > 
            <br /> <br />
 	   <input type="submit" value="提交" />
 	</form>
 	</body>
</html>

5、重新启动tomcat,访问如下地址

http://localhost:8080/chapter03/form.html

在下图中填写评论后提交 

就能看到post请求被处理了,如下: 

 四、如果对get和post的请求处理方式一样,怎么办?

可以在doPost方法中调用doGet方法或者相反,如下所示:

protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		out.print("the same way of the doGet and doPost method");
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值