论坛首页 Java企业应用论坛

jdk6的httpserver小试

浏览 1840 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-28  

网上一堆例子,个人做一个,有下载,可以用模板的小例子。(Groovy)

 

尤其是在团队做demo时候使用,实时更新最先代码。

 

代码如下:

 

import com.sun.net.httpserver.*
import org.apache.commons.io.IOUtils
import org.lilystudio.smarty4j.*

class TplHandler implements HttpHandler {
    def engine = new Engine()
    final String contextDir = "../"
    final String encoding = "GBK"
    
    public TplHandler(){
        engine.setTemplatePath(contextDir)
        engine.setEncoding(encoding)
		engine.setDebug(true)
    }

    def out(Map map, String tpl, Writer writer) {
        def template = engine.getTemplate(tpl)
        def ctx = new Context()
        ctx.putAll(map)
        try {
			template.merge(ctx, writer)
        } catch (ex) {
            ex.printStackTrace()
        } finally {
			writer.flush()
			writer.close()
        }
    }   


    void handle(HttpExchange he) {
    //  def is = he.requestBody
    //  def reader = new BufferedReader(new InputStreamReader(is))
    //  List lines = reader.readLines() 

    //  String path = he.httpContext.path
        def uri = he.getRequestURI() 
        String tpl = uri.path

		// 如果是下载
		if(tpl.endsWith('download')){
			try {
				def ant = new AntBuilder()
				String zipFile = contextDir + '../demo.zip'
				ant.zip destfile : zipFile, basedir : contextDir

				he.responseHeaders.set("Content-Type", "application/zip")
				he.responseHeaders.set("Content-Disposition", "attachment;" + "filename=\"demo.zip\"")
				he.sendResponseHeaders(200, 0)

				def os = he.responseBody
				def downFile = new File(zipFile)
				os.write(IOUtils.toByteArray(new FileInputStream(downFile)))
				os.flush()
				os.close()
				return
			} catch (ex) {
				println ex.message
			}
		}

		he.responseHeaders.set("Content-Type", "html/plain;charset=" + encoding)
        he.sendResponseHeaders(200, 0)

		def os = he.responseBody
        try {
            if(tpl ==~ /.*(\.js|\.css)$/){
                def writer = new PrintWriter(new OutputStreamWriter(os, encoding))
                def file = new File(new File(contextDir), tpl)
                if(!file.exists())
                    writer.println 'File not exists : ' + tpl
                else
                    writer.println file.text

                writer.flush()
                writer.close()
            }else if(tpl ==~ /.*(?i)(\.gif|\.jpg|\.png)$/){
                def mat = tpl =~ /.*(?i)\.(gif|jpg|png)$/
                he.responseHeaders.set("Content-Type", "image/" + mat[0][1])

                def file = new File(new File(contextDir), tpl)
                def defaultFile = new File(new File(contextDir), 'images/calen_pic.gif')

                if(!file.exists())
                    os.write(IOUtils.toByteArray(new FileInputStream(defaultFile)))
                else
                    os.write(IOUtils.toByteArray(new FileInputStream(file)))

				os.flush()
				os.close()
            }else{
                Map params = [:]
                def writer = new PrintWriter(new OutputStreamWriter(os, encoding))
                out(params, tpl, writer)
            }
        } catch (ex) {
            def writer = new PrintWriter(new OutputStreamWriter(os, encoding))
            writer.println ex.message
			writer.flush()
			writer.close()
        } 
    }
}


HttpServer hs = HttpServer.create(new InetSocketAddress(8888), 0)
hs.createContext("/", new TplHandler())
hs.start()
println(" ---Start--- ")
println(hs.getAddress().getHostName())
println(hs.getAddress().getPort())
println(hs.getAddress().getAddress())
 
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics