java 程序内嵌WEB服务

1.使用tomcat嵌入式
链接:http://blog.csdn.net/tomyjohn/article/details/6450225
2.使用mina框架模拟:

启动方法:
start() {
    HttpRequestDecoder.defaultEncoding = "UTF-8";
    HttpResponseEncoder.defaultEncoding = "UTF-8";
    acceptor = new NioSocketAcceptor();
    acceptor.getFilterChain().addLast("protocolFilter",new ProtocolCodecFilter(new HttpServerProtocolCodecFactory()));
    acceptor.setHandler(new HttpServerHandler());
    acceptor.bind(new InetSocketAddress("0.0.0.0",port));
    SocketSessionConfig config = acceptor.getSessionConfig();  
    config.setReadBufferSize(1024*1024);//1M
    config.setIdleTime(IdleStatus.BOTH_IDLE,30*60*1000);//限制时间30分钟
}
public class HttpServerProtocolCodecFactory extends DemuxingProtocolCodecFactory {
    public HttpServerProtocolCodecFactory() {
        super.addMessageDecoder(HttpRequestDecoder.class);
        super.addMessageEncoder(HttpResponseMessage.class,HttpResponseEncoder.class);
    }
}  
public class HttpRequestDecoder extends MessageDecoderAdapter {
    @Override
    public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
        try {
            return messageComplete(in) ? MessageDecoderResult.OK : MessageDecoderResult.NEED_DATA;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return MessageDecoderResult.NOT_OK;
    }

    @Override
    public MessageDecoderResult decode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {
        HttpRequestMessage request = decodeBody(in);
        if (request == null) {
            return MessageDecoderResult.NEED_DATA;
        }
        String clientIP = ((InetSocketAddress)session.getRemoteAddress()).getAddress().getHostAddress();  
        request.setIp(clientIP);
        out.write(request);
        return MessageDecoderResult.OK;
    }
}
public class HttpResponseEncoder implements MessageEncoder<HttpResponseMessage> {
@Override
    public void encode(IoSession session, HttpResponseMessage msg , ProtocolEncoderOutput out) throws Exception {
    }
}
public class HttpServerHandler extends IoHandlerAdapter{
    public void messageReceived(IoSession session, Object message) {  
         HttpRequestMessage request = (HttpRequestMessage) message;
          HttpResponseMessage response = new HttpResponseMessage();
    }
}
public class HttpRequestMessage {
    /**
     * HTTP请求的主要属性及内容
     */
    private Map<String, String[]> headers = null;

    private String ip;

    public Map<String, String[]> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String[]> headers) {
        this.headers = headers;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    /**
     * 获取HTTP请求的Context信息
     */
    public String getContext() {
        String[] context = headers.get("Context");
        return context == null ? "" : context[0];
    }

    /**
     * 根据属性名称获得属性值数组第一个值,用于在url中传递的参数
     */
    public String getParameter(String name) {
        String[] param = headers.get("@".concat(name));
        return (param == null || param.length == 0) ? "" : param[0];
    }

    /**
     * 根据属性名称获得属性值,用于在url中传递的参数
     */
    public String[] getParameters(String name) {
        String[] param = headers.get("@".concat(name));
        return param == null ? new String[] {} : param;
    }

    public Map<String,String> getParameters() {
        Map<String,String> result = new HashMap<String, String>();
        for (String key : headers.keySet()){
            if (key.contains("@")){
                String[] temp = headers.get(key);
                key = key.substring(1,key.length());
                result.put(key,temp[0]);
            }
        }
        return result;
    }

    /**
     * 根据属性名称获得属性值,用于请求的特征参数
     */
    public String[] getHeader(String name) {
        return headers.get(name);
    }

    //public String getPostValue() {
    //  String[] param = headers.get("$value");
    //  return param == null ? "" : param[0];
    //}

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        for (Entry<String, String[]> e : headers.entrySet()) {
            str.append(e.getKey() + " : " + arrayToString(e.getValue(), ',') + "\n");
        }
        return str.toString();
    }

    /**
     * 静态方法,用来把一个字符串数组拼接成一个字符串
     * 
     * @param s要拼接的字符串数组
     * @param sep数据元素之间的烦恼歌负
     * @return 拼接成的字符串
     */
    public static String arrayToString(String[] s, char sep) {
        if (s == null || s.length == 0) {
            return "";
        }
        StringBuffer buf = new StringBuffer();
        if (s != null) {
            for (int i = 0; i < s.length; i++) {
                if (i > 0) {
                    buf.append(sep);
                }
                buf.append(s[i]);
            }
        }
        return buf.toString();
    }
}
public class HttpResponseMessage {
    /** HTTP response codes */
    public static final int HTTP_STATUS_SUCCESS = 200;

    public static final int HTTP_STATUS_NOT_FOUND = 404;

    /** Map<String, String> */
    private final Map<String, String> headers = new HashMap<String, String>();

    /** Storage for body of HTTP response. */
    private final ByteArrayOutputStream body = new ByteArrayOutputStream(1024);

    private int responseCode = HTTP_STATUS_NOT_FOUND;

    Map<String, Object> datas = new HashMap<String,Object>();

    public HttpResponseMessage() {
        headers.put("Server", "HttpServer (Mina 2.0)");
        headers.put("Cache-Control", "private");
        headers.put("Content-Type", "text/html; charset=UTF-8");
        headers.put("Connection", "keep-alive");
        headers.put("Keep-Alive", "200");
        headers.put("Date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));
        headers.put("Last-Modified", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date()));
        headers.put("Access-Control-Allow-Origin","*");
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setContentType(String contentType) {
        headers.put("Content-Type", contentType);
    }

    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    public int getResponseCode() {
        return this.responseCode;
    }

    public void appendBody(byte[] buffer, int start, int len) {
        try {
            body.write(buffer,start,len);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void appendBody(byte[] b) {
        try {
            body.write(b);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void appendBody(String s) {
        try {
            body.write(s.getBytes());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public IoBuffer getBody() {
        return IoBuffer.wrap(body.toByteArray());
    }

    public int getBodyLength() {
        return body.size();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值