springboot入门项目-登陆功能实现
springboot登陆功能案例,初学者学习案例
1 概述
上一篇博客:spring入门案例-登陆功能实现
这次使用springboot完成同样的功能。
0积分下载代码
演示
2 实现
2.1 项目环境准备
2.1.1 创建maven项目
具体详情可以参考我的另一篇博客:IDEA创建Maven web项目以及Tomcat部署项目的方法
刚开始学习的时候,我比较推荐不使用模板创建项目,自己从0到1搭一个,能更好地熟悉各个模块。
2.1.2 创建包结构
包的结构与spring一样,但是在src/main/java/com/zou目录下多了一个Application类
在Application类中有一个main方法,可以直接启动spring应用
@SpringBootApplication
@EnableTransactionManagement
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
2.1.3 导入依赖
2.1.4 创建数据库表
DROP DATABASE IF EXISTS sampledb;
CREATE DATABASE sampledb DEFAULT CHARACTER SET utf8;
USE sampledb;
##创建用户表
CREATE TABLE t_user (
user_id INT AUTO_INCREMENT PRIMARY KEY,
user_name VARCHAR(30),
password VARCHAR(32),
credits INT,
last_visit datetime,
last_ip VARCHAR(23)
)ENGINE=InnoDB;
##创建用户登录日志表
CREATE TABLE t_login_log (
login_log_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT,
ip VARCHAR(23),
login_datetime datetime
)ENGINE=InnoDB;
##插入初始化数据
INSERT INTO t_user (user_name,password)
VALUES('admin','123456');
COMMIT;
2.1.5 创建spring的配置文件
同样在resources目录下创建一个application.properties的文件
# 配置数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/sampledb?useSSL=false
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 自定义连接池
#spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
# 连接池配置信息
spring.datasource.max-wait=10000
spring.datasource.max-active=50
spring.datasource.max-idle=10
spring.datasource.min-idle=8
spring.datasource.test-on-borrow=true
spring.datasource.validation-query=select 1
# 配置JNDI数据源
#spring.datasource.jndi-name=java:comp/env/jdbc/sampleDs
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
2.2 Dao层开发
2.2.1 创建domain对象
和上一博客一样,User和LoginLog
2.2.2 定义访问User的Dao
@Repository
public class UserDao {
private JdbcTemplate jdbcTemplate;
private final static String MATCH_COUNT_SQL = " SELECT count(*) FROM t_user " +
" WHERE user_name =? and password=? ";
private final static String UPDATE_LOGIN_INFO_SQL = " UPDATE t_user SET " +
" last_visit=?,last_ip=?,credits=? WHERE user_id =?";
public int getMatchCount(String userName, String password) {
return jdbcTemplate.queryForObject(MATCH_COUNT_SQL, new Object[]{userName, password}, Integer.class);
}
public User findUserByUserName(final String userName) {
String sqlStr = " SELECT user_id,user_name,credits "
+ " FROM t_user WHERE user_name =? ";
final User user = new User();
jdbcTemplate.query(sqlStr, new Object[]{userName},
new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
user.setUserId(rs.getInt("user_id"));
user.setUserName(userName);
user.setCredits(rs.getInt("credits"));
}
});
return user;
}
public void updateLoginInfo(User user) {
jdbcTemplate.update(UPDATE_LOGIN_INFO_SQL, new Object[]{user.getLastVisit(),
user.getLastIp(), user.getCredits(), user.getUserId()});
}
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
2.2.3 定义访问LoginLogDao的Dao
@Repository
public class LoginLogDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//保存登陆日志SQL
private final static String INSERT_LOGIN_LOG_SQL= "INSERT INTO t_login_log(user_id,ip,login_datetime) VALUES(?,?,?)";
public void insertLoginLog(LoginLog loginLog) {
Object[] args = { loginLog.getUserId(), loginLog.getIp(),
loginLog.getLoginDate() };
jdbcTemplate.update(INSERT_LOGIN_LOG_SQL, args);
}
}
与spring不同,springboot不需要配置Dao。
2.3 Service层开发
同样,在登陆功能中,只有一个service,UserService。负责将Dao层的UserDao和LoginLogDao组织起来,完成用户/密码认证,登陆日志记录等操作。
2.3.1 创建UserService
@Service
public class UserService {
private UserDao userDao;
private LoginLogDao loginLogDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Autowired
public void setLoginLogDao(LoginLogDao loginLogDao) {
this.loginLogDao = loginLogDao;
}
public boolean hasMatchUser(String userName, String password) {
int matchCount =userDao.getMatchCount(userName, password);
return matchCount > 0;
}
public User findUserByUserName(String userName) {
return userDao.findUserByUserName(userName);
}
@Transactional
public void loginSuccess(User user) {
user.setCredits( 5 + user.getCredits());
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
userDao.updateLoginInfo(user);
loginLogDao.insertLoginLog(loginLog);
}
}
同样,springboot不需要配置Service
2.4 Web层开发
2.4.1 配置springMVC
在应用启动类Application中重写configure()方法
2.4.2 处理登录请求
即编写controller类,LoginController,与上一博客的相同
@RestController
public class LoginController{
private UserService userService;
@RequestMapping(value = {"/","/index.html"})
public ModelAndView loginPage(){
return new ModelAndView("login");
}
@RequestMapping(value = "/loginCheck.html")
public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){
boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),
loginCommand.getPassword());
if (!isValidUser) {
return new ModelAndView("login", "error", "用户名或密码错误。");
} else {
User user = userService.findUserByUserName(loginCommand
.getUserName());
user.setLastIp(request.getLocalAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user);
request.getSession().setAttribute("user", user);
return new ModelAndView("main");
}
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
2.4.3 配置视图映射
在application.properties中创建好视图的路径,prefix表示路径前缀,suffix表示路径后缀。
2.4.3 前端页面
同样,两个jsp页面,login.jsp和main.jsp。
jsp文件放在webapp/WEB-INF目录下
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>春天论坛登陆</title>
</head>
<body>
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}" /></font>
</c:if>
<form action="<c:url value="loginCheck.html"/>" method="post">
用户名:
<input type="text" name="userName">
<br>
密 码:
<input type="password" name="password">
<br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form>
</body>
</html>
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>春天论坛</title>
</head>
<body>
${user.userName},欢迎您进入小春论坛,您当前积分为${user.credits};
</body>
</html>
2.5 启动web应用
使用springboot插件启动应用,双击spring-boot:run启动
3 bug
No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
在配置的数据库url中关闭ssl,jdbc:mysql://localhost:3306/sampledb?useSSL=false
更多推荐
所有评论(0)