这是一个关于留言板的项目,项目虽然小,但是十分的简单和全面。
第一步:在pom中添加我们依赖的包:
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.24</version>
</dependency>
<!--mysql 连接器-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--提供实体set,get方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
第二步:创建数据库,这里我的数据库名设为demo,其中包括两个表:user和word
CREATE TABLE user
(
user_name VARCHAR(40) NULL,
user_password VARCHAR(40) NULL,
register_time DATETIME NULL,
id INT AUTO_INCREMENT
PRIMARY KEY
)
ENGINE = InnoDB;
CREATE TABLE word
(
word_id INT AUTO_INCREMENT
PRIMARY KEY,
user_id INT NULL,
title VARCHAR(100) NULL,
content VARCHAR(200) NULL,
leave_time TIMESTAMP NULL
)
ENGINE = InnoDB;
第三步,我们需要将项目与数据库进行关联,我们需要在application.properties文件下配置数据库链接和jpa的配置
## mysql init
spring.datasource.url = jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
spring.datasource.username = root
spring.datasource.password = 123456789
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.jpa:
show-sql: true
database: MYSQL
properties.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
第四步:设置swagger2
在xxApplication同级添加swagger2.java文件
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//com.example.gz.controller 就是存放controller类的包
.apis(RequestHandlerSelectors.basePackage("com.ex.goog.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("malei API 文档")
.version("1.0")
.termsOfServiceUrl("http://www.baidu.com")
.description("API 描述")
.build();
}
}
以上4个步骤就将项目需要的环境就搭建完成了。现在开始写代码了
第五步:创建用户和留言板实体
@Data
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, columnDefinition = "Int(11) COMMENT '用户主键'")
private int id;
@Column(nullable = false, columnDefinition = "varchar(40) COMMENT '用户名' default '未命名'")
private String userName;
@Column(nullable = false, columnDefinition = "varchar(40) COMMENT '用户密码' default ' '")
private String userPassword;
@JSONField(format="yyyy-MM-dd HH:mm:ss")
@Column(nullable = false, columnDefinition = "datetime COMMENT '注册时间'")
private Timestamp registerTime;
}
@Data
@Entity
public class Word {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, columnDefinition = "Int(11) COMMENT '留言主键'")
private int wordId;
@Column(nullable = false, columnDefinition = "Int(11) COMMENT '用户外键'")
private int userId;
@Column(nullable = false, columnDefinition = "varchar(100) COMMENT '留言标题' default '未命名'")
private String title;
@Column(nullable = false, columnDefinition = "varchar(20000) COMMENT '留言内容' default '没有内容'")
private String content;
@JSONField(format="yyyy-MM-dd HH:mm:ss")
@Column(nullable = false, columnDefinition = "datetime COMMENT '留言时间'")
private Timestamp leaveTime;
}
第六步:编写controller包
@RestController
@Api("swaggerController相关的api")
public class UserController {
@Autowired
UserService userService;
/**
* 注册新用户
*
* @param userName
* @param userPassword
* @return
*/
@ApiOperation(value = "注册新用户", notes = "试一试吧")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userName", value = "用户ID", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "userPassword", value = "密码", required = true, dataType = "String")})
@PostMapping(value = "/userRegister")
public Response userRegister(@RequestParam("userName")String userName,
@RequestParam("userPassword")String userPassword){
return userService.userRegister(userName,userPassword);
}
/**
* 根据id查询用户
*/
@ApiOperation(value = "通过userId查询用户", notes = "试一试吧")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "String")})
@PostMapping(value = "/getUser")
public Response getUser(@RequestParam("userId") int userId){
return userService.getUserById(userId);
}
/**
* 用户登陆
*/
@ApiOperation(value = "用户登陆", notes = "试一试吧")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userName", value = "用户ID", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "userPassword", value = "密码", required = true, dataType = "String")})
@PostMapping(value = "/userLogin")
public Response userLogin(@RequestParam("userName")String userName,
@RequestParam("userPassword")String userPassword){
return userService.userLogin(userName,userPassword);
}
}
@RestController
public class WordController {
@Autowired
WordService wordService;
/**
* 留言
*
* @param userId
* @param title
* @param content
* @return
*/
@ApiOperation(value = "留言", notes = "试一试吧")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "title", value = "标题", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "content", value = "内容", required = true, dataType = "String")})
@PostMapping(value = "/leaveWord")
public Response leaveWord(@RequestParam("userId")Integer userId,
@RequestParam("title")String title,
@RequestParam("content")String content){
return wordService.leaveWord(userId,title,content);
}
/**
* 获取所有留言
*
* @param userId
* @return
*/
@ApiOperation(value = "留言", notes = "试一试吧")
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "String")})
@PostMapping(value = "/getWords")
public Response getWords(@RequestParam("userId")Integer userId){
return wordService.getWords(userId);
}
}
第七步:我们需要编写service层和实现
public interface UserService {
Response userRegister(String userName, String userPassword);
Response getUserById(int userId);
Response userLogin(String userName, String userPassword);
}
public interface WordService {
Response leaveWord(Integer userId, String title, String content);
Response getWords(Integer userId);
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserRepository userRepository;
@Override
public Response userRegister(String userName, String userPassword) {
try{
User user = new User();
user.setUserName(userName);
user.setUserPassword(userPassword);
user.setRegisterTime(new Timestamp(System.currentTimeMillis()));
user = userRepository.save(user);
return new Response("0", JSON.toJSONString(user));
}catch (Exception ex){
ex.printStackTrace();
return new Response("-1", "错误");
}
}
@Override
public Response getUserById(int id) {
if(!userRepository.existsById(id)){
return new Response("-1", "用户不存在");
}
Optional<User> optional = userRepository.findById(id);
User user = optional.get();
return new Response("0", JSON.toJSONString(user));
}
@Override
public Response userLogin(String userName, String userPassword) {
User user = userRepository.findByUserName(userName);
if(user != null){
if(user.getUserPassword().equals(userPassword)){
user.setUserPassword("");
return new Response("0", JSON.toJSONString(user));
}else {
return new Response("-1","密码错误");
}
}else {
return new Response("-1","用户不存在");
}
}
}
@Service
public class WordServiceImpl implements WordService{
@Autowired
WordRepository wordRepository;
@Autowired
UserRepository userRepository;
@Override
public Response leaveWord(Integer userId, String title, String content) {
Integer id = userId;
//判断该id是否存在
if(!userRepository.existsById(id)){
return new Response("-1", "用户不存在");
}
try {
Word word = new Word();
word.setUserId(userId);
word.setTitle(title);
word.setContent(content);
word.setLeaveTime(new Timestamp(System.currentTimeMillis()));
wordRepository.save(word);
return new Response("0", JSON.toJSONString(word));
}catch (Exception ex){
ex.printStackTrace();
return new Response("-1", "错误");
}
}
@Override
public Response getWords(Integer userId) {
List<Word> words = wordRepository.findAll();
if(words.size()>0)
return new Response("0", JSONArray.toJSONString(words));
else
return new Response("0", "没有留言");
}
}
第八步:编写数据库的实现
/**
* 数据库查询
*/
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
User findByUserName(String userName);
}
public interface WordRepository extends JpaRepository<Word,Integer> {
}