实验报告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

相关文章

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

Springboot整合Redis主从实践

《Springboot整合Redis主从实践》:本文主要介绍Springboot整合Redis主从的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言原配置现配置测试LettuceConnectionFactory.setShareNativeConnect

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

SpringBoot整合Apache Flink的详细指南

《SpringBoot整合ApacheFlink的详细指南》这篇文章主要为大家详细介绍了SpringBoot整合ApacheFlink的详细过程,涵盖环境准备,依赖配置,代码实现及运行步骤,感兴趣的... 目录1. 背景与目标2. 环境准备2.1 开发工具2.2 技术版本3. 创建 Spring Boot

Spring Boot 整合 Apache Flink 的详细过程

《SpringBoot整合ApacheFlink的详细过程》ApacheFlink是一个高性能的分布式流处理框架,而SpringBoot提供了快速构建企业级应用的能力,下面给大家介绍Spri... 目录Spring Boot 整合 Apache Flink 教程一、背景与目标二、环境准备三、创建项目 & 添

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

MQTT SpringBoot整合实战教程

《MQTTSpringBoot整合实战教程》:本文主要介绍MQTTSpringBoot整合实战教程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录MQTT-SpringBoot创建简单 SpringBoot 项目导入必须依赖增加MQTT相关配置编写

C++ HTTP框架推荐(特点及优势)

《C++HTTP框架推荐(特点及优势)》:本文主要介绍C++HTTP框架推荐的相关资料,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Crow2. Drogon3. Pistache4. cpp-httplib5. Beast (Boos

MybatisPlus3.3.1整合clickhouse的过程

《MybatisPlus3.3.1整合clickhouse的过程》:本文主要介绍MybatisPlus3.3.1整合clickhouse的过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定... 前言ClickHouse是俄罗斯Yandex发布的一款数据分析型数据库支持sql语法,详情可以访问官网,