简体   繁体   中英

How to convert web.xml to @WebServlet?

I have a web application with servlet 3.1 and have servlet filter without @WebFilter annotation and its working fine.

I want to replace it with @WebServlet annotation but using same old filter without creating new filter class and using @WebFilter in the old filter class. Below is my web.xml file.

<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>

and I tried to replace it with below 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
    }
}

I did not find any annotation for filter-mapping and security-constraint.

Could you help me on this?

For the @WebFilter you should be able to use the urlPatterns attribute for the filter mapping. In addition you should be able to use @ServletSecurity annotation for your security-constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM