JavaWeb学习篇之----Servlet(二)

2014-11-23 23:56:31 · 作者: · 浏览: 3
/post方式现在最常用,其他的方式被弃用了,所以我们在这里看一看到以do开头的方法其实是专门用来处理不同方式的请求的,但是我们之前说过所有的请求都会调用service方法,所以这时候我们可以看一下service中的源代码:


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 = req.getDateHeader(HEADER_IFMODSINCE);
		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);
	}
    }

其实看到源代码我们发现内部实现是很简单的,首先通过HttpRequest对象中的getMethod()方法获取客户机的请求方式,然后进行判断,执行对应的方法,所以我们在编写Http协议的Servlet的时候,只需要继承HttpServlet,实现其doGet/doPost方法即可,


下面我就是用MyEclipse来开发一个HttpServlet:

首先在MyEclipse中新建一个web应用,在应用中新建包名(web应用中的程序是必须要有包名的),在包下面新建一个Servlet(这里不要在新建一个java类了,不然我们还需要手动的继承HttpServlet,配置这个类的对外访问路径,步骤是很麻烦的),如果是新建一个Servlet的话,MyEclipse会自动帮我们将这个Servlet配置好对外访问路径,而且会自动的继承HttpServlet类。这样我们就可以在doGet和doPost方法中处理客户机的请求了。


上面的内容就介绍了Servlet的相关知识,下面就来开始介绍和Servlet相关的对象:

首先来看一下ServletConfig:

之前说过:Servlet接口中有一个getServletConfig()方法,而且在init(ServletConfig config)方法中也会回传一个ServletConfig对象,那么这个对象到底有什么用呢?见名知意,是Servlet的配置信息相关的,没错,他就是将ServletConfig的配置信息封装成对象,那么Servlet的配置信息是在哪里配置,配置后之后怎么读取,什么样的信息才需要进行配置呢?

其实有很多信息我们都是需要进行配置的,比如:这个Servlet所需要的连接数据库的信息,所使用的字符集码表,下面就来个例子吧:

首先看一下怎么配置,在webx.xml文件中找到对应的Servlet的 标签,在该标签中添加配置:

  
		
   
    ServletConfigDemo
   
		
   
    com.weijia.servletconfig.ServletConfigDemo
   
		
   
		
    
     
    
     url
     
    
     data
     
   
		
    
    
     username
     
    
     jiangwei
     
   
		
    
    
     password
     
    
     123456
     
   

  

这样我们就配置好了三个参数信息:数据库的url,用户名username,密码password,其实这信息是通过Map数据结构来进行存储的。

package com.weijia.servletconfig;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigDemo extends HttpServlet{
	private static final long serialVersionUID = 1L;
	//ServletConfig对象是封装init_param数据
	//可以查看struts中的案例中的配置
	//在实际开发中,有一些不适合在servlet程序中写死的数据,这些数据就可以通过配置方式配给servlet,
	//例如:servlet采用哪个码表,servlet连接那个数据库,servlet读取哪个配置文件等信息
	public ServletConfig config = null;
	
	@Override
	public void init(ServletConfig config){
		this.config = config;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		//这里可以直接使用:this.getServletConfig()方法直接返回一个ServletConfig,因为父类在调用init的时候已经初始化了,所以我们
		//在init方法中直接调用init方法即可
		
		//得到所有的初始化参数的key和value
		Enumeration
  
    e = config.getInitParameterNames();
		while(e.hasMoreElements()){
			String name = e.nextElement();
			System.out.println("name:"+name);
			System.out.println("value:"+config.getInitParameter(name));
			System.out.println("********************");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		doGet(req,resp);
	}

}

  

上面就是用来读取这些参数值的,我们可以看到这里我们是通过父类中的init方法来获取ServletConfig对象的,其实我们也可以通过this.getSer