如何将web.xml转换为@WebServlet?

时间:2018-04-26 16:49:59

标签: java-ee websphere servlet-filters weblogic12c servlet-3.1

我有一个带有servlet 3.1的Web应用程序,并且没有@WebFilter注释的servlet过滤器,并且工作正常。

我想用@WebServlet注释替换它,但是使用相同的旧过滤器而不创建新的过滤器类并在旧的过滤器类中使用@WebFilter。下面是我的web.xml文件。

<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  <display-name>Archetype Created Web Application</display-name>
    <filter>
        <display-name>User Auth Filter</display-name>
        <filter-name>UserAuthFilter</filter-name>
        <filter-class>com.example.UserAuthFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>checkUser</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>doValidate</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
   <filter-mapping>
        <filter-name>UserAuthFilter</filter-name>
        <url-pattern>/usercount</url-pattern>
    </filter-mapping>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Services</web-resource-name>
            <url-pattern>/usercount</url-pattern>
            <http-method>GET</http-method>
        </web-resource-collection>
    </security-constraint>
    <deny-uncovered-http-methods/>
</web-app>

我尝试用下面的servlet替换它。

package com.example;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet
@WebFilter(displayName = "User Auth Filter",
        filterName = "UserAuthFilter",
        value = "com.example.UserAuthFilter",
        asyncSupported = true,
        initParams = {
                @WebInitParam(name = "checkUser",value = "true"),
                @WebInitParam(name = "doValidate",value = "true")
        })
public class NotificationWebsocketServlet {
    public NotificationWebsocketServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
}

我没有找到过滤映射和安全约束的任何注释。

你可以帮我吗?

1 个答案:

答案 0 :(得分:0)

对于@WebFilter,您应该能够使用urlPatterns属性进行过滤器映射。此外,您应该能够使用@ServletSecurity注释作为安全约束。