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/urlPatterns:2个都可以指定serlvet-urlPattern,多个使用{}
loadOnStartup:servlet的load-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个属性name和value
2种用法:
A、嵌入到@WebServlet的initParams参数里
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 | |
| value |
不需要参数,不需要在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 | |
| asyncSupported |
| description |
dispatcherTypes | |
| displayName |
| filterName |
initParams | |
| largeIcon |
| servletNames |
| smallIcon |
| urlPatterns |
| value |
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
}
}
推荐阅读
代码之余轻松一下:当前热门-人民的名义