Spring MVC 使用 Jetty 作为内嵌服务器

简介: Jetty 是高性能的 Servlet 容器,经常会在开发环境中作为服务器来使用。在本文中,我们将使用 Spring Web MVC 技术来实现 REST 接口,并使用 使用 Jetty 作为内嵌服务器,方便测试。

Jetty 是高性能的 Servlet 容器,经常会在开发环境中作为服务器来使用。在本文中,我们将使用 Spring Web MVC 技术来实现 REST 接口,并使用 使用 Jetty 作为内嵌服务器,方便测试。

接口设计

我们将会在系统中实现两个接口:

其中,第一个接口“/hello”将会返回“Hello World!” 的字符串;而第二个接口“/hello/way”则会返回一个包含用户信息的JSON字符串。

系统配置

我们需要在应用中添加如下依赖:

<properties>
    <spring.version>5.0.4.RELEASE</spring.version>
    <jetty.version>9.4.9.v20180320</jetty.version>
    <jackson.version>2.9.4</jackson.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>${jetty.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
</dependencies>

其中,

  • spring-webmvc 是为了使用 Spring MVC 的功能。
  • jetty-servlet是为了提供内嵌的 Servlet 容器,这样我们就无需依赖外部的容器,可以直接运行我们的应用。
  • jackson-corejackson-databind 为我们的应用提供 JSON 序列化的功能。

后台编码实现

领域模型

创建一个 User 类,代表用户信息。

public class User {
    private String username;
    private Integer age;

    public User(String username, Integer age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

控制器

创建 HelloController 用于处理用户的请求。

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello World! Welcome to visit waylau.com!";
    }
    
    @RequestMapping("/hello/way")
    public User helloWay() {
        return new User("Way Lau", 30);
    }
}

其中,映射到“/hello”的方法将会返回“Hello World!” 的字符串;而映射到“/hello/way”则会返回一个包含用户信息的JSON字符串。

应用配置

在本应用中,我们采用基于 Java 注解的配置。

AppConfiguration 是我们的主应用配置:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = { "com.waylau.spring" })  
@Import({ MvcConfiguration.class })
public class AppConfiguration {

}

AppConfiguration 会扫描“com.waylau.spring”包下的文件,并自动将相关的 bean 进行注册。

AppConfiguration 同时又引入了 MVC 的配置类 MvcConfiguration:

@EnableWebMvc
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }
}

MvcConfiguration 配置类一方面启用了 MVC 的功能,另一方面添加了 Jackson JSON 的转换器。

最后,我们需要引入 Jetty 服务器 JettyServer:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import com.waylau.spring.mvc.configuration.AppConfiguration;

public class JettyServer {
    private static final int DEFAULT_PORT = 8080;
    private static final String CONTEXT_PATH = "/";
    private static final String MAPPING_URL = "/*";

    public void run() throws Exception {
        Server server = new Server(DEFAULT_PORT);
        server.setHandler(servletContextHandler(webApplicationContext()));
        server.start();
        server.join();
    }

    private ServletContextHandler servletContextHandler(WebApplicationContext context) {
        ServletContextHandler handler = new ServletContextHandler();
        handler.setContextPath(CONTEXT_PATH);
        handler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
        handler.addEventListener(new ContextLoaderListener(context));
        return handler;
    }

    private WebApplicationContext webApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfiguration.class);
        return context;
    }
}

JettyServer 将会在 Application 类中进行启动:

public class Application {

    public static void main(String[] args) throws Exception {
        new JettyServer().run();;
    }

}

11.13.6 运行

在编辑器中,直接运行 Application 类即可。启动之后,应能看到如下控制台信息:

2018-03-21 23:14:52.665:INFO::main: Logging initialized @203ms to org.eclipse.jetty.util.log.StdErrLog
2018-03-21 23:14:52.868:INFO:oejs.Server:main: jetty-9.4.9.v20180320; built: 2018-03-20T20:21:10+08:00; git: 1f8159b1e4a42d3f79997021ea1609f2fbac6de5; jvm 1.8.0_112-b15
2018-03-21 23:14:52.902:INFO:oejshC.ROOT:main: Initializing Spring root WebApplicationContext
三月 21, 2018 11:14:52 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization started
三月 21, 2018 11:14:52 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing Root WebApplicationContext: startup date [Wed Mar 21 23:14:52 CST 2018]; root of context hierarchy
三月 21, 2018 11:14:52 下午 org.springframework.web.context.support.AnnotationConfigWebApplicationContext loadBeanDefinitions
信息: Registering annotated classes: [class com.waylau.spring.mvc.configuration.AppConfiguration]
三月 21, 2018 11:14:53 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/hello]}" onto public java.lang.String com.waylau.spring.mvc.controller.HelloController.hello()
三月 21, 2018 11:14:53 下午 org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
信息: Mapped "{[/hello/way]}" onto public com.waylau.spring.mvc.vo.User com.waylau.spring.mvc.controller.HelloController.helloWay()
三月 21, 2018 11:14:53 下午 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
信息: Looking for @ControllerAdvice: Root WebApplicationContext: startup date [Wed Mar 21 23:14:52 CST 2018]; root of context hierarchy
三月 21, 2018 11:14:53 下午 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization completed in 983 ms
2018-03-21 23:14:53.893:INFO:oejshC.ROOT:main: Initializing Spring FrameworkServlet 'org.springframework.web.servlet.DispatcherServlet-6aaa5eb0'
三月 21, 2018 11:14:53 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'org.springframework.web.servlet.DispatcherServlet-6aaa5eb0': initialization started
三月 21, 2018 11:14:53 下午 org.springframework.web.servlet.FrameworkServlet initServletBean
信息: FrameworkServlet 'org.springframework.web.servlet.DispatcherServlet-6aaa5eb0': initialization completed in 15 ms
2018-03-21 23:14:53.910:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@2796aeae{/,null,AVAILABLE}
2018-03-21 23:14:54.037:INFO:oejs.AbstractConnector:main: Started ServerConnector@42054532{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2018-03-21 23:14:54.038:INFO:oejs.Server:main: Started @1578ms

分别在浏览器中访问 “http://localhost:8080/hello” 和 “http://localhost:8080/hello/way” 地址进行测试,能看到图1和图2的响应效果。

图1 /hello接口的返回内容

图1 “/hello”接口的返回内容

图2 /hello/way接口的返回内容

图2 “/hello/way”接口的返回内容

参考应用

目录
相关文章
|
4月前
|
安全 Java Spring
Spring Security OAuth 资源服务器认证浅析
【1月更文挑战第18天】之前的几篇文章介绍了如何进行用户认证并向客户端分发 Token,以及 Token 是如何生成的,这篇分析一下,当客户端拿着 Token 去访问资源的时候,资源服务器是如何验证 Token 是否合法的。
55 2
|
7月前
|
消息中间件 Cloud Native Java
解决Spring Boot 2.7.16 在服务器显示启动成功无法访问问题:从本地到服务器的部署坑
解决Spring Boot 2.7.16 在服务器显示启动成功无法访问问题:从本地到服务器的部署坑
320 0
|
6月前
|
缓存 安全 算法
Spring Security OAuth 2.0 资源服务器— JWT
Spring Security OAuth 2.0 资源服务器— JWT
245 1
|
3月前
|
前端开发 Java API
构建异步高并发服务器:Netty与Spring Boot的完美结合
构建异步高并发服务器:Netty与Spring Boot的完美结合
|
5月前
|
存储 Java 数据库连接
Spring Boot 嵌入式服务器、Hibernate 关系和 Spring Data 全解析
Spring Boot 的嵌入式服务器功能是一项方便而强大的功能,它允许你在应用程序中直接运行 Web 服务器,无需将其部署到单独的独立 Web 服务器中。这使得开发、测试和部署 Web 应用程序变得容易,而且它还是轻量级的、易于启动和停止的,易于配置。
67 0
|
7月前
|
Web App开发 编解码 前端开发
2023年WEB内嵌VLC直接播放RTSP视频流,无需服务器转码,支持硬件解码及高版本Chrome
2015年之前还可以用VLC原生播放器在Chrome、Firefox等浏览器中直接播放,延迟比较低,效果也还不错。可惜好景不长,从 2015年Chrome、Firefox等浏览器取消了对 NPAPI插件的支持,海康威视官方提供的 web3.0开发包也只能在低版本浏览器播放。
261 0
|
8月前
|
Java 数据库 Spring
Spring Boot 生产环境出现问题,且问题莫明其妙 有可能是服务器的容量不足
今天系统莫明使用不了,同事跟我说昨天还好好的,今天突然就不行了。一想服务器没有动过,不会有什么问题呀!于是查看日志,查看数据库是都没有问题。心里非常不解,但是问题却一直存在。花了大概1小时,还是没有找到问题,最后看一眼服务器的容量,发现使用率为100%,顿时知道发生了什么事,将容量解放,重启服务问题就解决了。 像这种错误,如果没有检查服务器,估计到死都不知道是这样产生的。
43 0
|
9月前
|
前端开发 JavaScript Java
SpringMVC--服务器表单校验
SpringMVC--服务器表单校验
46 0
|
9月前
|
监控 算法 Unix
在Linux服务器上通过日志筛选技巧定位Spring Boot项目问题
在项目开发和维护的过程中,我们经常需要在 Linux 服务器上查询和分析日志文件。为了高效地处理大量的文本数据,我们可以借助一些强大的文本过滤工具,如 tail -f、more、zmore 和 grep。本文将介绍这些常用的 Linux 命令,帮助您在日志分析中更加得心应手。
155 0
|
10月前
|
安全 JavaScript 小程序
Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理
Spring Cloud实战 | 第九篇:Spring Cloud整合Spring Security OAuth2认证服务器统一认证自定义异常处理