您当前的位置: 首页 >  服务器

_waylau

暂无认证

  • 1浏览

    0关注

    275博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

_waylau 发布时间:2018-03-27 23:53:53 ,浏览量:1

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

接口设计

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

  • GET http://localhost:8080/hello
  • GET http://localhost:8080/hello/way

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

系统配置

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


    5.0.4.RELEASE
    9.4.9.v20180320
    2.9.4


    
        org.springframework
        spring-webmvc
        ${spring.version}
    
    
        org.eclipse.jetty
        jetty-servlet
        ${jetty.version}
        provided
    
    
        com.fasterxml.jackson.core
        jackson-core
        ${jackson.version}
    
    
        com.fasterxml.jackson.core
        jackson-databind
        ${jackson.version}
    

其中,

  • 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            
关注
打赏
1651845987
查看更多评论
0.0388s