基于 Spring MVC 的web开发技术,实现了一个具有 登录/注册/发送JSON数据
的小应用。
与 Servlet 相比,Spring 更加简单、方便,省去了大量繁琐的步骤。
也是对前面 Spring 基础学习的一次实践:
程序访问入口:
登录:127.0.0.1:8080/login.html
注册:127.0.0.1:8080/register.html
JSON数据:127.0.0.1:8080/user/user-list.json
回到目录…
启动类,什么也不需要写。
@SpringBootApplication
public class LoginApplication {
public static void main(String[] args) {
SpringApplication.run(LoginApplication.class, args);
}
}
配置类,将 DataSource
的单例对象连接到数据库,并提交给 Spring 管理。
@Configuration
public class AppConfig {
@Bean
public DataSource getDataSource(@Value("${spring.datasource.url}") String url,
@Value("${spring.datasource.username}") String username,
@Value("${spring.datasource.password}") String password) {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(url);
mysqlDataSource.setUser(username);
mysqlDataSource.setPassword(password);
return mysqlDataSource;
}
}
回到目录…
实体类,将表中的数据包装成对象。
@Data
public class User {
private Integer uid;
private String username;
@JsonIgnore // 表示在 JSON 格式下,不显示password
private String password;
}
持久层(Dao),表示是一个获取对象的类 (实际操作数据库
)。
@Repository
public class UserDao {
private final DataSource dataSource;
@Autowired // 构造方法注入 DataSource 对象
public UserDao(DataSource dataSource) {
this.dataSource = dataSource;
}
// 向表中插入新用户
@SneakyThrows
public void insert(User user) {
String sql = "insert into users (username, password) values (?, ?)";
try (Connection c = dataSource.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.executeUpdate();
try (ResultSet rs = ps.getGeneratedKeys()) {
rs.next();
user.setUid(rs.getInt(1));
}
}
}
}
// 根据用户名获取表中的用户数据
@SneakyThrows
public User selectOneByUsername(String username) {
String sql = "select uid, username, password from users where username = ?";
try (Connection c = dataSource.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, username);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
User user = new User();
user.setUid(rs.getInt("uid"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
}
}
}
// 生成链表(包含表中所有用户数据)
@SneakyThrows
public List<User> selectList() {
List<User> userList = new ArrayList<>();
String sql = "select uid, username, password from users order by uid desc";
try (Connection c = dataSource.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(sql)) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
User user = new User();
user.setUid(rs.getInt("uid"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
userList.add(user);
}
}
}
}
return userList;
}
}
回到目录…
业务逻辑类,表示具体的业务逻辑,注册、登录。。。
@Slf4j
@Service
public class UserService {
private final UserDao userDao;
@Autowired
public UserService(UserDao userDao) {
this.userDao = userDao;
}
// 注册
public void register(User user) {
userDao.insert(user);
}
// 登录
public User login(String username, String password) {
User user = userDao.selectOneByUsername(username);
if (user == null) {
log.debug("用户名对应的用户不存在");
return null;
}
if (!user.getPassword().equals(password)) {
log.debug("密码不对");
return null;
}
log.debug("用户名 + 密码都正确");
return user;
}
// 用户列表
public List<User> getUserList() {
return userDao.selectList();
}
}
回到目录…
控制类,处理http请求。
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
// 注册动态资源
@PostMapping(value = "/register.do", produces = "text/html; charset=utf-8")
@ResponseBody
public String register(User user) {
log.debug("用户传入参数: {}", user);
userService.register(user);
// 注册成功,返回HTML标签
return "注册成功!去登录";
}
// 登录动态资源
@PostMapping("/login.do")
public String login(String username, String password, HttpServletRequest request) {
User user = userService.login(username, password);
if (user == null) {
// 不存在该用户
log.debug("用户登录失败,重定向回登录页");
return "redirect:/login.html"; // "redirect:" 是固定的,后边加目标 URL
}
// 登录成功 - 建立会话
HttpSession session = request.getSession(true);
session.setAttribute("currentUser", user);
// 展示用户列表
return "redirect:/user/user-list.json";
}
// 演示一个用户列表的 JSON,要求,用户必须已经登录
private static class ResultView {
public boolean success;
public User currentUser;
public List<User> userList;
// 用户不存在,返回一堆空
public ResultView() {
this.success = false;
this.currentUser = null;
this.userList = new ArrayList<>();
}
// 用户存在,返回数据
public ResultView(User currentUser, List<User> userList) {
this.success = true;
this.currentUser = currentUser;
this.userList = userList;
}
}
@GetMapping("/user-list.json")
@ResponseBody // 表示处理 JSON
public ResultView userList(HttpServletRequest request) {
User currentUser = null;
HttpSession session = request.getSession(false); // 参数 false,防止新建会话
if (session != null) {
currentUser = (User) session.getAttribute("currentUser");
}
if (currentUser == null) {
return new ResultView();
}
// 获取数据链表
List<User> userList = userService.getUserList();
return new ResultView(currentUser, userList);
}
}
回到目录…
DOCTYPE html>
<html lang="zh-hans">
<head>
<meta charset="UTF-8">
<title>登录title>
head>
<body>
<form method="post" action="/user/login.do">
<input type="text" name="username">
<input type="password" name="password">
<button>登录button>
form>
body>
html>
DOCTYPE html>
<html lang="zh-hans">
<head>
<meta charset="UTF-8">
<title>注册title>
head>
<body>
<form method="post" action="/user/register.do">
<input type="text" name="username">
<input type="password" name="password">
<button>注册button>
form>
body>
html>
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/lianxi?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: 123456
回到目录…
总结:
提示:这里对文章进行总结:
以上就是今天的学习内容,本文是SpringMVC的学习,学习基于SpringMVC的web开发技术,也是对Spring注解的综合应用,实现了一个具有注册/登录/发送JSON数据功能的小应用。之后的学习内容将持续更新!!!