1.新建一个springboot的maven项目:
2.数据库文件:
INSERT INTO user VALUES ('2', '李四', '男');
3.引入依赖文件pom.xml:
4.application.properties文件:
server.port = 8088
# jdbc:mysql
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.typeAliasesPackage=com.springboot.entity
mybatis.mapperLocations=classpath:mapper/*.xml
5.User实体类文件:
package com.springboot.entity;
public class User {
private String id;
private String name;
private String sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
6.UserMapper文件:
package com.springboot.mapper;
import java.util.List;
import com.springboot.entity.User;
public interface UserMapper {
/**获取所有用户信息
* @return
*/
public List
}
7.json工具类:
package com.springboot.tools;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* json工具
*
* @author shenyan
*
*/
public class JsonUtility {
private static Logger logger = LogManager.getLogger(JsonUtility.class.getName());
public static String convertBean2Json(Object bean) {
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
json = mapper.writeValueAsString(bean);
} catch (JsonProcessingException e) {
logger.error(e.getMessage());
}
return json;
}
}
8.UserController类:
package com.springboot.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.entity.User;
import com.springboot.mapper.UserMapper;
import com.springboot.tools.JsonUtility;
@Controller
public class UserController{
@Autowired
private UserMapper userMapper;
@RequestMapping("/")
@ResponseBody
public String home() {
return "Hello World!";
}
@RequestMapping("/getAllUsers")
@ResponseBody
public String getAllUsers() {
List
return JsonUtility.convertBean2Json(users);
}
}
9.springboot启动类:
package com.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.springboot.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
10.UserMapper.xml文件:
id, name, sex