Spring MVC 使用 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-core
和jackson-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”接口的返回内容
图2 “/hello/way”接口的返回内容
参考应用
- 源码:见《Spring 5 案例大全》(https://github.com/waylau/spring-5-book)的 “s5-ch11-mvc-rest”应用。
- 原文同步至:https://waylau.com/spring-mvc-use-jetty/

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
Mac下python3安装mysqlclient
最近在搞Python web,需要用到mysql驱动,以前一直使用pymysql,听说Mysqlclient性能要比pymysql好一些,果断试试安装Mysqlclient,windows下安装倒没什么问题,mac上安装花了我一天时间才搞定,过程纪录在此。MySQLdb = Mysqlclient 导入包的时候需要 import MySQLdb, 安装的时候需要 pip3 install Mysqlclient 直接pip3 install Mysqlclient 报错如图: error1.png 1.执行brew unlink mysql-connector-c卸载之前的残渣, 2.执行brew install mysql安装 再次执行pip3 install mysqlclient报错如下: error2.png 查找mysql_config文件夹位置,一般在/usr/local/mysql/bin/这个路径下,解决方法: 将mysql_config链接到/usr/local/bin目录下ln -s /usr/local/mysql/bin/mysql_config /usr/lo...
- 下一篇
Eclipse配置反编译插件jadclipse(内容有部分纠正)
Eclipse配置反编译插件jadclipse(内容有部分纠正) Jad是一个Java的一个反编译工具,是用命令行执行,和通常JDK自带的java,javac命令是一样的。不过因为是控制台运行,所以用起来不太方便。不过幸好有一个eclipse的插件JadClipse,二者结合可以方便的在eclipse中查看class文件的源代码。 1. 下载 JadClipse 下载JadClipse:http://jadclipse.sourceforge.net/wiki/index.php/Main_Page#Download注意选择与 eclipse合适的版本,用的是eclipse的neon版本,下载最新的net.sf.jadclipse_3.3.0.jar 2. 下载 Jad 下载Jad:http://www.varaneckas.com/jad,下载相应版本jad158g.win.zip 3. 配置 (1)在eclipse的dropins目录下新建features和plugins目录,将下载下来的Jadclipse,即net.sf.jadclipse_3.3.0.jar拷贝到plugins...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- CentOS7设置SWAP分区,小内存服务器的救世主
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- SpringBoot2全家桶,快速入门学习开发网站教程
- CentOS8编译安装MySQL8.0.19
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- MySQL8.0.19开启GTID主从同步CentOS8
- CentOS7,CentOS8安装Elasticsearch6.8.6
- SpringBoot2配置默认Tomcat设置,开启更多高级功能