开发者可以用注解标记Servlet,Filter等,而不用在部署描述符web.xml文件中配置。随着注解的引入,部署描述符web.xml文件成为可选的。
现在创建Servlet相当简单:
UserServlet.java:
package com.tanlan.servlet3; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 处理用户信息的Servlet * @author tanlan [email protected] * @date 2009-08-09 */ @WebServlet(urlPatterns={"/UserServlet"}) public class UserServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName=request.getParameter("userName"); request.setAttribute("userName", userName); //处理逻辑... request.getRequestDispatcher("result.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
注解@WebServlet用于在Web应用程序中标记一个继承了HttpServlet的类为Servlet。其属性urlPatterns的值即是web.xml中的url-pattern。在地址栏输入如下的路径即可访问改Servlet:
http://localhost:8080/Javaee6web/UserServlet?userName=tanlan
创建过滤器如下
CharSetFilter.java:
package com.tanlan.servlet3; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; /** * 处理正文问题的Filter * @author tanlan [email protected] * @date 2009-08-09 */ @WebFilter(urlPatterns={"/*"}) public class CharSetFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() { } }
注解@WebFilter用于在Web应用程序中标记一个实现了Filter接口的类为过滤器。
为Servlet或Filter配置初始化参数分别如下:
@WebServlet(urlPatterns={"/UserServlet"},initParams={@WebInitParam(name="name",value="Servlet's tanlan")}) @WebFilter(urlPatterns={"/*"},initParams={@WebInitParam(name="name",value="Filter's tanlan")})
调用的代码分别为:
UserServlet.java:
public void init(ServletConfig config) throws ServletException { System.out.print(config.getInitParameter("name")); }
CharSetFilter.java:
public void init(FilterConfig filterConfig) throws ServletException { System.out.println(filterConfig.getInitParameter("name")); }