如何在 java Servlet 过滤器中更改传入 URL 并将请求重定向到新 URL [重复]

Posted

技术标签:

【中文标题】如何在 java Servlet 过滤器中更改传入 URL 并将请求重定向到新 URL [重复]【英文标题】:How to change incoming URL in java Servlet filter and redirect request to the new URL [duplicate] 【发布时间】:2017-08-20 13:46:08 【问题描述】:

我创建了一个 webapp,我正在修改 url 中的参数以解密其中一个参数。解密后,我想将参数附加到新的 URL,以便获得预期的响应。我创建了一个收集输入的 html,而登录页面是一个 Java 页面,我正在拦截请求。我不希望请求转到登录页面,而是希望将其发送到新网址。

下面是我的过滤代码。

    package com.test.secondServlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Servlet Filter implementation class SecondFilter
 */
@WebFilter("/SecondFilter")
public class SecondFilter implements Filter 
    public String decryptedString;
    private static final String characterEncoding = "UTF-8";
    Properties prop = new Properties();
    InputStream input = null;
    public String globalKey;
    public String RedirectURL;
    public String DN;
    public String TYPE;
    public String NAME;
    public String NUMBER;
    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */

     @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException 
         //chain.doFilter(req, res);    
         HttpServletRequest request = (HttpServletRequest) req;
            //String requestURI = request.getRequestURI();
            //System.out.println(requestURI);
            String url = ((HttpServletRequest)request).getRequestURL().toString() +"?"+request.getQueryString();
            System.out.println(url);
            String queryString = ((HttpServletRequest)request).getQueryString();
            DN = ((HttpServletRequest) request).getParameter("DN");
            TYPE = ((HttpServletRequest) request).getParameter("TYPE");
            NAME = ((HttpServletRequest) request).getParameter("NAME");
            NUMBER = ((HttpServletRequest) request).getParameter("encryptedssn");
           // String key = ((HttpServletRequest) request).getParameter("aeskey");   

          //Code to load key from property file
            try 

                String filename = "Secretkey.properties";
                input = SecondFilter.class.getClassLoader().getResourceAsStream(filename);
                if(input==null)
                        System.out.println("Sorry, unable to find " + filename);
                    return;
                

                //load a properties file from class path, inside static method
                prop.load(input);
                //get the property value and print it out
                globalKey=prop.getProperty("Secretkey");
                System.out.println("Global Key : "+globalKey);

             catch (IOException ex) 
                ex.printStackTrace();
             
            //code ends 

            if (queryString!=null) 

                //decryptingssnhere
                    byte[] clearText;
                    try 
                        clearText = AesEncryption.decryptBase64EncodedWithManagedIV(NUMBER, globalKey);
                        decryptedString = new String(clearText,characterEncoding);
                        System.out.println("ClearText:" +decryptedString);
                     catch (Exception e) 
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    
                    // System.out.println("ClearText:" + new String(clearText,characterEncoding));

            //if(url.startsWith("/SSNdecrypt/SSNdecrypt"))
            System.out.println("queryString :"+queryString);
            System.out.println("DN : "+DN);
            System.out.println("TYPE : "+TYPE);
            System.out.println("NAME : "+NAME);
            System.out.println("S1/ NUMBER : "+NUMBER);
            //System.out.println("key : "+key);
            System.out.println("decrypted S1/ Number : "+decryptedString);
            //String toReplace = url.substring(38);
            System.out.println("input : "+input);
            //String Redirect = "SSNdecrypt?"+queryString.substring(0,13)+decryptedString;
            //System.out.println("redirect : "+Redirect);
            //String newURI = url.replace(queryString, Redirect);
            //System.out.println("new URL"+newURI);
            //String newURI = url.concat("?"+newquerystring);

            RedirectURL = "http://differentservername.com/contentexplorer/servlet/VipDms?";
            String Redirect =RedirectURL+"DN="+DN+"&TYPE="+TYPE+"&NAME="+NAME+"&-NUMBER="+decryptedString;          
            System.out.println("redircting new URL for DOCVIEW : "+Redirect);

            final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) 
                @Override
                public StringBuffer getRequestURL() 
                    final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
                    return new StringBuffer(Redirect);
                
            ;
            //chain.doFilter(wrapped, res);
            wrapped.getRequestDispatcher(Redirect).forward(wrapped, res);

             else 
                chain.doFilter(req, res);
            
            //SSNdecrypt/SSNdecrypt?encryptedssn=1234
            //res.getWriter().println(requestURI.toString());

        /**if (request instanceof HttpServletRequest) 
             String url = ((HttpServletRequest)request).getRequestURL().toString();
             String queryString = ((HttpServletRequest)request).getQueryString();
            **/
    

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException 
        // TODO Auto-generated method stub
    
    /**
     * @see Filter#destroy()
     */
    public void destroy() 
        // TODO Auto-generated method stub
    
     

我不想使用 urlrewriter 并且想在同一个过滤器中使用它。如何更改请求的 URL?

【问题讨论】:

您在代码中遇到的问题是什么? 我的请求 URL 是 http://localhost/SSNdecrypt/SSNdecrypt?DN=Docview_Test&TYPE=OL&NAME=OLDNEW_GUL&encryptedssn=FwMzepVbKyMDmEAJPB1gLdVwwWUtwgWmJZTBurg6Bh0%3D,我想将 URL 更改为 http://servername.com/contentexplorer/servlet/VipDms?DN=Docview_Test&TYPE=OL&NAME=GUL&-NUMBER=123456789。这里的 NUMBER 是来自请求 URL 的加密 SSN。我能够解密并且只需要更改 url 来发送请求。参数部分正在处理中。 试试这个 response.sendRedirect("your_url?NUMBER=" + URLEncoder.encode("yourdecryptString", "UTF-8")); 在我的 doFilter 方法中,我无法使用它。它给出了错误,因为未定义 servletResponse 的 sendredirect。 您是否将“response”替换为“res”? 【参考方案1】:

我正在使用HttpServletResponse resp = (HttpServletResponse) res; resp.sendRedirect(Redirect); 而不是转发wrapped.getRequestDispatcher(Redirect).forward(wrapped, res); 的请求。我没有使用请求 qrapper,而是使用 HTTP 响应包装器,并且能够从请求 url 修改完整的 URL。

【讨论】:

以上是关于如何在 java Servlet 过滤器中更改传入 URL 并将请求重定向到新 URL [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何检查 java servlet 过滤器中的 OPTIONS 方法调用?

如何过滤所有传入的请求,而不仅仅是映射到 servlet 的请求?

java web过滤器filter

Java - Tuckee URL Rewrite 过滤器如何更改请求的 url?

如何使用保留请求正文和响应正文的 servlet 过滤器记录请求和响应?

如何读取和复制 HTTP servlet 响应输出流内容以进行日志记录