java内嵌jetty服务器

有的时候需要将一个简单的功能封装为服务,相比python使用flask、web.py的简洁,使用java-web显得太重量级,幸好,我们可以直接在java项目中使用jetty来搭建简易服务

 

1、pom.xml加入jetty依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.4.0.v20161208</version>
</dependency>
 
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>9.4.0.v20161208</version>
</dependency>
 
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-continuation</artifactId>
<version>9.4.0.v20161208</version>
</dependency>
 
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jsp</artifactId>
<version>9.1.4.v20140401</version>
</dependency>

  

2、增加Server

1
Serverserver=newServer(12580);

  

3、设置ServletContextHandler

1
2
ServletContextHandlercontext=newServletContextHandler(server,"/");
server.setHandler(context);

  

4、Context增加Servlet 
4.1 创建Servlet 继承HttpServlet,重载doGet,doPost即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class XXXHandler extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject ret =  new JSONObject();
        try {
            String ttsTxt = req.getParameter("text");
 
            String outFile = System.nanoTime() + ".mp4";
            String url = xx.xxx(ttsTxt,...);
            ret.put("ret","0");
            ret.put("url",url);
        }catch (Exception ex){
            ret.put("ret","-1");
            ret.put("error",ex.getMessage());
        }
        if(req.getParameter("callback")!=null) {
            resp.getWriter().write(req.getParameter("callback")+"("+ret.toString()+")");
        }else {
            resp.getWriter().write(ret.toString());
        }
    }
 
}

  

4.2 将Servlet 加入Context

1
2
context.addServlet(xxxHandler.class,"/xxx");
context.addServlet(Image2VideoHandler.class,"/*");

  

5、启动server

1
2
server.start();
server.join();

6、在浏览器访问http://localhost:12580/XXX 即可 

关注作者

欢迎关注作者微信公众号, 一起交流软件开发:欢迎关注作者微信公众号

posted @   JadePeng  阅读(4966)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示