Servlet3.0@WebServlet注解

2017-06-28  本文已影响390人  木水Code

Servlet3.0以后,可以不用再web.xml里面配置servlet,只需要加上@WebServlet注解就可以修改该servlet的属性了。

属性名 类型 描述
name String 指定Servlet 的 name 属性,等价于 <servlet-name>。如果没有显式指定,则该 Servlet 的取值即为类的全限定名。
value String[] 该属性等价于 urlPatterns 属性。两个属性不能同时使用。
urlPatterns String[] 指定一组 Servlet 的 URL 匹配模式。等价于<url-pattern>标签。
loadOnStartup int 指定 Servlet 的加载顺序,等价于 <load-on-startup>标签。
initParams WebInitParam[] 指定一组 Servlet 初始化参数,等价于<init-param>标签。
asyncSupported boolean 声明 Servlet 是否支持异步操作模式,等价于<async-supported> 标签。
description String 该 Servlet 的描述信息,等价于 <description>标签。
displayName String 该 Servlet 的显示名,通常配合工具使用,等价于 <display-name>标签。

代码中可以这样写:

@WebServlet(name = "ServletConfigTest", urlPatterns = "/ServletConfigTest", initParams = {
        @WebInitParam(name = "name", value = "GRR") })
public class ServletConfigTest extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private ServletConfig config;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {

    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = this.config.getInitParameter("name");
        response.getWriter().print(name);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

而web.xml文件中就不必在配置了:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
</web-app>
上一篇 下一篇

猜你喜欢

热点阅读