实验报告6-SSM框架整合

2024-06-02 23:44
文章标签 ssm 整合 框架 实验报告

本文主要是介绍实验报告6-SSM框架整合,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

资料下载链接

实验报告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")@ResponseBodypublic 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 = falsereturn 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 {@Resourceprivate UserMapper userMapper;@Overridepublic 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")@ResponseBodypublic 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 {@Resourceprivate ProductMapper productMapper;@Overridepublic 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")@ResponseBodypublic 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 {@Overridepublic 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>

这篇关于实验报告6-SSM框架整合的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1025426

相关文章

一文详解如何从零构建Spring Boot Starter并实现整合

《一文详解如何从零构建SpringBootStarter并实现整合》SpringBoot是一个开源的Java基础框架,用于创建独立、生产级的基于Spring框架的应用程序,:本文主要介绍如何从... 目录一、Spring Boot Starter的核心价值二、Starter项目创建全流程2.1 项目初始化(

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应

Python GUI框架中的PyQt详解

《PythonGUI框架中的PyQt详解》PyQt是Python语言中最强大且广泛应用的GUI框架之一,基于Qt库的Python绑定实现,本文将深入解析PyQt的核心模块,并通过代码示例展示其应用场... 目录一、PyQt核心模块概览二、核心模块详解与示例1. QtCore - 核心基础模块2. QtWid

Spring Boot 整合 MyBatis 连接数据库及常见问题

《SpringBoot整合MyBatis连接数据库及常见问题》MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,下面详细介绍如何在SpringBoot项目中整合My... 目录一、基本配置1. 添加依赖2. 配置数据库连接二、项目结构三、核心组件实现(示例)1. 实体类2. Ma

SpringBoot整合jasypt实现重要数据加密

《SpringBoot整合jasypt实现重要数据加密》Jasypt是一个专注于简化Java加密操作的开源工具,:本文主要介绍详细介绍了如何使用jasypt实现重要数据加密,感兴趣的小伙伴可... 目录jasypt简介 jasypt的优点SpringBoot使用jasypt创建mapper接口配置文件加密

SpringBoot整合MybatisPlus的基本应用指南

《SpringBoot整合MybatisPlus的基本应用指南》MyBatis-Plus,简称MP,是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,下面小编就来和大家介绍一下... 目录一、MyBATisPlus简介二、SpringBoot整合MybatisPlus1、创建数据库和

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统

Python结合Flask框架构建一个简易的远程控制系统

《Python结合Flask框架构建一个简易的远程控制系统》这篇文章主要为大家详细介绍了如何使用Python与Flask框架构建一个简易的远程控制系统,能够远程执行操作命令(如关机、重启、锁屏等),还... 目录1.概述2.功能使用系统命令执行实时屏幕监控3. BUG修复过程1. Authorization

SpringBoot集成图片验证码框架easy-captcha的详细过程

《SpringBoot集成图片验证码框架easy-captcha的详细过程》本文介绍了如何将Easy-Captcha框架集成到SpringBoot项目中,实现图片验证码功能,Easy-Captcha是... 目录SpringBoot集成图片验证码框架easy-captcha一、引言二、依赖三、代码1. Ea