1. 程式人生 > >spring boot 重寫requestServlet統一解密請求引數

spring boot 重寫requestServlet統一解密請求引數

在做專案過程中,經常需要對傳遞的引數進行加解密操作,如果把加解密放到每個方法中,會很麻煩,也不統一,因為每個方法都要這部分程式碼。

所以可以重寫request替換spring原來的request入口。達到引數在請求進入時就解密好,這樣既不破環spring本身的特徵,也能讓其他開發人員無感知的情況下完成加解密操作,

好處不言而喻。直接看看程式碼吧:

統一給返回值加密可以看另外一篇博文:http://blog.csdn.net/kokjuis/article/details/77371324

定義一個入口總類,重寫dodispatch方法

/*
 * 檔名:MyDispatcherServlet.java 版權:Copyright by www.huawei.com 描述: 修改人:kokJuis 修改時間:2017年8月24日
 * 跟蹤單號: 修改單號: 修改內容:
 */

package com.poly.rbl.plugin.request;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.DispatcherServlet;


/**
 * 重寫doDispatch方法,該方法是所有請求得總入口,把request轉到自定義的類裡面
 * 
 * @author gogym
 * @version 2017年8月30日
 * @see MyDispatcherServlet
 * @since
 */
public class MyDispatcherServlet extends DispatcherServlet
{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doDispatch(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        super.doDispatch(new MyRequest(request), response);
    }

}
重寫request(關鍵):
/*
 * 檔名:Myrequest.java 版權:Copyright by www.huawei.com 描述: 修改人:kokJuis 修改時間:2017年8月24日 跟蹤單號: 修改單號:
 * 修改內容:
 */

package com.poly.rbl.plugin.request;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;

import org.springframework.util.StringUtils;

import com.poly.rbl.utils.FastJsonUtils;
import com.poly.rbl.utils.RsaEncryptUtil;


/**
 * 自定義HttpServletRequest,統一處理請求資料解密問題
 * 
 * @author gogym
 * @version 2017年8月30日
 * @see MyRequest
 * @since
 */
public class MyRequest implements HttpServletRequest
{

    public HttpServletRequest originalRequest;

    public Map decryptParameterMap;

    public MyRequest(HttpServletRequest request)
    {

        originalRequest = request;

        System.out.println(originalRequest.getRemoteAddr() + "---URL:"
                           + originalRequest.getRequestURL() + "---URI:"
                           + originalRequest.getRequestURI());

        // 根據你自己的需要處理邏輯

        // 不解密
        // decryptParameterMap = new HashMap();
        // try
        // {
        // request.setCharacterEncoding("UTF-8");
        // }
        // catch (UnsupportedEncodingException e)
        // {
        // e.printStackTrace();
        // }
        //
        // Map<String, String[]> properties = request.getParameterMap();
        // Map<String, String> returnMap = new HashMap<String, String>();
        // Iterator<Entry<String, String[]>> entries = properties.entrySet().iterator();
        // Entry<String, String[]> entry;
        // String key = "";
        // String value = "";
        // while (entries.hasNext())
        // {
        // entry = (Entry<String, String[]>)entries.next();
        // key = (String)entry.getKey();
        // Object valueObj = entry.getValue();
        // if (null == valueObj)
        // {
        // value = "";
        // }
        // else if (valueObj instanceof String[])
        // {
        // String[] values = (String[])valueObj;
        // for (int i = 0; i < values.length; i++ )
        // {
        // value = values[i] + ",";
        // }
        // value = value.substring(0, value.length() - 1);
        // }
        // else
        // {
        // value = valueObj.toString();
        // }
        // returnMap.put(key, value);
        // }
        //
        // decryptParameterMap.putAll(returnMap);

        String data = request.getParameter("data");

        if (!StringUtils.isEmpty(data))
        {
            try
            {
                // 通過金鑰解密引數,並轉成Map
                String deStr = RsaEncryptUtil.decryptByPrivateKey(data);
                decryptParameterMap = FastJsonUtils.toBean(deStr, Map.class);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Object getAttribute(String s)
    {

        return originalRequest.getAttribute(s);

    }

    @Override
    public Enumeration getAttributeNames()
    {

        return originalRequest.getAttributeNames();

    }

    @Override
    public String getCharacterEncoding()
    {
        return originalRequest.getCharacterEncoding();
    }

    @Override
    public void setCharacterEncoding(String s)
        throws UnsupportedEncodingException
    {
        originalRequest.setCharacterEncoding(s);
    }

    @Override
    public int getContentLength()
    {
        return originalRequest.getContentLength();
    }

    @Override
    public long getContentLengthLong()
    {
        return originalRequest.getContentLengthLong();
    }

    @Override
    public String getContentType()
    {
        return originalRequest.getContentType();
    }

    @Override
    public ServletInputStream getInputStream()
        throws IOException
    {
        return originalRequest.getInputStream();
    }

    @Override
    public String getParameter(String s)
    {

        // 返回解密後的引數
        return String.valueOf(decryptParameterMap.get(s));
    }

    @Override
    public Enumeration getParameterNames()
    {
        // 這裡是通過實體類注入引數
        return Collections.enumeration(decryptParameterMap.keySet());
    }

    @Override
    public String[] getParameterValues(String s)
    {

        // 這裡是注入引數
        Object o = decryptParameterMap.get(s);
        if (o == null)
        {
            return null;
        }
        else
        {
            return new String[] {String.valueOf(o)};
        }

    }

    @Override
    public Map getParameterMap()
    {
        return originalRequest.getParameterMap();
    }

    @Override
    public String getProtocol()
    {
        return originalRequest.getProtocol();
    }

    @Override
    public String getScheme()
    {
        // TODO Auto-generated method stub
        return originalRequest.getScheme();
    }

    @Override
    public String getServerName()
    {
        // TODO Auto-generated method stub
        return originalRequest.getServerName();
    }

    @Override
    public int getServerPort()
    {
        // TODO Auto-generated method stub
        return originalRequest.getServerPort();
    }

    @Override
    public BufferedReader getReader()
        throws IOException
    {
        // TODO Auto-generated method stub
        return originalRequest.getReader();
    }

    @Override
    public String getRemoteAddr()
    {
        // TODO Auto-generated method stub
        return originalRequest.getRemoteAddr();
    }

    @Override
    public String getRemoteHost()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRemoteHost();

    }

    @Override
    public void setAttribute(String s, Object obj)
    {
        originalRequest.setAttribute(s, obj);
    }

    @Override
    public void removeAttribute(String s)
    {
        // TODO Auto-generated method stub
        originalRequest.removeAttribute(s);
    }

    @Override
    public Locale getLocale()
    {

        // TODO Auto-generated method stub
        return originalRequest.getLocale();

    }

    @Override
    public Enumeration<Locale> getLocales()
    {

        // TODO Auto-generated method stub
        return originalRequest.getLocales();

    }

    @Override
    public boolean isSecure()
    {

        // TODO Auto-generated method stub
        return originalRequest.isSecure();

    }

    @Override
    public RequestDispatcher getRequestDispatcher(String s)
    {

        // TODO Auto-generated method stub

        return originalRequest.getRequestDispatcher(s);

    }

    @Override
    public String getRealPath(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.getRealPath(s);

    }

    @Override
    public int getRemotePort()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRemotePort();

    }

    @Override
    public String getLocalName()
    {

        // TODO Auto-generated method stub
        return originalRequest.getLocalName();

    }

    @Override
    public String getLocalAddr()
    {

        // TODO Auto-generated method stub
        return originalRequest.getLocalAddr();

    }

    @Override
    public int getLocalPort()
    {

        // TODO Auto-generated method stub
        return originalRequest.getLocalPort();

    }

    @Override
    public ServletContext getServletContext()
    {

        // TODO Auto-generated method stub
        return originalRequest.getServletContext();

    }

    @Override
    public AsyncContext startAsync()
        throws IllegalStateException
    {

        // TODO Auto-generated method stub
        return originalRequest.startAsync();

    }

    @Override
    public AsyncContext startAsync(ServletRequest servletrequest, ServletResponse servletresponse)
        throws IllegalStateException
    {
        return originalRequest.startAsync(servletrequest, servletresponse);
    }

    @Override
    public boolean isAsyncStarted()
    {

        return originalRequest.isAsyncStarted();
    }

    @Override
    public boolean isAsyncSupported()
    {

        return originalRequest.isAsyncSupported();

    }

    @Override
    public AsyncContext getAsyncContext()
    {

        // TODO Auto-generated method stub
        return originalRequest.getAsyncContext();

    }

    @Override
    public DispatcherType getDispatcherType()
    {

        // TODO Auto-generated method stub
        return originalRequest.getDispatcherType();

    }

    @Override
    public boolean authenticate(HttpServletResponse httpservletresponse)
        throws IOException, ServletException
    {

        // TODO Auto-generated method stub
        return originalRequest.authenticate(httpservletresponse);

    }

    @Override
    public String changeSessionId()
    {

        // TODO Auto-generated method stub
        return originalRequest.changeSessionId();

    }

    @Override
    public String getAuthType()
    {

        // TODO Auto-generated method stub
        return originalRequest.getAuthType();

    }

    @Override
    public String getContextPath()
    {

        // TODO Auto-generated method stub
        return originalRequest.getContextPath();

    }

    @Override
    public Cookie[] getCookies()
    {

        // TODO Auto-generated method stub
        return originalRequest.getCookies();

    }

    @Override
    public long getDateHeader(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.getDateHeader(s);

    }

    @Override
    public String getHeader(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.getHeader(s);

    }

    @Override
    public Enumeration getHeaderNames()
    {

        // TODO Auto-generated method stub
        return originalRequest.getHeaderNames();

    }

    @Override
    public Enumeration getHeaders(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.getHeaders(s);

    }

    @Override
    public int getIntHeader(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.getIntHeader(s);

    }

    @Override
    public String getMethod()
    {

        return originalRequest.getMethod();
    }

    @Override
    public Part getPart(String s)
        throws IOException, ServletException
    {

        // TODO Auto-generated method stub
        return originalRequest.getPart(s);

    }

    @Override
    public Collection<Part> getParts()
        throws IOException, ServletException
    {

        // TODO Auto-generated method stub
        return originalRequest.getParts();

    }

    @Override
    public String getPathInfo()
    {

        // TODO Auto-generated method stub
        return originalRequest.getPathInfo();

    }

    @Override
    public String getPathTranslated()
    {

        // TODO Auto-generated method stub
        return originalRequest.getPathTranslated();

    }

    @Override
    public String getQueryString()
    {

        // TODO Auto-generated method stub
        return originalRequest.getQueryString();

    }

    @Override
    public String getRemoteUser()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRemoteUser();

    }

    @Override
    public String getRequestURI()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRequestURI();

    }

    @Override
    public StringBuffer getRequestURL()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRequestURL();

    }

    @Override
    public String getRequestedSessionId()
    {

        // TODO Auto-generated method stub
        return originalRequest.getRequestedSessionId();

    }

    @Override
    public String getServletPath()
    {

        // TODO Auto-generated method stub
        return originalRequest.getServletPath();

    }

    @Override
    public HttpSession getSession()
    {

        // TODO Auto-generated method stub
        return originalRequest.getSession();

    }

    @Override
    public HttpSession getSession(boolean flag)
    {

        // TODO Auto-generated method stub
        return originalRequest.getSession(flag);

    }

    @Override
    public Principal getUserPrincipal()
    {

        // TODO Auto-generated method stub
        return originalRequest.getUserPrincipal();

    }

    @Override
    public boolean isRequestedSessionIdFromCookie()
    {

        // TODO Auto-generated method stub
        return originalRequest.isRequestedSessionIdFromCookie();

    }

    @Override
    public boolean isRequestedSessionIdFromURL()
    {

        // TODO Auto-generated method stub
        return originalRequest.isRequestedSessionIdFromURL();

    }

    @Override
    public boolean isRequestedSessionIdFromUrl()
    {

        // TODO Auto-generated method stub
        return originalRequest.isRequestedSessionIdFromUrl();

    }

    @Override
    public boolean isRequestedSessionIdValid()
    {

        // TODO Auto-generated method stub
        return originalRequest.isRequestedSessionIdValid();

    }

    @Override
    public boolean isUserInRole(String s)
    {

        // TODO Auto-generated method stub
        return originalRequest.isUserInRole(s);

    }

    @Override
    public void login(String s, String s1)
        throws ServletException
    {

        originalRequest.login(s, s1);

    }

    @Override
    public void logout()
        throws ServletException
    {
        originalRequest.logout();
    }

    @Override
    public <T extends HttpUpgradeHandler> T upgrade(Class<T> class1)
        throws IOException, ServletException
    {
        return originalRequest.upgrade(class1);
    }

}

使用:在專案啟動類上註冊自定義的requestServlet。即可使用
 /**
     * Description: 註冊自定義的DispatcherServlet,用於解決加解密不破壞spring特徵
     * 
     * @return
     * @see
     */
     @Bean
     @Qualifier(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
     public DispatcherServlet dispatcherServlet()
     {
     return new MyDispatcherServlet();
     }