Servlet开发

来源:互联网 发布:网络摄像头扫描工具 编辑:程序博客网 时间:2024/05/29 13:21
 

一、Servlet介绍


Servlet简单的说就是一个Java程序,目的和Javabean差不多,为了使得JSP页面中代码简洁、清晰;

JavaBean不需要配置,只需要放在WEB-INF/classes中即可;

Servlet也是放在 WEB-INF/classes/中,并在web.xml中配置如下形式:


view plaincopy to clipboardprint?
  1. <servlet>  
  2. <servlet-name></servlet-name>  
  3. <servlet-class></servlet-class>  
  4. </servlet>  
  5. <servlet-mapping>  
  6. <servlet-name></servlet-name>  
  7. <url-pattern></url-pattern>  
  8. </servlet-mapping>  

如果需要设置配置信息,则需要形式如下:

view plaincopy to clipboardprint?
  1. <servlet>  
  2. <servlet-name></servlet-name>  
  3. <servlet-class></servlet-class>  
  4. <init-param>  
  5. <param-name></param-name>  
  6. <param-value></param-value>  
  7. </init-param>  
  8.   
  9. </servlet>  
  10. <servlet-mapping>  
  11. <servlet-name></servlet-name>  
  12. <url-pattern></url-pattern>  
  13. </servlet-mapping>  


注意:在url-pattern中,主目录为:"/",而不是"\"!

Servlet可以处理客户端传来的请求,即request,并且可以返回给客户端回应,即response,这个操作通过

(1)public void service(ServletRequest req,ServletResponse resp)throws ServletExeption,IOException{}

(2)public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletExeption,IOException{}

(3)public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletExeption,IOException{}

完成;

这里需要注意的是service的参数只是ServletRequest,而其他两个函数的参数是HttpServletRequest;

一般如果我们要自定义Servlet,则需要继承HttpServlet类,并覆盖相应的方法即可;


二、Servlet的结构


Servlet生命周期为:加载-->初始化--->服务--->销毁--->卸载;

加载:web容器加载Servlet,即创建一个对象;

初始化:调用servlet的init方法,为了完成一些预备动作;

服务:调用类service方法;

销毁:调用destroy()方法;当一个Servlet对象长时间不使用或web容器(tomcat)关闭时调用;

卸载:即退出;

继承HttpServlet后,可以覆写以下方法:

1.public void init()throws ServletException{}     //初始化Servlet,(1)当需要使用Servlet时调用;(2)如果在web.xml中配置,则可以web容器启动时自动加载;配置如下:

view plaincopy to clipboardprint?
  1. <serlvet>  
  2.     <serlvet-name></servlet-name>  
  3.     <servlet-class></servlet-class>  
  4.     <load-on-startup>1</load-on-startup>  
  5. </servlet>  

2.public void init(ServletConfig config)throws ServletExeption{} //初始化Servlet,可以得到配置信息

3.public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletExeption,IOException{} 当get方式传递,则调用此方法

4.public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletExeption,IOException{}当post方法传递,则调用此方法

5.public void service(ServletRequest req,ServletResponse resp)throws ServletExeption,IOException{}

6.public void destroy(){}   //销毁时调用

注意:

1.   当1,2同时出现时,2有较高优先级;

2.   当3或4和5同时出现时,5具有较高优先级;

3   .PrintWriter writer = resp.getWriter();可以获得输出流;

注意:writer输出时需要输出HTML结构;


三、Servlet常见问题


1.在init方法中,通过config.getInitParameter()方法取得配置信息;

2.req.getSession():取得Session对象;

3.super.getServletContext();取得application对象;因为GenericServlet中有getServletContext方法;

4.resp.getWriter()返回一个PrintWriter用以输出;

四、Servlet跳转


1.客户端跳转:resp.sendRedirect("1.jsp") ;    //类似于内置对象中的跳转;

2.服务器跳转:req.getRequestDispatcher("hello.jsp").forward(req,resp);能够跳转到hello.jsp中;     

注意:客户端跳转和服务器端跳转的区别;

六、过滤器(过滤Servlet)


Servlet的一种,因此也有init和destroy方法,还有一个服务方法,只是这里提供的服务是过滤;

实现javax.servlet.Filter接口

一般客户端发出请求后会交给Servlet;如果过滤器存在,则客户端发出的请求都是先交给过滤器,然后交给Servlet;

我们可以完成一些在执行Servlet之前必须要做的事,比如request.setCharacterEncoding("GBK");

必须实现以下方法:(因为Filter是一个接口,因此三个方法必须都实现)

1.public void init(FilterConfig config) throws ServletException{}   //   init方法在Web容器启动时就会调用;

2.public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain){}  // doFilter的参数是ServletRequest和ServletResponse而不是Http的;

3.public void destroy(){}

注意:

1.FilterChain含有public void doFilter(ServletRequest req,ServletResponse resp){}

一般代码形式如下:

public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain){

    chain.doFilter(req,resp);        //执行Servlet操作;

}

则这个函数会调用两次,一次是执行chain.doFilter之前,一次是执行chain.doFilter()之后;

写完过滤器后,我们必须要限制过滤器调用的范围,即域名为多少时会调用过滤器,我们在web.xml 中进行配置;

view plaincopy to clipboardprint?
  1. <filter>  
  2.     <filter-name></filter-name>  
  3.     <filter-class></filter-class>  
  4. </filter>  
  5. <filter-mapping>  
  6.     <filter-name></filter-name>  
  7.     <url-pattern></url-pattern>            <!--过滤器应用的范围,如果为/*,则如果域名设置形如/a 或/abc等都会调用过滤器-->  
  8. <!-- 比如url-pattern中为 /*  ,则对于根目录下的所有文件进行过滤-->  
  9. </filter-mapping>  


如果需要配置信息,则形式如下:

view plaincopy to clipboardprint?
  1. <filter>  
  2. <span style="white-space:pre">    </span><filter-name></filter-name>  
  3. <span style="white-space:pre">    </span><filter-class></filter-class>  
  4. <span style="white-space:pre">    </span><init-param>  
  5. <span style="white-space:pre">        </span><param-name></param-name>  
  6. <span style="white-space:pre">        </span><param-value></param-value>  
  7. <span style="white-space:pre">    </span></init-param>  
  8. </filter>  
  9. <filter-mapping>  
  10.     <filter-name></filter-name>  
  11.     <url-pattern></url-pattern>            <!--过滤器应用的范围,如果为/*,则如果域名设置形如/a 或/abc等都会调用过滤器-->  
  12. </filter-mapping>  


总结:需要自动执行的操作需要过滤器;

 七、监听器(监听Servlet)


监听器的作用类似于Swing中的监听器的作用,效果也差不多,即当某个事件发生时,就触发了某个设置好的监听器,但是这里触发的原因不同,这里是由于

(1)某个对象创建和销毁;

(2)设置和清除了内置对象的属性;

这里监听器能监听application、session、request对象。

写好监听器类后需要配置web.xml,形式如下:

view plaincopy to clipboardprint?
  1. <listener>  
  2.     <listener-class></listener-class>  
  3. </listener>  



1.application监听器:ServletContextListener


需要实现的方法:

(1)public void contextInitialized(ServletContextEvent e);       //在application创建时就调用

(2)public void contextDestroyed(ServletContextEvent e);        //当application销毁时调用

ServletContextEvent的getServletContext()方法可以取得application对象;


2.application属性监听器:ServletContextAttributeListener


需要实现的方法:

(1)public void attributeAdded(ServletContextAttributeEvent e);            //当调用application.setAttribute()时调用

(2)public void attributeRemoved(ServletContextAttributeEvent e);        //当调用applcaition.removeAttribute()时调用

(3)public void attributeReplaced(ServletContextAttributeEvent e);        //当调用两次application.setAttribute()赋予相同属性时调用

ServletContextAttributeEvent 的方法有:

(1)getName();  取得属性的名称;

(2)getValue();   取得属性的值;(注意:返回的是Object,必须转型)


3.session监听器:HttpSessionListener


需要实现的方法:

(1)public void sessionCreated(HttpSessionEvent e);                //当打开一个浏览器时,就会触发这个方法;

(2)public void sessionDestroyed(HttpSessionEvent e);            //当调用session.invalidate();或超时时调用

HttpSessionEvent的方法有getSession()取得HttpSession内置对象;  

销毁session:

(1)session.invalidate();

(2)超过超时时间,超时时间在web.xml中配置:

view plaincopy to clipboardprint?
  1. <session-config>  
  2.     <session-timeout>5</session-timeout>  <!-- 5分钟 -->  
  3. </session-config>  


4.session属性监听器:HttpSessionAttributeListener


需要实现的方法:

(1)public void attributeAdded(HttpSessionBindingEvent e);            //当调用session.setAttribute()时调用

(2)public void attributeRemoved(HttpSessionBindingEvent e);        //当调用session.removeAttribute()时调用

(3)public void attributeReplaced(HttpSessionBindingEvent e);         //当调用两次session.setAttribute()赋予相同属性时调用

HttpSessionBindingEvent 方法:

(1)getSession();

(2)getName();

(3)getValue();


5.session属性绑定监听器:HttpSessionBindingListener


需要实现的方法:

(1)public void valueBound(HttpSessionBindingEvent e);                    

(2)public void valueUnbound(HttpSessionBindingEvent e);

注意:这个监听器不用在web.xml中进行配置,而自动生效。

当实现这个接口的类被作为属性添加如内置对象时,就会触发valueBound;当删除这个属性时,则会触发valueUnbound;

比如

class A implements HttpSessionBindingListener{

    .....

    public void valueBound(HttpSessionBindingEvent e){}

    public void valueUnbound(HttpSessionBindingEvent e){}

}

当调用

session.setAttribute("info",new A())时即添加A类对象时,则会触发valueBound方法,当调用session.removeAttribute("info")时触发valueUnbound方法;


6.request监听器:ServletRequestListener


需要实现的方法:

(1)public void requestInitialized(ServletRequestEvent e);        //当请求一个网页时会调用

(2)public void requestDestroyed(ServletRequestEvent e);       //当请求结束时会调用

ServletRequestEvent 方法:

(1)getServletContext();取得application对象;

(2)getServletRequest();  取得request对象;


7.request属性监听器:ServletRequestAttributeListener


需要实现的方法:

(1)attributeAdded(ServletRequestAttributeEvent e);                            //当调用request.setAttribute()时调用

(2)attributeRemoved(ServletRequestAttributeEvent e);                     //当调用request.removeAttribute()时调用

(3)attributeReplaced(ServletRequestAttributeEvent e);                     //当调用两次request.setAttribute()赋予相同属性时调用

ServletRequestAttributeEvent 方法:

(1)getName();

(2)getValue();