显示标签为“Web”的博文。显示所有博文
显示标签为“Web”的博文。显示所有博文

2009年4月14日星期二

为Tomcat添加https

其实这个主题网上一搜可以找到很多答案,但是我看过后总是觉得没有表达清楚。

这个过程其实很简单,步骤如下:
1.生成自己的证书
先运行命令:

%Java_home%\bin\keytool -genkey -alias tomcat -keyalg RSA
上面的命令默认生成一个.keystore文件在用户主目录下,也可以在后面加上-keystore filepath参数,由filepath来指定.keystore文件的位置。
运行命令时会需要输入很多信息,根据提示输入即可,需要注意的是密码部分,
上面的过程中最后需要你输入一个密码,要保证和最先输入的一样,否则无法使用,另外需要在Tomcat的配置文件server.xml中配置你的密码,这个见第二部分。
这样生成的证书是没有经过认证机构sign的,网上有提供免费试用的certificate的站点,如Rapidssl(http://www.rapidssl.com/index.htm),它可以认证你的证书,这样浏览器就不会弹出证书不可信的警告了。至于怎么让它认证自己的证书可以参照认证机构的向导。
2.为Tomcat添加https
需要将tomcat目录下的conf目录下的server.xml中的定义https连接的connector启用即可。如下:
<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
<!--
<Connector
port="8443" minProcessors="5" maxProcessors="75"
enableLookups="true" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"/>
-->
如果你的.keystore文件在不在你的用户主目录中,你需要加上属性
keystoreFile="yourpath/.keystore"
另外你还需要制定生成.keystore文件时所用的密码,如下:
keystorePass="yourpass"
所以配置好的<Connector>应该像这样:
<-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->

<Connector
port="8443" minProcessors="5" maxProcessors="75"
enableLookups="true" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
keystoreFile="yourpath/.keystore" keystorePass="yourpass"
clientAuth="false" sslProtocol="TLS"/>

OK,大功告成,启动Tomcat,就可以用https连接了,注意的是url格式变了,不再是http://localhost:8080/而是https://localhost:8443/,另外要指明的是使用https对客户端和服务器端来说都是透明的,浏览器和web服务器已经把加密解密的过程完成了,看起来和使用普通的http一样,只是url变了而已。
参考Tomcat的官方文档的SSL配置:http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html
--
Be yourself.

实现文件上传的Servlet

今天帮同学实现一个上传的servlet,本来以为很简单,最后做起来,才发现还是比较复杂的,虽然现在已经用惯了spring,但是基本的servlet也不能忘记。今天做这个收获颇多,特贴出来,以便以后使用。其实写的不是优雅,但也基本能完成任务。
对于文件上传有这么几点,首先是servlet接受到文件上传表单的数据后,并未提取出文件名等信息,需要自己分析。而且在文件数据前后都有一个添加上去的头和尾信息,需要自己去除。下面是我的代码:

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HandleFileServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String path = "D:\\";
        String filename = "";

        // System.out.println(getServletContext().getContextPath());
        System.out.println("content type:" + request.getContentType());
        System.out.println("file length:" + request.getContentLength());

        ServletInputStream is = request.getInputStream();
        int readLen = 0, conLen = request.getContentLength();
        byte[] b = new byte[1024];
        int len = 0;
        String terminator = "";
        // read the head infomation
        while ((len = is.readLine(b, 0, b.length)) != -1) {
            readLen += len;
            String str = new String(b,0,len);
            System.out.println("a line: " + "length:" + len + "data:" + str);
            int pos = -1;
            //got terminate string
            if (str.startsWith("---------------------------")) {
                terminator = str;
                terminator += "--";
                System.out.println(terminator);
            }
            //got filename
            if ((pos = str.indexOf("filename=\"")) != -1) {
                pos += "filename=\"".length();
                filename = str.substring(pos, str.lastIndexOf("\""));
                System.out.println("got filename:" + filename);
            }
            // quit read head data
            if (b[0] == '\r' && b[1] == '\n') {
                System.out.println("break from rn");
                break;
            }
        }
        if (filename.length() == 0)
            filename = "unknown_name.txt";
        File f = new File(path, filename);
        if (!f.createNewFile()) {
            System.out.println("Cannot create file");
        }
        FileOutputStream fos = new FileOutputStream(f);
        byte[] data = new byte[2048];
        int toReadLen = data.length;
        
        System.out.println("read length:"+readLen);
        System.out.println("content length:"+ conLen);
        System.out.println("conLen - terminator.length() " + (conLen - terminator.length()));
        
        if(readLen + data.length > ( conLen - terminator.length()))
        {
            toReadLen = conLen - terminator.length() - readLen-2;
        }
        while ((len = is.read(data, 0,toReadLen))!= 0 ) {
            readLen += len;
            //String tempStr = new String(data, 0, len);
            fos.write(data, 0, len);
            if(readLen + data.length > ( conLen - terminator.length()))
            {
                toReadLen = conLen - terminator.length() - readLen-2;
            }
        }
        fos.close();
        System.out.println("read after header:" + new String(data));

    }
}

html页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传测试</title>
</head>
<body>
<h1>选择一个文本文件上传:</h1>
<form action="servlet/upload" method="post"
            enctype="multipart/form-data">
            <input type="file" name="file" id="file1" />
             <input type="submit" value="上传" />
        </form>
</body>
</html>

--
Be yourself.