使用Http Server构建web应用

2019-06-17  本文已影响0人  奋斗live
一、输出信息到页面中
package http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class Http {


    public static void main(String[] arg) throws Exception{
        HttpServer server = HttpServer.create(new InetSocketAddress(8001),0);
        server.createContext("/index",new TestHandler());
        server.start();
    }

    static class TestHandler implements HttpHandler{

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "this is server";
            exchange.sendResponseHeaders(200, 0);
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

直接在浏览器上输入地址访问
http://127.0.0.1:8001/index

显示如下图


image.png
二、加载某个页面

加载某个页面,需要用到pom.xml
项目结构如下


image.png

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>netty_tcp_test</groupId>
    <artifactId>netty_tcp_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <netty.version>4.1.25.Final</netty.version>
        <os.detected.classifier>linux-x86_64</os.detected.classifier>
        <slf4j.version>1.7.25</slf4j.version>
        <java.version>1.8</java.version>
    </properties>

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${java.version}</encoding>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

Http.java

package http;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class Http {


    public static void main(String[] arg) throws Exception{
        HttpServer server = HttpServer.create(new InetSocketAddress(8002),0);
        server.createContext("/index.html",new TestHandler());
        server.start();
        System.out.println("启动成功");
    }

    static class TestHandler implements HttpHandler{

        private byte[] data;

        public TestHandler(){
            try(InputStream in = this.getClass().getResourceAsStream("/index.html")){
                this.data = new byte[in.available()];
                in.read(data);
            }catch (Exception e){
                throw  new RuntimeException(e);
            }
        }
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "this is server";
            exchange.getResponseHeaders().set("Content-Type", "text/html");
            exchange.sendResponseHeaders(200, 0);

            OutputStream os = exchange.getResponseBody();
            os.write(data);
            os.close();
        }
    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>teste</title>
</head>
<body>
<form onsubmit="return false;">
    <label>
        name
        <input type="text" value="yilian" id="userId" required="required" style="width: 100%">
    </label>
    <br/>
    <label>
        age<span style="color: red">*</span>
        <input type="text" value="age" id="hello" required="required" style="width: 100%">

    </label>
    <br/>
    <label>
        sex
        <input type="checkbox" value="sex" id="broadcast">
    </label>
    <br/>
    <br/>
    <input type="button" value="Send To Client" style="width: 100%" onclick="send()">
</form>
<script type="application/javascript">
    function $(id) {
        return document.getElementById(id);
    }

    function send() {
        var broadcast = $('broadcast').checked;
        var userId = $('userId').value;
        var content = $('hello').value;
        if (!userId && !broadcast) {
            alert("please input userId.");
            return false;
        }

        if (!content) {
            alert("please input content.");
            return false;
        }


        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/push', true);
        xhr.setRequestHeader("context-type", "application/json; charset=utf-8");
        xhr.onload = function (e) {
            if (this.status == 200) {
                alert(this.response)
            }
        };

        xhr.send(JSON.stringify({
            userId: userId,
            hello: content,
            broadcast: broadcast,
            condition: $('condition').value
        }));
    }
</script>
</body>
</html>

启动后如下访问,即可访问到对应的index.html页面


image.png
3、并发处理

对于TestHandler,可以在其中为每个新的请求新开一个线程进行处理,如下

  static class TestHandler implements HttpHandler{

        private byte[] data;

        public TestHandler(){
            try(InputStream in = this.getClass().getResourceAsStream("/index.html")){
                this.data = new byte[in.available()];
                in.read(data);
            }catch (Exception e){
                throw  new RuntimeException(e);
            }
        }
        @Override
        public void handle(HttpExchange exchange) throws IOException {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        exchange.getResponseHeaders().set("Content-Type", "text/html");
                        exchange.sendResponseHeaders(200, 0);

                        OutputStream os = exchange.getResponseBody();
                        os.write(data);
                        os.close();
                    }catch (IOException ie){
                        ie.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }
上一篇下一篇

猜你喜欢

热点阅读