4.嵌入式 Tomcat容器 |
您所在的位置:网站首页 › springmvc怎么运行tomcat › 4.嵌入式 Tomcat容器 |
我们将会在系统中实现两个接口: GET http://localhost:8888/hello GET http://localhost:8888/hello/way 其中,第一个接口“/hello”将会返回“Hello World!” 的字符串;而第二个接口“/hello/way”则会返回一个包含用户信息的JSON字符串。 二、项目配置我们需要在应用中添加如下依赖: org.springframework spring-webmvc org.apache.tomcat.embed tomcat-embed-core javax.servlet javax.servlet-api provided com.fasterxml.jackson.core jackson-core com.fasterxml.jackson.core jackson-databind org.projectlombok lombok 复制代码其中, spring-webmvc是为了使用 Spring MVC 的功能 tomcat-embed-core是为了提供内嵌的 Servlet 容器,这样我们就无需依赖外部的容器,可以直接运行我们的应用。 jackson-core 和 jackson-databind为我们的应用提供 JSON 序列化的功能。 三、后台编码实现 领域模型创建一个 User 类,代表用户信息。 import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class User { private String username; private Integer age; } 复制代码 控制器创建 HelloController 用于处理用户的请求。 import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello() { return "Hello World!"; } @RequestMapping("/hello/way") public User helloWay() { return new User("luopeng", 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.epom" }) @Import({ MvcConfiguration.class }) public class AppConfiguration { } 复制代码AppConfiguration 会扫描“com.epom”包下的文件,并自动将相关的 bean 进行注册。 AppConfiguration 同时又引入了 MVC 的配置类 MvcConfiguration: import java.util.List; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableWebMvc @Configuration public class MvcConfiguration implements WebMvcConfigurer { public void extendMessageConverters(List |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |