当前位置: 代码迷 >> Ajax >> Tomcat运用SSL,AJAX代理中加入的SSL
  详细解决方案

Tomcat运用SSL,AJAX代理中加入的SSL

热度:737   发布时间:2012-10-07 17:28:51.0
Tomcat使用SSL,AJAX代理中加入的SSL

今天公司要求把Web版客户端全部加上https,这里记录一下实现过程:

?

1.添加KeyPair:

在命令行模式下切换到目录%TOMCAT_HOME%,使用jdk的keytool工具,

keytool -genkey -alias tomcat -keyalg RSA -keypass password -storepass password -keystore name.keystore -validity 3600

其中-validity 3600是过期时间,单位是天,默认是90天

?

2.将证书导入的JDK的证书信任库中:

keytool -export -trustcacerts -alias tomcat -file server.cer -keystore server.keystore -storepass password
keytool -import -trustcacerts -alias tomcat -file server.cer -keystore %JAVA_HOME%/jre/lib/security/cacerts -storepass password

这里注意tomcat使用的是哪个jre

如果本来目录中的cacerts存在,会报个错,把原来的cacerts备份一下,换个名字就可以了

?

3.配置tomcat https端口:
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"??
??? ??? maxThreads="150" scheme="https"
??? ??? secure="true" clientAuth="false" keystoreFile="d:\elitecrm.cer"
??? ??? keystorePass="letmein" sslProtocol="TLS" />

4.如果有需要,可以再配置压缩
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"??
??? ??? maxThreads="150" scheme="https"
??? ??? secure="true" clientAuth="false" keystoreFile="d:\elite.keystore"
??? ??? keystorePass="letmein" sslProtocol="TLS" compression="on"
??????? compressionMinSize="2048"
??????? noCompressionUserAgents="gozilla, traviata"
??????? compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain"/>

compression设为on打开压缩
compressionMinSize为启用压缩的阀值,设置这个值要综合考虑压缩的代价和网络传输代价的平衡值。
noCompressionUserAgents设置对于何种类型的浏览器不启用压缩
compressableMimeType设置对于哪些数据类型启用压缩,对于我们的客户端,text/html和text/xml要启用。

?

这样就可以用https协议8443端口访问之前的url,但是如果要用java.net.URL类来访问https的内容,还需要修改部分代码:

下面是一个用java.net.URL类来做ajax跨域代理的工具类,其中使用了模拟的post请求,并且配置了HttpsCertificates

其中配置SSL的信任证书这块是网上找到的,具体的作用还不是完全明白,不过这样以前的应用就又能正常使用了。

?

package com.elite.servlet;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CrossDomainProxyServlet extends HttpServlet{

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		postService(request,response);
	}
	
	public void postService(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String url = null; 
		PrintWriter out=response.getWriter();   
		   Map<String, String> req_map = new HashMap<String, String>();  
		   Enumeration<?> _enum = request.getParameterNames();  
		   while (_enum.hasMoreElements()) {  
		       String paramName = (String) _enum.nextElement();  
		       String paramValue = request.getParameter(paramName);  
		       req_map.put(paramName, paramValue);  
		   }  
		   if (!req_map.isEmpty()) {
		       url = req_map.remove("url");
		       System.out.println("url:"+url);
		   }
		   StringBuffer url_sbf = new StringBuffer();
		   String postData="";
		   if ((url != null) && (url.length() > 0)) { 
		       if (!req_map.isEmpty()) {  
		           for (Map.Entry<String, String> entry : req_map.entrySet()) {//generate parameters  
		               String _par_key = entry.getKey();  
		               String _par_value = entry.getValue();
		               System.out.println(_par_key+":"+_par_value);
		               _parvalue=URLEncoder.encode(_par_value,"utf-8");
		               if (_par_key != null && _par_key != "") {  
		                   if (url_sbf.indexOf("?") == -1)  
		                       url_sbf.append("?");  
		                   else  
		                       url_sbf.append("&");  
		                   url_sbf.append(_par_key).append("=").append(_par_value);  
		               }  
		           }
		           if(url_sbf.toString().startsWith("?"))
		        	   postData=url_sbf.substring(1);
		       }
		       
		       try {
		    	   trustAllHttpsCertificates();
				} catch (Exception e) {
					e.printStackTrace();
				}
	           HttpsURLConnection.setDefaultHostnameVerifier(hv);
	           
		       java.net.URL _url = new java.net.URL(url);  
		       HttpURLConnection  urlcon =(HttpURLConnection) _url.openConnection();  
		       urlcon.setRequestMethod("POST");
		       urlcon.setRequestProperty("Proxy-Connection", "Keep-Alive");
		       urlcon.setDoOutput(true);
		       OutputStream os = urlcon.getOutputStream();
		       DataOutputStream dos=new DataOutputStream(os);
		       dos.write(postData.getBytes());
		       dos.flush();
		       dos.close();
		       
		       java.io.InputStream is = urlcon.getInputStream();  
		       java.io.BufferedReader buffer = new java.io.BufferedReader(  
		               new java.io.InputStreamReader(is));  
		       StringBuffer bs = new StringBuffer();  
		       String lineStr = null;  
		       while ((lineStr = buffer.readLine()) != null) {  
		           //String stri = java.net.URLDecoder.decode(lineStr, "UTF-8");  
		           bs.append(lineStr).append("\n");  
		       }  
		       if (bs.toString().indexOf("<?xml version=") != -1) {//if XML file, for AJAX  
		           response.setContentType("text/xml; charset=UTF-8");  
		           response.setHeader("Cache-Control", "no-cache");  
		           out.println(bs.toString());  
		       } else  
		           out.println(bs.toString());  
		   }	
	}

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc =  javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    }
    public static class miTM implements javax.net.ssl.TrustManager,
	    javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
		    return null;
		}
		public boolean isServerTrusted(
		        java.security.cert.X509Certificate[] certs) {
		    return true;
		}
		public boolean isClientTrusted(
		        java.security.cert.X509Certificate[] certs) {
		    return true;
		}
		public void checkServerTrusted(
		        java.security.cert.X509Certificate[] certs, String authType) throws
		        java.security.cert.CertificateException {
		    return;
		}
		public void checkClientTrusted(
		        java.security.cert.X509Certificate[] certs, String authType) throws
		        java.security.cert.CertificateException {
		    return;
		}
	}
}

?

?

  相关解决方案