项目搭建
打开 IDEA 编辑器,选择 File -> New -> Project;
填写name(项目名称) Group( maven项目中的唯一坐标,可以由组织,比如 com ,和公司名称组成 )及 Artifact(项目名称,emmm我也不清楚这是个什么)
第一次创建我选择了默认值
点击下一步以后选择 spring web 点击创建
好啦这样我们的第一个项目就搭建完成啦
然后让我们来写我们的第一个接口!
第一个接口
实现一个获取单条用户信息的接口 getUserItem,访问地址为 http://localhost:8080/getUserItem。
- 在 com.example.demo 文件包下新建 entity 文件包;在此文件包下新建 User 类,在 User 类中分别定义 name 和 password 属性,
内容如下;
package com.example.demo.entity;
public class User {
String name;
int password;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public String toString(){
return "user{name='"+name+"\',"+"password="+password+"}";
}
}
- 在 com.example.demo 文件包下新建 service 文件包;在此文件包下新建 UserService 接口,在 UserService 接口中定义 getUserInfo 方法
内容如下:
package com.example.demo.service;
import com.example.demo.entity.User;
public interface UserService {
public User getUserInfo();
}
- 随后在 service 文件包中新建 impl 文件包,在 impl 文件包中新建 UserServiceImpl 类来实现 UserService 接口,内容如下:
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
public User getUserInfo(){
User user = new User();
user.setName("jack");
user.setPassword(12341234);
return user;
}
}
- 在 com.example.demo 文件包下新建 controller 文件包;在此文件包下新建 UserController 类,定义接口路径,返回接口数据,内容如下:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService service;
@RequestMapping(value = "/getUserItem",method = RequestMethod.GET)
public String getUserItem(){
User user = service.getUserInfo();
return user.toString();
}
}
验证接口
- 执行主函数
- 在地址栏输入 http://localhost:8080/getUserItem 进行验证,结果正确。