最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

netty 實(shí)現(xiàn)tomcat的示例代碼

 更新時間:2022年06月03日 17:55:45   作者:o_瓜田李下_o  
這篇文章主要介紹了netty 實(shí)現(xiàn)tomcat,主要包括自定義基礎(chǔ)類及netty 服務(wù)端的示例代碼詳解,通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

netty 實(shí)現(xiàn)tomcat

自定義基礎(chǔ)類

TomcatServlet

public abstract class TomcatServlet {
 
    public void service(ServletRequest request, ServletResponse response){
        if ("GET".equalsIgnoreCase(request.getMethod())){
            doGet(request, response);
        }else if ("POST".equalsIgnoreCase(request.getMethod())){
            doPost(request, response);
        }else {
            doResponse(response, "暫不支持其它請求方法");
        }
    }
 
    public abstract void doGet(ServletRequest request, ServletResponse response);
    public abstract void doPost(ServletRequest request, ServletResponse response);
 
    public void doResponse(ServletResponse response, String message){
        response.write(message);
    }
}          

ServletRequest

@Data
public class ServletRequest {
 
    private ChannelHandlerContext context;
    private HttpRequest httpRequest;
 
    public ServletRequest(){
 
    }
 
    public ServletRequest(ChannelHandlerContext context, HttpRequest httpRequest){
        this.context = context;
        this.httpRequest = httpRequest;
    }
 
    public String getMethod(){
        return httpRequest.method().name();
    }
 
    public HttpHeaders getHeaders(){
        return httpRequest.headers();
    }
 
    public Map<String, List<String>> getParameters(){
        QueryStringDecoder decoder = new QueryStringDecoder(httpRequest.uri());
        return decoder.parameters();
    }
 
    public Map<String,String> getPostFormParameters(){
        Map<String,String> params = new HashMap<>();
 
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(httpRequest);
        decoder.getBodyHttpDatas().forEach(item -> {
            if (item.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute){
                Attribute attribute = (Attribute) item;
 
                try {
                    String key = attribute.getName();
                    String value = attribute.getValue();
 
                    params.put(key, value);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
 
        return params;
    }
 
    public Map<String, Object> getPostBody(){
        ByteBuf content = ((FullHttpRequest)httpRequest).content();
        byte[] bytes = new byte[content.readableBytes()];
        content.readBytes(bytes);
 
        return JSON.parseObject(new String(bytes)).getInnerMap();
    }
}

ServletResponse

@Data
public class ServletResponse {
 
    private ChannelHandlerContext context;
    private HttpRequest httpRequest;
 
    public ServletResponse(){
 
    }
 
    public ServletResponse(ChannelHandlerContext context, HttpRequest httpRequest){
        this.context = context;
        this.httpRequest = httpRequest;
    }
 
    public void write(String message){
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set("Content-Type","application/json;charset=utf-8");
        response.content().writeCharSequence(message, StandardCharsets.UTF_8);
 
        context.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}

CustomServlet

ublic class CustomServlet extends TomcatServlet{
 
    @Override
    public void doGet(ServletRequest request, ServletResponse response) {
        System.out.println("處理GET請求");
        System.out.println("請求參數(shù)為:");
        request.getParameters().forEach((key,value) -> System.out.println(key + " ==> "+value));
 
        doResponse(response, "GET success");
    }
 
    @Override
    public void doPost(ServletRequest request, ServletResponse response) {
        if (request.getHeaders().get("Content-Type").contains("x-www-form-urlencoded")){
            System.out.println("處理POST Form請求");
            System.out.println("請求參數(shù)為:");
            request.getPostFormParameters().forEach((key,value) -> System.out.println(key + " ==> " + value));
 
            doResponse(response, "POST Form success");
        }else if (request.getHeaders().get("Content-Type").contains("application/json")){
            System.out.println("處理POST json請求");
            System.out.println("請求參數(shù)為:");
            request.getPostBody().forEach((key,value) -> System.out.println(key + " ==> " + value));
 
            doResponse(response, "POST json success");
        }else {
            doResponse(response, "error:暫不支持其它post請求方式");
        }
    }
}

ServletMapping:url與對應(yīng)的TomcatServlet映射

public class ServletMapping {
 
    private static final Map<String,TomcatServlet> urlServletMapping = new HashMap<>();
 
    public static Map<String, TomcatServlet> getUrlServletMapping(){
        return urlServletMapping;
    }
}

web.properties:使用properties存儲url與對應(yīng)的TomcatServet

servlet.url=/hello
servlet.className=com.example.demo.tomcat.servlet.CustomServlet

netty 服務(wù)端

CustomServerHandler

public class CustomServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
 
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {
        String uri = request.uri();
        String path = uri;
        if (uri.contains("?")){
            path = uri.substring(0,uri.indexOf("?"));
        }
 
        if (ServletMapping.getUrlServletMapping().containsKey(path)){
            ServletRequest servletRequest = new ServletRequest(channelHandlerContext, request);
            ServletResponse servletResponse = new ServletResponse(channelHandlerContext, request);
 
            ServletMapping.getUrlServletMapping().get(path).service(servletRequest, servletResponse);
        }else {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            response.content().writeCharSequence("404 NOT FOUND:"+path+"不存在", StandardCharsets.UTF_8);
 
            channelHandlerContext.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

NettyServer

public class NettyServer {
 
    private static final Properties webProperties = new Properties();
 
    public static void init(){
        try {
            InputStream inputStream = new FileInputStream("./web.properties");
            webProperties.load(inputStream);
 
            for (Object item : webProperties.keySet()){
                String key = (String)item;
                if (key.endsWith(".url")){
                    String servletKey = key.replaceAll("\\.url","\\.className");
                    String servletName = webProperties.getProperty(servletKey);
 
                    TomcatServlet servlet = (TomcatServlet) Class.forName(servletName).newInstance();
                    ServletMapping.getUrlServletMapping().put(webProperties.getProperty(key),servlet);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
    public static void startServer(int port){
        init();
 
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
 
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
 
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            channelPipeline.addLast(new HttpRequestDecoder());
                            channelPipeline.addLast(new HttpResponseEncoder());
                            channelPipeline.addLast(new HttpObjectAggregator(65535));
                            channelPipeline.addLast(new CustomServerHandler());
                        }
                    });
 
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
 
    public static void main(String[] args) {
        startServer(8000);
    }
}

使用測試

get請求:localhost:8000/hello?name=瓜田李下&age=20

處理GET請求
請求參數(shù)為:
name ==> [瓜田李下]
age ==> [20]

get請求:localhost:8000/hello2?name=瓜田李下&age=20

/hello2路徑?jīng)]有對應(yīng)的TomcatServlet處理

Post form請求:x-www-form-urlencoded

處理POST Form請求
請求參數(shù)為:
name ==> 瓜田李下
age ==> 20

Post json請求

處理POST json請求
請求參數(shù)為:
name ==> 瓜田李下
age ==> 20

Post form-data請求

目前只支持x-www-form-urlencoded、post json請求,不支持其它請求方式

Put:localhost:8000/hello?name=瓜田李下&age=20

目前只支持GET、POST請求方法,不支持其它方法

到此這篇關(guān)于netty 實(shí)現(xiàn)tomcat的文章就介紹到這了,更多相關(guān)netty 實(shí)現(xiàn)tomcat內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Tomcat安裝配置方法圖文教程

    Tomcat安裝配置方法圖文教程

    這篇文章主要為大家詳細(xì)介紹了Tomcat安裝配置方法圖文教程,java環(huán)境變量如何配置,Eclipse安裝配置方法圖文教程 ,為大家分享了三個教程,感興趣的小伙伴們可以參考一下
    2016-06-06
  • 阿里云服務(wù)器安裝配置tomcat 添加外網(wǎng)訪問端口的教程

    阿里云服務(wù)器安裝配置tomcat 添加外網(wǎng)訪問端口的教程

    這篇文章主要介紹了阿里云服務(wù)器安裝配置tomcat 添加外網(wǎng)訪問端口,需要的朋友可以參考下
    2019-11-11
  • Jenkins+tomcat自動發(fā)布的熱部署/重啟及遇到的問題解決辦法(推薦)

    Jenkins+tomcat自動發(fā)布的熱部署/重啟及遇到的問題解決辦法(推薦)

    這篇文章主要介紹了Jenkins+tomcat自動發(fā)布的熱部署/重啟及遇到的問題解決辦法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • 解讀Tomcat啟動、重啟、暫停操作(window)

    解讀Tomcat啟動、重啟、暫停操作(window)

    這篇文章主要介紹了解讀Tomcat啟動、重啟、暫停操作(window),具有很好的參考價值,希望對大家有所幫助。
    2023-04-04
  • Tomcat添加JMS遠(yuǎn)程監(jiān)控的代碼示例

    Tomcat添加JMS遠(yuǎn)程監(jiān)控的代碼示例

    為Tomcat添加JMS(Java Message Service)遠(yuǎn)程監(jiān)控可以讓你通過消息隊(duì)列來接收Tomcat服務(wù)器的性能指標(biāo)和事件通知,下面是一個關(guān)于在Tomcat中添加JMS遠(yuǎn)程監(jiān)控的思維導(dǎo)圖大綱,并給出一些代碼示例和建議,需要的朋友可以參考下
    2025-02-02
  • 詳解Tomcat7中WebSocket初探

    詳解Tomcat7中WebSocket初探

    隨著Html5技術(shù)的普及,主流瀏覽器對HTML5標(biāo)準(zhǔn)的支持越來越好,利用瀏覽器原生支持WebSocket就可以輕松的實(shí)現(xiàn)上面的功能。有興趣的可以了解一下。
    2017-01-01
  • nginx+tomcat單個域名及多個域名配置教程

    nginx+tomcat單個域名及多個域名配置教程

    這篇文章主要介紹了nginx+tomcat單個域名及多個域名配置教程,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-12-12
  • servlet簡介_動力節(jié)點(diǎn)Java學(xué)院整理

    servlet簡介_動力節(jié)點(diǎn)Java學(xué)院整理

    Servlet是一種服務(wù)器端的編程語言,是J2EE中比較關(guān)鍵的組成部分。本文給大家簡單介紹servlet的基本知識,感興趣的朋友一起看看吧
    2017-07-07
  • Tomcat的webapps文件夾使用

    Tomcat的webapps文件夾使用

    這篇文章主要介紹了Tomcat的webapps文件夾使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • Tomcat配置https SSL證書的項(xiàng)目實(shí)踐

    Tomcat配置https SSL證書的項(xiàng)目實(shí)踐

    本文主要介紹了Tomcat配置https SSL證書的項(xiàng)目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07

最新評論

公安县| 井陉县| 新疆| 淮北市| 凤冈县| 佛冈县| 蕲春县| 合山市| 南宁市| 沂南县| 沈阳市| 汽车| 亚东县| 海口市| 海丰县| 卫辉市| 鹿泉市| 吉木萨尔县| 分宜县| 图们市| 静海县| 那坡县| 辽中县| 昭通市| 虹口区| 策勒县| 南汇区| 西昌市| 新河县| 修武县| 瑞丽市| 霍州市| 定南县| 治多县| 榆树市| 平原县| 麟游县| 大城县| 进贤县| 彭水| 杭州市|