zoukankan      html  css  js  c++  java
  • 轻量级的java HTTP Server——NanoHttpd

    NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。 
    github地址:https://github.com/NanoHttpd/nanohttpd。

    maven依赖:

    <dependency>
    <groupId>org.nanohttpd</groupId> <!-- <groupId>com.nanohttpd</groupId> for 2.1.0 and earlier -->
    <artifactId>nanohttpd</artifactId>
    <version>2.2.0</version>
    </dependency>

    官网demo:

    package com.example;
    
    import java.io.IOException;
    import java.util.Map;
    
    import fi.iki.elonen.NanoHTTPD;
    // NOTE: If you're using NanoHTTPD >= 3.0.0 the namespace is different,
    //       instead of the above import use the following:
    // import org.nanohttpd.NanoHTTPD;
    
    public class App extends NanoHTTPD {
    
        public App() throws IOException {
            super(8080);
            start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
            System.out.println("
    Running! Point your browsers to http://localhost:8080/ 
    ");
        }
    
        public static void main(String[] args) {
            try {
                new App();
            } catch (IOException ioe) {
                System.err.println("Couldn't start server:
    " + ioe);
            }
        }
    
        @Override
        public Response serve(IHTTPSession session) {
            String msg = "<html><body><h1>Hello server</h1>
    ";
            Map<String, String> parms = session.getParms();
            if (parms.get("username") == null) {
                msg += "<form action='?' method='get'>
      <p>Your name: <input type='text' name='username'></p>
    " + "</form>
    ";
            } else {
                msg += "<p>Hello, " + parms.get("username") + "!</p>";
            }
            return newFixedLengthResponse(msg + "</body></html>
    ");
        }
    }

    运行App,浏览器打开http://localhost:8080/ 即可看到效果。

    输入username,然后回车:

    这样一个简单的登录功能就完成了。

    问题: 
    如果form中指定action为post,你会发现后台session获取不到参数。 
    解决办法:

    session.parseBody(new HashMap());
    params = session.getParms();

    意思也就是,对于post请求,你需要先调用parseBody()方法,直接传一个简单的新构造的map就行了,然后再调用getParams()方法。

  • 相关阅读:
    RedissonConfProperty
    IdGenerator(雪花)
    Btrace和arthas地址
    SqlFilter
    AuthorityFilter
    111
    分布式数据库-杂记
    站点集群
    分布式精华文章
    高并发
  • 原文地址:https://www.cnblogs.com/huangjinyong/p/12792346.html
Copyright © 2011-2022 走看看