实验报告6-SSM框架整合(1验证码)
实验报告6-SSM框架整合(2管理员登录)
实验报告6-SSM框架整合(3商品的分页查询)
实验报告6-SSM框架整合(4权限拦截器)
一、需求分析
使用普通整合方式实现SSM(SpringMVC、Spring和MyBatis)整合,实现管理员登录、后台首页和图书管理功能。
二、编码实现
1、初始代码
idea运行Exp6项目,启动Tomcat,显示HelloWorld页面
2、配置静态资源的访问映射
webapp目录下,新建/static
static目录下,导入layuimini-v2
applicationContext.xml
<!-- 配置静态资源的访问映射 -->
<mvc:resources mapping="/static/**" location="/static/" />
测试。地址栏中输入“http://localhost:8080/static/layuimini-v2/images/bg.jpg”,能正常显示图片
3、验证码
java目录,com.sw.controller包
@Controller
@RequestMapping("/admin")
public class AdminController {
@GetMapping("/login")
public String login(){
return "/admin/login";
}
}
webapp目录,/pages/admin/login.jsp,复制layuimini-v2/page/login-2.html,并修改静态资源引用路径
com.sw.controller包,CommonController
@Controller
@RequestMapping("/common")
public class CommonController {
@GetMapping("/createCaptcha")
public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
Captcha captcha = new ArithmeticCaptcha(115, 42);
//算术类型
captcha.setCharType(2);
//本次产生的验证码
String text = captcha.text();
System.out.println(text);
//将验证码进行缓存
HttpSession session = request.getSession();
session.setAttribute("captcha",text);
//将生成的验证码图片通过输出流写回客户端浏览器页面
captcha.out(response.getOutputStream());
}
}
webapp目录,/pages/user/login.jsp
定义jquery
$ = layui.jquery,
修改验证码图片鼠标悬停样式
.admin-captcha {cursor: pointer}
设置验证码图片的src属性,并设置单击事件
<img class="admin-captcha" src="/common/createCaptcha" onclick="changeCaptcha()">
window.changeCaptcha=function () {
var img = $("img.admin-captcha")
img.attr("src","/common/createCaptcha?t=" + new Date().getTime())
}
com.sw.util包,引入ApiResult类
com.sw.controller包,CommonController
@GetMapping("/checkCaptcha")
@ResponseBody
public ApiResult checkCaptcha(String captcha,HttpServletRequest request){
ApiResult result = new ApiResult();
//数据校验
if (captcha==null || captcha==""){
result.setErrorCode();
result.setMsg("验证码为空");
return result;
}
//整数校验
Integer captchaFront = 0;
try {
captchaFront = Integer.parseInt(captcha);
}
catch (Exception ex){
System.out.println(ex.getMessage());
result.setErrorCode();
result.setMsg("验证码格式错误");
return result;
}
String str = request.getSession().getAttribute("captcha").toString();
Integer sessionCaptcha = Integer.parseInt(str);
if (!sessionCaptcha.equals(captchaFront)){
result.setErrorCode();
result.setMsg("验证码错误");
}
return result;
}
webapp目录,/pages/admin/login.jsp
//验证校验码
var captchaFlag = true
$.ajax({
//同步请求
async: false,
//请求地址
url:"/common/checkCaptcha",
//传递的数据
data:{captcha:data.captcha},
//返回数据类型
dataType:"json",
success:function(res){
if (res.status != 200) {
layer.alert(res.msg)
captchaFlag = false
return false
}
},
error: function () {
layer.msg("系统异常");
return false
}
})
if (!captchaFlag){
return false
}
4、管理员登录
com.sw.pojo包,User
public class User {
private int id;
private String username;
private String password;
private String role;
//get、set
//tostring
}
com.sw.mapper包,UserMapper
public interface UserMapper {
User getOne(User userFront);
}
com/sw/mapper目录,UserMapper.xml
<select id="getOne" parameterType="User" resultType="User">
select * from t_user where username=#{username} and password=#{password} and role=#{role}
</select>
com.sw.service包,UserService
User login(User userFront);
com.sw.service.impl包,UserServiceImpl
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public User login(User userFront) {
return userMapper.getOne(userFront);
}
}
com.sw.util包,MyConst
public static final String ADMIN_SESSION = "ADMIN_SESSION.17291#$%&*";
com.sw.util包,MD5Util
public class MD5Util {
public static String encryptMD5(String input) {
try {
// 创建MD5加密对象
MessageDigest md5 = MessageDigest.getInstance("MD5");
// 执行加密操作
byte[] messageDigest = md5.digest(input.getBytes());
// 将字节数组转换为16进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
// 返回加密后的字符串
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
com.sw.controller包,AdminController
@PostMapping("/login")
@ResponseBody
public ApiResult login(User user, HttpServletRequest request){
ApiResult result = new ApiResult();
//数据校验
if (user==null||user.getUsername().equals("")||user.getPassword().equals("")){
result.setErrorCode();
result.setMsg("后台数据校验失败");
}
String md5 = MD5Util.encryptMD5(user.getPassword());
user.setPassword(md5);
user.setRole("admin");
User userDb = userService.login(user);
//登录失败
if (userDb==null){
result.setErrorCode();
result.setMsg("用户名或者密码错误");
return result;
}
userDb.setPassword("");
request.getSession().setAttribute(MyConst.ADMIN_SESSION,userDb);
return result;
}
webapp目录,/pages/admin/login.jsp
//异步登录
$.ajax({
//请求地址
url:"/admin/login",
type:"post",
//传递的数据
data:{
username:data.username,
password:data.password
},
//返回数据类型
dataType:"json",
success:function(res){
if (res.status != 200) {
layer.alert(res.msg)
return false
}
else {
window.location = '/admin/index';
}
},
error: function () {
layer.msg("系统异常");
return false
}
})
com.sw.controller包,AdminController
@GetMapping("/index")
public String index(){
return "/admin/index";
}
webapp目录,新建/pages/admin/index.jsp
5、后台首页
webapp目录,/pages/admin/index.jsp,复制layuimini-v2/index.html,并修改静态资源引用路径
com.sw.controller包,ProductController
@Controller
@RequestMapping("/product")
public class ProductController {
@GetMapping("/index")
public String index(){
return "/product/index";
}
}
webapp目录,新建/pages/product/index.jsp,复制layuimini-v2/page/table.html,并修改静态资源引用路径
webapp目录,/static/layuimini-v2/api/init.json,删除“主页模板”目录,将“菜单管理”修改为“商品管理”,href指向“/product/index”
6、商品的分页查询
com.sw.pojo包,Product
public class Product {
private int id;
private String name;
private double price;
//get、set
//tostring
}
com.sw.mapper包,ProductMapper
public interface ProductMapper {
List<Product> getList(Product product);
}
com/sw/mapper目录,ProductMapper.xml
<select id="getList" resultType="Product" parameterType="Product">
select * from t_product
<where>
<if test="name!=null and name !=''">
and name like concat('%',#{name},'%')
</if>
</where>
</select>
com.sw.service包,ProductService
PageInfo<Product> page(int pageNum, int pageSize, Product product);
com.sw.service.impl包,ProductServiceImpl
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Resource
private ProductMapper productMapper;
@Override
public PageInfo<Product> page(int pageNum, int pageSize, Product product) {
PageHelper.startPage(pageNum,pageSize);
PageInfo<Product> pageInfo = new PageInfo(productMapper.getList(product));
return pageInfo;
}
}
com.sw.util包,MyConst
public static final Integer PAGE_NUM = 1;
public static final Integer PAGE_SIZE = 10;
com.sw.controller包,ProductController
@PostMapping("/page")
@ResponseBody
public ApiResult<PageInfo<Product>> page(Integer pageNum, Integer pageSize, Product product){
ApiResult result = new ApiResult();
pageNum = pageNum > 0 ? pageNum : MyConst.PAGE_NUM;
pageSize = pageSize > 0 ? pageSize : MyConst.PAGE_SIZE;
PageInfo<Product> page = productService.page(pageNum, pageSize, product);
result.setData(page);
return result;
}
webapp目录,/pages/product/index.jsp
//初始化分页表格
form.render()
url: '/product/page',
method:"post",
cols: [[
{ type:"numbers", width: 60, title: '序号'},
{field: 'name', width: 280, title: '商品名'},
{field: 'price', width: 80, title: '价格'},
]],
parseData: function(res){ //res 即为原始返回的数据
console.log(res)
return {
"code": 0, //解析接口状态
"msg": res.msg, //解析提示文本
"count": res.data.total, //解析数据长度
"data": res.data.list //解析数据列表
};
},
request: {
pageName: 'pageNum' //页码的参数名称,默认:page
,limitName: 'pageSize' //每页数据量的参数名,默认:limit
}
webapp目录,/pages/product/index.jsp
修改第一个输入框的lable为“商品名”
//执行搜索重载
table.reload('currentTableId', {
url: '/product/page',
method:"post",
where:{
name:data.field.name,
},
parseData: function(res){ //res 即为原始返回的数据
console.log(res)
return {
"code": 0, //解析接口状态
"msg": res.msg, //解析提示文本
"count": res.data.total, //解析数据长度
"data": res.data.list //解析数据列表
};
},
request: {
pageName: 'pageNum', //页码的参数名称
limitName: 'pageSize' //每页数据量的参数名
}
}, 'data');
return false;
7、权限拦截器
com.sw.interceptor包,MyAdminInterceptor
public class MyAdminInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//合法用户拥有访问权限
User userSession = (User) request.getSession().getAttribute(MyConst.ADMIN_SESSION);
if(userSession!=null){
if(userSession.getRole().equals("admin")){
return true;
}
}
//非法用户跳转至登录页面
response.sendRedirect("/admin/login");
return false;
}
}
applicationContext.xml
<!--配置拦截器-->
<mvc:interceptors>
<!--管理员权限拦截器-->
<mvc:interceptor>
<!--需要拦截的请求-->
<mvc:mapping path="/admin/*"/>
<mvc:mapping path="/product/*"/>
<!--放行的请求-->
<mvc:exclude-mapping path="/admin/login"/>
<mvc:exclude-mapping path="/common/*"/>
<!--拦截器全限定名-->
<bean class="com.sw.interceptor.MyAdminInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>