Spring Boot中引入web模块

1、修改pom.xml

引入spring boot web模块

		<dependency>
			<!-- 引入web模块 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

2、新增controller类

Controller字样标明当前类要作为一个控制器servlet,MVC中的C
注解RestController标明controller里面的方法,输出json格式内容
注解RequestMapping标明路由信息(网址)

@RestController
public class HelloController {
	
	@RequestMapping("/hello")
	public String hello(){
		return "Hello World!";
	}

}

3、application.properties

指定tomcat端口为8081,如果不指定则默认8080
server.port=8081

4、运行

run

5、查看结果

浏览器中输入http://cos6743:8081/hello,界面输出 Hello World!

6、更上层楼:自定义java对象

6.1、新增model类,返回该类的对象

package com.test.demo.model;

public class User {
	String name;
	int age;
	List<String> books;
	
	public List<String> getBooks() {
		return books;
	}
	public void setBooks(List<String> books) {
		this.books = books;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

6.2、新增方法

在HelloController类中新增如下方法

	@RequestMapping("/helloUser")
	public User getUer(){
		List<String> books = new ArrayList<String>();
		books.add("Harry Potter");
		books.add("Cinderella");
		
		User u = new User();
		u.setName("Tom");
		u.setAge(35);
		u.setBooks(books);
		return u;
	}

6.3、启动application类,查看结果

访问地址http://cos6743:8081/helloUser,
返回Json结果:{“name”:“Tom”,“age”:35,“books”:[“Harry Potter”,“Cinderella”]}

猜你喜欢

转载自blog.csdn.net/weixin_44153121/article/details/85326997