Getting hostname of the client that is calling my

2019-09-02 04:46发布

问题:

I have developed my rest service in JAX-RS Jersey. I have deployed in the Tomcat 7.0. Now I am exposing my web service URL to third party client. I want to put validation mechanism that includes getting host name i.e. the client host name that is using my service. I would like to match with our database entered host name. How to get the host name of the client?

Here is my web.xml:

<servlet>
    <servlet-name>ServletAdaptor</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletAdaptor</servlet-name>
        <url-pattern>/intellixservices/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>secureRESTFilter</filter-name>
        <filter-class>com.astroved.intellix.security.SecurityFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>secureRESTFilter</filter-name>
        <url-pattern>/intellixservices/*</url-pattern>
    </filter-mapping>

Now I am creating a SecurityFilter class implementing Filter. inside doFilter() method -

@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpRes = (HttpServletResponse)res;
    String url = "http://localhost:8888/IntellixWebApi/intellixservices/dnareport";
    System.out.println("In security filter");
    req.getRequestDispatcher(url).forward(req, res);    

    chain.doFilter(httpReq, httpRes);
}

But it is not forwarding to the next URL. In Resource class, it is returning xml/json type.

回答1:

Have you considered using a filter ? not sure if this will be a good design, but you can get the values in the doFilter method using request.getRemoteHost() request.getRemoteAddr() and do your validation edit: forgot about client behind proxy.. this Getting IP address of client link might help



标签: java rest jax-rs