持久层 MyBatis-Plus
业务层Spring
表现层SpringMVC+Thymeleaf
用户信息包括用户标号id,用户名称username和用户口令password,以及用户的邮箱email
添加依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.3.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.15version>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<scope>runtimescope>
dependency>
建表语句
强调:具体开发时表的约束除去primary key之外,其他约束一概不加,具体的数据检查委托给业务实现
create table if not exists tb_users(
id bigint primary key auto_increment,
username varchar(32) not null unique,
password varchar(32) not null,
email varchar(32)
)engine=innodb default charset utf8;
添加配置将连接池的管理委托给Spring框架负责
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
定义控制器,如果用户已经登录,则直接跳转分页显示页面,否则跳转到登录输入数据的页面
@Controller
public class IndexController {
@RequestMapping(value={"","/","/index"},method =
{RequestMethod.GET,RequestMethod.POST}) 实际上是模拟一个首页的效果
public String index(WebSession session) {
Object obj = session.getAttribute("userInfo");
if (obj != null && obj instanceof User)
return "index";
else {
return "redirect:/login"; 重定向到/login对应的控制器
}
}
}
UserController控制器中包含跳转到登录页面,同时准备命令对象
@Controller
public class UserController {
@GetMapping("/login")
public String toLogin(Model model){
User user=new User();
user.setUsername("yanjun");
model.addAttribute("user",user);
return "user/login";
}
}
对应的包含form表单的页面
<form action="#" th:action="@{/login}" method="post" th:object="${user}">
<table>
<tr>
<td><label for="username">用户名称:label>td>
<td>
<input type="text" id="username" th:field="*{username}"
placeholder="请输入用户名称"/>
td>
tr>
<tr>
<td><label for="password">用户口令:label>td>
<td>
<input type="password" id="password" th:field="*{password}" />
td>
tr>
<tr>
<td colspan="2">
<input type="submit" value="登录系统"/>
<input type="reset" th:value="重置数据"/>
td>
tr>
table>
form>
接收数据的控制器方法定义
@PostMapping("/login")
public String login(User user, Errors errors) throws Exception{
if(errors.hasErrors())
return "user/login";
System.out.println(user);
return "success";
}
添加服务器端数据校验
在实体类上添加对应的校验规则
@Data
@TableName("tb_users")
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Long id;
@NotBlank(message = "用户名称不能为空!")
@Size(min = 6,max = 20,message = "用户口令应该是6到20个字符之间")
private String username;
@NotBlank(message = "用户口令不能为空!")
@Size(min = 6,max = 20,message = "用户口令应该是6到20个字符之间")
private String password;
@TableField(exist = false)
private String repassword;
private String email;
}
修改控制器的方法添加验证注解
@PostMapping("/login")
public String login(@Validated User user, Errors errors) throws Exception{
if(errors.hasErrors())
return "user/login";
System.out.println(user);
return "success";
}
报错显示th:errors
<form action="#" th:action="@{/login}" method="post" th:object="${user}">
<table>
<tr>
<td><label for="username">用户名称:label>td>
<td>
<input type="text" id="username" th:field="*{username}"
placeholder="请输入用户名称"/>
<span th:errors="*{username}">span>
td>
tr>
<tr>
<td><label for="password">用户口令:label>td>
<td>
<input type="password" id="password" th:field="*{password}" />
<span th:errors="*{password}">span>
td>
tr>
<tr>
<td colspan="2">
<input type="submit" value="登录系统"/>
<input type="reset" th:value="重置数据"/>
td>
tr>
table>
form>
添加业务
接口
public interface IUserServ extends IService<User> {
boolean login(User user);
}
添加实现类
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@Service
public class UserServImpl extends ServiceImpl<UserMapper, User> implements
IUserServ {
@Override
public boolean login(User user) {
Assert.notNull(user,"参数不能为空!");
Assert.hasText(user.getUsername(),"用户名称不能为空!");
Assert.hasLength(user.getPassword(),"用户口令不能为空!");
Map<String,Object> map=new HashMap<>();
map.put("username",user.getUsername());
map.put("password",user.getPassword());
List<User> userList=getBaseMapper().selectByMap(map);
if(userList!=null && userList.size()>0){
User tmp=userList.get(0);
BeanUtils.copyProperties(tmp,user);
return true;
}
return false;
}
}
针对业务层的单元测试
@SpringBootTest
class Demo01131ApplicationTests {
@Autowired
private IUserServ userServ;
@Test
void contextLoads() {
}
@Test
void testLogin(){
User tmp=new User();
tmp.setUsername("zhangsan");
tmp.setPassword("123456");
Assertions.assertTrue(userServ.login(tmp));
System.out.println(tmp);
}
}
控制器
@PostMapping("/login")
public String login(@Validated User user, Errors errors,Model model) throws
Exception{
if(errors.hasErrors())
return "user/login";
try {
boolean res = userService.login(user);
if(!res)
throw new RuntimeException("登录失败!请重新登录");
model.addAttribute("userInfo",user);
return "redirect:/user/show";
} catch (RuntimeException e){
errors.reject("msg",null,e.getMessage());
return "user/login";
}
}
控制器
@Controller
@RequestMapping("/user")
public class AdminUserController {
@Autowired
private IUserServ userService;
@RequestMapping(value="/show",method =
{RequestMethod.GET,RequestMethod.POST})
public String show(Model model){
List<User> userList=userService.list();
return "user/show";
}
}
使用table表格显示数据
<table border="1" width="60%">
<thead>
<tr><th>用户编号th><th>用户名称th><th>用户口令th><th>邮箱th>tr>
thead>
<tbody>
<tr th:each="user:${userList}">
<td th:text="${user.id}">001td>
<td th:text="${user.username}">001td>
<td th:text="${user.password}">001td>
<td th:text="${user.email}">001td>
tr>
tbody>
table>