创建项目
1、创建maven / SpringBoot 项目
2、添加依赖
3、创建SpringBoot引导类 Application
项目基本结构
引导类Application 同级目录下创建模块包
在resources目录存放xml、配置文件及页面等
controller 控制层
定义前端请求与后端接口间的映射关系
Tips:这里只是映射,具体的业务逻辑方法在services包中说明
工作原理:
- 前端向指定的URL发送请求;
- 后端接收到请求,根据URL的格式,查找controller层中的不同方法,将该请求传给符合条件的方法进行处理;
- 返回response(这个response可以是一个html页面,也可以是json对象和json字符串)
@Slf4j
@Controller
@RequestMapping(value = "/api/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(String name, Integer age, String pwd, Model model, HttpServletRequest request, HttpServletResponse response)throws Exception{
try{
//打印日志
log.info(name+","+age+","+pwd);
//获取注册的结果
User result = DempService.register(name, age, pwd);
if(result.isSuccess()){
//将结果存到model里面,用于前端view层展示
model.addAttribute("result",result);
//跳转至注册结果页面
return "registerResult";
}else{
response.setContentType("application/json; charset=utf-8");
response.getWriter().print("{\"code\":\"0002\",\"msg\":\"用户名已存在,注册失败!\"}");
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(String name, String pwd, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception{
try{
//打印日志
log.info(name+","+pwd);
//获取登录查询的结果
User result = demoServices.login(name, pwd);
if(result.isSuccess()){
//将结果存到model里面,用于前端view层展示
model.addAttribute("result",result);
HttpSession session = request.getSession();
session.setAttribute("name", result.getName());
session.setAttribute("password",result.getPwd());
System.out.println("登录后的sessionID:"+session.getId());
//跳转至登录结果页面
return "loginResult";
}else{
response.setContentType("application/json; charset=utf-8");
response.getWriter().print("{\"code\":\"0001\",\"msg\":\"用户名或密码错误!\"}");
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
示例
model 数据库实体层 DTO
数据库表对应的Entity类,每个字段都是表中的一列
Tips:注意属性名与数据库列名的对照
public class User {
private Long id;
private String username;
private String password;
private String identity;
//getter与setter方法
//...
}
service 业务层
定义后端接口的具体业务逻辑方法的实现
存放services接口与具体的实现类
借助dao包(即mapper)中提供的数据库相关功能,完成前端要求功能所需的数据的查询与插入,并返回相关的entity类对象。
Tips:services包的相关方法只是调用dao包的相关方法
命名规则
- 接口为XxxServices / XxxInterfaceService:只是简单地声明相关业务逻辑方法,没有别的代码和注解;
- 接口实现类为XxxServicesImpl / XxxServices,继承自XxxServices / XxxInterfaceService,需要实现这些业务逻辑方法
格式:
public Demo sercice_func(...){
Demo result = new Demo();
xxx = DemoMapper.mapper_func(...);
try{
if(xxx != null){
//sql成功,成功接收返回值
result.setXxx(...);
result.setMsg("成功!");
}else{
//sql失败
result.setXxx(...);
result.setMsg("失败,...");
}catch (Exception e){
e.printStackTrace();
result.setMsg(e.getMessage());
}
return result;
}
public interface DemoInterfaceService {
User register(String name, Integer age, String pwd);
User login(String name, String pwd);
}
接口 DemoInterfaceService.java
@Service
public class DemoServices ements DemoInterfaceService {
@Autowired
private DemoMapper demoMapper;
@Override
public User register(String name, Integer age, String pwd){
User existUser = demoMapper.findUserByName(name);
User result = new User();
try {
if (existUser != null) {
result.setXxx(...);
} else {
demoMapper.register(name, age, pwd);//注册后再使用该名字查询用户信息
User currentRegUser = demoMapper.findUserByName(name);
result.setXxx(...);
}
} catch (Exception e) {
e.printStackTrace();
result.setMsg(e.getMessage());
}
return result;
}
@Override
public User login(String name, String pwd){
User result = new User();
result.setSuccess(false);
Long userId = demoMapper.login(name,pwd);
try{
if(userId != null){
result.setMsg("登录成功!");
result.setSuccess(true);
//根据userId查询出当前登录用户
User currentLoginUser = demoMapper.findUserById(userId);
result.setXxx(...);
}else{
result.setMsg("用户名或密码不正确!");
result.setSuccess(false);
}
} catch (Exception e){
e.printStackTrace();
result.setMsg(e.getMessage());
}
return result;
}
}
接口实现类 DemoService.java
mapper 数据持久层 DAO
定义接口dao,声明了数据库操作的相关方法,业务逻辑层的各项功能通过dao方法实现与数据库的交互
Tips:具体的方法实现在mapper.xml中完善 方法对应id
DemoMapper.java
@Repository
@Mapper
public interface DemoMapper {
//查询用户是否存在,若是存在则提示已存在
User findUserByName(String name);
//新增用户
void register(String name, Integer age, String pwd);
//用户登录--根据用户名和密码查询ID是否存在
Long login(String name, String pwd);
User findUserById(Long id);
}
DemoMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxx.demo.mapper.DemoMapper" >
<resultMap id="DemoResultMap" type="com.xxx.Demo.Model.DemoModel" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="pwd" property="pwd" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, name, age, pwd
</sql>
<select id="findUserByName" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where name=#{name}
</select>
<select id="login" resultType="java.lang.Long">
select u.id from user u where u.name=#{param1} and u.pwd=#{param2}
</select>
<select id="findUserById" resultMap="BaseResultMap">
select * from user u where u.id=#{id}
</select>
<insert id="register">
insert into user (name,age,pwd) values(#{param1},#{param2},#{param3})
</insert>
</mapper>
Tips:
- com开始:com.xxx.xxx.XxxMapper;
- 如果要返回多个查询项,就要用resultMap,它对应一个entity类,借助类对象返回;
- mapper 中方法传入的参数,通过#{参数名}传进xml文件。
编写顺序
model --> mapper.xml --> mapper.java --> interfaceService --> Service --> Controller --> html、js
调用顺序
html、js --> Controller --> interfaceService --> Service --> mapper --> model