springboot+thymeleaf+druid+mybatis 多模块实现用户登录功能
项目代码:https://github.com/bruceq/supermarket
项目结构:
依赖关系:
common:公共层,无依赖
dao:数据层,依赖common
service:服务层,依赖dao、common
web:应用层,依赖dao、common、service
注:启动类在web层中
父依赖pom
<?xml version='1.0' encoding='UTF-8'?><project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <modules> <module>web</module> <module>dao</module> <module>service</module> <module>common</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <!--<version>2.1.2.RELEASE</version>--> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.loan</groupId> <artifactId>supermarket</artifactId> <version>0.0.1-SNAPSHOT</version> <name>supermarket</name> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- springboot监控 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>runtime</scope> </dependency> <!-- 日志工具类 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!-- SpringBoot集成thymeleaf模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- alibaba的druid数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> <!--常用工具类 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!--集合常用工具类 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.2</version> </dependency> <!-- json处理--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> <!--验证码 --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> </dependencies> </project>
web层pom依赖:
<?xml version='1.0' encoding='UTF-8'?><project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <parent> <artifactId>supermarket</artifactId> <groupId>com.loan</groupId> <version>0.0.1-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>web</artifactId> <dependencies> <dependency> <artifactId>dao</artifactId> <groupId>com.loan</groupId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <artifactId>common</artifactId> <version>0.0.1-SNAPSHOT</version> <groupId>com.loan</groupId> </dependency> <dependency> <artifactId>service</artifactId> <version>0.0.1-SNAPSHOT</version> <groupId>com.loan</groupId> </dependency> </dependencies> <build> <plugins> <plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration> <mainClass>com.loan.supermarket.web.Application</mainClass> <!--<includeSystemScope>true</includeSystemScope>--> <layout>ZIP</layout></configuration><executions> <execution> <goals> <!--可以把依赖的包都打包到生成的Jar包中--> <goal>repackage</goal> </goals> </execution></executions> </plugin> </plugins> </build></project>
application.properties配置:
## 数据源配置spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=falsespring.datasource.username=rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 初始化时建立物理连接的个数spring.datasource.druid.initial-size=5# 最大连接池数量spring.datasource.druid.max-active=30# 最小连接池数量spring.datasource.druid.min-idle=5# 获取连接时最大等待时间,单位毫秒spring.datasource.druid.max-wait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.druid.time-between-eviction-runs-millis=60000# 连接保持空闲而不被驱逐的最小时间spring.datasource.druid.min-evictable-idle-time-millis=300000# 用来检测连接是否有效的sql,要求是一个查询语句spring.datasource.druid.validation-query=SELECT 1 FROM DUAL# 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。spring.datasource.druid.test-while-idle=true# 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。spring.datasource.druid.test-on-borrow=false# 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。spring.datasource.druid.test-on-return=false# 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。spring.datasource.druid.pool-prepared-statements=true# 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。spring.datasource.druid.max-pool-prepared-statement-per-connection-size=50# 配置监控统计拦截的filters,去掉后监控界面sql无法统计spring.datasource.druid.filters=stat,wall# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500# 合并多个DruidDataSource的监控数据spring.datasource.druid.use-global-data-source-stat=true # druid连接池监控spring.datasource.druid.stat-view-servlet.login-username=adminspring.datasource.druid.stat-view-servlet.login-password=123# 排除一些静态资源,以提高效率spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* # 端口配置server.port=8000 # mybatismybatis.type-aliases-package=com.loan.supermarket.mappermybatis.mapper-locations=classpath:mapping/*.xmlmybatis.configuration.map-underscore-to-camel-case=true # THYMELEAF (ThymeleafAutoConfiguration)spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlspring.thymeleaf.mode=HTML5spring.thymeleaf.encoding=UTF-8# ;charset=<encoding> is added#spring.thymeleaf.content-type=text/html# set to false for hot refreshspring.thymeleaf.cache=false
前42行是对druid的基础配置,包括基础数据源配置,以及druid的基础参数;
47~50行是mybatis中对于mapper的xml的配置,便于项目启动后扫描到xml的相关文件,xml内写的是项目相关的sql。
45行指默认项目启动默认端口为8000。
52行~60行是thymeleaf的基础配置,thymeleaf是一种常见的模板引擎,相当于jsp这样的前台代码。
为了实现简单的登录功能,我们在controller中定义一些接口方法:
package com.loan.supermarket.web.controller; import com.google.code.kaptcha.impl.DefaultKaptcha;import com.loan.supermarket.mapper.JsonObject;import com.loan.supermarket.mapper.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import org.thymeleaf.util.StringUtils; import javax.imageio.ImageIO;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.util.ArrayList;import java.util.Date; @Controllerpublic class TemplateController { @RequestMapping('/index') public String index(Model model) { User user = new User(); user.setName('张三'); user.setId(1L); user.setTelephone('123456789'); user.setPassword('@#$%^&*()'); user.setRegisterTime(new Date()); user.setPopedom(1); User user1 = new User(); user1.setName('李四'); user1.setId(2L); user1.setTelephone('2222222'); user1.setPassword('最近是南风天'); user1.setRegisterTime(new Date()); user1.setPopedom(1); User user2 = new User(); user2.setName('王五'); user2.setId(3L); user2.setTelephone('33333333333'); user2.setPassword('妖姬'); user2.setRegisterTime(new Date()); user2.setPopedom(1); User user3 = new User(); user3.setName('赵六'); user3.setId(4L); user3.setTelephone('33333333333'); user3.setPassword('过河卒'); user3.setRegisterTime(new Date()); user3.setPopedom(0); ArrayList<User> list = new ArrayList<User>(); list.add(user); list.add(user1); list.add(user2); list.add(user3); model.addAttribute('users', list); return 'index'; } @RequestMapping('/login') public String login1() { return 'login'; } @PostMapping('/user_login') @ResponseBody public JsonObject<String> login(String username, String password, HttpServletRequest request) { JsonObject<String> obj = new JsonObject<String>(); HttpSession session = request.getSession(); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { obj.setCode('0'); User user = new User(); user.setName(username); session.setAttribute('loginUser', user); return obj; } obj.setCode('1'); obj.setMessage('用户名或密码错误'); return obj; } @Autowired private DefaultKaptcha captchaProducer; /** * 获取验证码 的 请求路径 * @param httpServletRequest * @param httpServletResponse * @throws Exception */ @RequestMapping('/defaultKaptcha') public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{ byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { //生产验证码字符串并保存到session中 String createText = captchaProducer.createText(); httpServletRequest.getSession().setAttribute('vrifyCode', createText); //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中 BufferedImage challenge = captchaProducer.createImage(createText); ImageIO.write(challenge, 'jpg', jpegOutputStream); } catch (IllegalArgumentException e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组 captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); httpServletResponse.setHeader('Cache-Control', 'no-store'); httpServletResponse.setHeader('Pragma', 'no-cache'); httpServletResponse.setDateHeader('Expires', 0); httpServletResponse.setContentType('image/jpeg'); ServletOutputStream responseOutputStream =httpServletResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } /** * 验证的方法 * @param httpServletRequest * @param httpServletResponse * @return */ @RequestMapping('/imgvrifyControllerDefaultKaptcha') public ModelAndView imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){ ModelAndView andView = new ModelAndView(); String captchaId = (String) httpServletRequest.getSession().getAttribute('vrifyCode'); String parameter = httpServletRequest.getParameter('vrifyCode'); System.out.println('Session vrifyCode '+captchaId+' form vrifyCode '+parameter); if (!captchaId.equals(parameter)) { andView.addObject('info', '错误的验证码'); andView.setViewName('index'); } else { andView.addObject('info', '登录成功'); andView.setViewName('success'); } return andView; }}
搭配前台的代码一起分析:
<!DOCTYPE html><html xmlns:th='http://www.thymeleaf.org'><head> <title>显示学生信息</title> <meta charset='UTF-8'/> <meta name='viewport' content='width=device-width, initial-scale=1'/> <link th:href='https://www.haobala.com/bcjs/@{/bootstrap/bootstrap.css}' href='https://www.haobala.com/static/bootstrap/bootstrap.css' rel='stylesheet'/> <link th:href='https://www.haobala.com/bcjs/@{/bootstrap/bootstrap-theme.css}' href='https://www.haobala.com/static/bootstrap/bootstrap-theme.css' rel='stylesheet'/> <script th:src='https://www.haobala.com/bcjs/@{/js/jquery.min.js}' src='https://www.haobala.com/static/js/jquery.min.js'></script> <script th:src='https://www.haobala.com/bcjs/@{/js/bootstrap.min.js}' src='https://www.haobala.com/static/js/bootstrap.min.js'></script> <script type='text/javascript'> $(function () { $('#submit').click(function () {$.post('/user_login', $('#loginForm').serialize(), function (data) { if (data.code == '0') { window.location.href = 'https://www.haobala.com/index'; } else if (data.code == '1') { $('#tick').text(data.message).css('color', 'red'); }}) }); }); </script></head><body><div class='container'> <div class='row'> <form id='loginForm'> <div class='col-md-4'><div class='panel panel-primary'> <div class='panel-heading text-center'> <span class='panel-title'>学生信息</span> </div> <div class='form-group'> <label for='username' style='color: red'>账 号:</label> <div class='col-sm-8'> <input type='text' name='username' placeholder='请输入账号'> </div> </div> <div class='form-group'> <label for='password' style='color: red'>密 码:</label> <div class='col-sm-8'> <input type='password' name='password' placeholder='请输入密码'> </div> </div> <div class='form-group'> <label id='tick'> </label> </div> <div class='form-group'> <form action='imgvrifyControllerDefaultKaptcha'> <div class='col-sm-8'><input type='text' name='vrifyCode' /> </div> <img alt='验证码' onclick='this.src=’defaultKaptcha?d=’+new Date()*1' src='https://www.haobala.com/bcjs/defaultKaptcha'> </br> </form> </div> <div class='form-group'> <div class='col-sm-8'> <button type='button' class='btn btn-default'>登录</button> </div> </div> <div class='panel-footer text-right'> <span class='panel-title'>大侠工作室@2108</span> </div></div> </div> </form> </div></div></body></html>
在项目启动后,访问http://localhost:8000/login,进入到登录页面,首先加载必要的css和js资源,在填写好用户名、密码后,点击登录,会执行user_login的接口方法, 简单的对用户进行校验,即可进入首页。
其次要说的是这个项目中,添加了验证码的功能,使用了kaptcha的依赖。在登录界面中,增加了验证码的显示,点击验证码图片后,可以切换验证码。
登录界面
到此这篇关于springboot+thymeleaf+druid+mybatis 多模块实现用户登录功能的文章就介绍到这了,更多相关springboot+thymeleaf+druid+mybatis 多模块登录内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章: