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" })

// 可以指定多个映射

publicclass FirstServlet extends HttpServlet {

 

       privatestaticfinallongserialVersionUID = 6531730293401271095L;

 

       @Override

       protectedvoid 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

       publicvoid onComplete(AsyncEvent arg0) throws IOException {

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

 

       }

 

       @Override

       publicvoid onError(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

       @Override

       publicvoid onStartAsync(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

       @Override

       publicvoid onTimeout(AsyncEvent arg0) throws IOException {

              // TODO Auto-generated method stub

 

       }

 

}

3.3.4.3动态注册Servlet

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

 

如下例子

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

publicclass DynamicServlet extends HttpServlet {

       publicvoid 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

publicclass MyListener2 implements ServletContextListener {

       @Override

       publicvoid contextDestroyed(ServletContextEvent arg0) {

             

       }

 

       @Override

       publicvoid 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

publicclass MyListener2 implements ServletContextListener {

 

       @Override

       publicvoid contextDestroyed(ServletContextEvent arg0) {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       publicvoid 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="/*")

publicclass MyFilter implements Filter {

 

       @Override

       publicvoid destroy() {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       publicvoid doFilter(ServletRequest arg0, ServletResponse arg1,

                     FilterChain arg2) throws IOException, ServletException {

              // TODO Auto-generated method stub

             

       }

 

       @Override

       publicvoid init(FilterConfig arg0) throws ServletException {

              // TODO Auto-generated method stub

             

       }

 

}

 

推荐阅读

 

代码之余轻松一下:当前热门-人民的名义

 

 

JAVAEE容器如何管理EntityManager和PersistenceContext

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值