Servlet3.0入门使用

1       前提

1.1     JAEE,Web容器,开发工具

基于JDK6/JAVAEE6

Web容器:Tomcat7以上

Myeclipse 9.0(或者在8基础上自己扩展)

2       配置及使用

2.1     Web.xml

Servlet2.5的配置

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

                   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 

Servlet3.0的配置

<web-app version="3.0"

       xmlns="http://java.sun.com/xml/ns/javaee"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 

3       Servlet

3.1     第一个例子

通过在java类里面使用Annotation注解的方式来配置servlet的名称和urlPattern

这样就不需要再在web.xml里配置了

@WebServlet(name = "firstServlet", urlPatterns = { "/firstServlet",

              "/myDefaultServlet" })

// 可以指定多个映射

public class FirstServlet extends HttpServlet {

 

       private static final long serialVersionUID = 6531730293401271095L;

 

       @Override

       protected void doGet(HttpServletRequest req, HttpServletResponse resp)

                     throws ServletException, IOException {

              resp.getWriter().write("this is my first Servlet");

       }

}

3.2     Servlet几个常用Annotation讲解

位于javax.servlet.annotation包下

3.2.1  @WebServlet

Name:配置servlet的名称

Value/urlPatterns2个都可以指定serlvet-urlPattern,多个使用{}

loadOnStartupservletload-on-startup顺序

initParams:初始化参数

注意,必须使用@WebInitParam(name=”xxx”,value=”xxx”)

initParams = {@WebInitParam(name=”xxx”,value=”xxx”), @WebInitParam(name=”xxx”,value=”xxx”)}

asyncSupported:是否支持异步,默认为false

 

3.2.2  @WebInitParam

上面也用到了,只有2个属性namevalue

2种用法:

A、 嵌入到@WebServletinitParams参数里

B、 直接定义(可重复使用)

 

3.3.4.2 监听器例子

AsyncContext sc = request.startAsync(request, response);

              sc.addListener(new MySyncListener());

 

class MySyncListener implements AsyncListener {

 

       @Override

       public void onComplete(AsyncEvent arg0) throws IOException {

              System.out.println("syncContext is complete");

 

       }

 

       @Override

       public void onError(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

       @Override

       public void onStartAsync(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

       @Override

       public void onTimeout(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

}

3.3.4.3 动态注册Servlet

在代码里实现注册,目前只支持ServletContext容器启动的时候注册,不支持运行中注册

 

如下例子

//不注解,也不在web.xml中配置,而是通过动态注册的方式

public class DynamicServlet extends HttpServlet {

       public void doGet(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

 

              response.setContentType("text/html");

              PrintWriter out = response.getWriter();

              out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

              out.println("<HTML>");

              out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

              out.println("  <BODY>");

              out.print("    This is ");

              out.print(this.getClass());

              out.println(", using the GET method");

              out.println("  </BODY>");

              out.println("</HTML>");

              out.flush();

              out.close();

       }

 

}

 

在有ServletContext的地方就可以注册该Serlvet如下

@WebListener

public class MyListener2 implements ServletContextListener {

       @Override

       public void contextDestroyed(ServletContextEvent arg0) {

             

       }

 

       @Override

       public void contextInitialized(ServletContextEvent se) {

              System.out.println("servletContext init");

             

              //动态注册Servlet

              ServletRegistration sr = se.getServletContext().addServlet("DynamicServlet", "com.lxh.servlet.DynamicServlet");

              sr.addMapping("/DynamicServlet");

              sr.addMapping("/DynamicServlet2");//可增加多个mapping

             

       }

}

 

这样的好处假设给现有系统增加一个servlet我们只需要自己编写完后打成jar包放在现有系统下即可。对原有代码不需要做任何改动。

4       Listener

上面在Servlet就已经使用到了

4.1     注解@WebListener

Optional Element Summary

 java.lang.String

value
          Description of the listener

 

不需要参数,不需要在web.xml中配置了,如下代码,tomcat启动的时候将会捕捉到

@WebListener

public class MyListener2 implements ServletContextListener {

 

       @Override

       public void contextDestroyed(ServletContextEvent arg0) {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       public void contextInitialized(ServletContextEvent arg0) {

              System.out.println("servletContext init");

             

       }

 

}

 

5       Filter

5.1     注解@WebFilter

Optional Element Summary

 boolean

asyncSupported
          Declares whether the filter supports asynchronous operation mode.

 java.lang.String

description
          The description of the filter

 DispatcherType[]

dispatcherTypes
          The dispatcher types to which the filter applies

 java.lang.String

displayName
          The display name of the filter

 java.lang.String

filterName
          The name of the filter

 WebInitParam[]

initParams
          The init parameters of the filter

 java.lang.String

largeIcon
          The large-icon of the filter

 java.lang.String[]

servletNames
          The names of the servlets to which the filter applies.

 java.lang.String

smallIcon
          The small-icon of the filter

 java.lang.String[]

urlPatterns
          The URL patterns to which the filter applies

 java.lang.String[]

value
          The URL patterns to which the filter applies

 

5.2     例子

@WebFilter(filterName="myFilter",urlPatterns="/*")

public class MyFilter implements Filter {

 

       @Override

       public void destroy() {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       public void doFilter(ServletRequest arg0, ServletResponse arg1,

                     FilterChain arg2) throws IOException, ServletException {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       public void init(FilterConfig arg0) throws ServletException {

              // TODO Auto-generated method stub

             

       }

 

}

你可能感兴趣的:(java,servlet3.0)