实验报告6-SSM框架整合

server/2024/10/22 15:32:00/

资料下载链接

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


http://www.ppmy.cn/server/46938.html

相关文章

Python 限制输入数的范围

Python 限制输入数的范围 在 Python 编程中&#xff0c;我们经常需要限制用户输入的数据范围&#xff0c;以避免一些可能出现的问题。例如&#xff0c;在一个游戏程序中&#xff0c;我们可能想要确保玩家的分数在某个范围内&#xff0c;而不是太高或太低。在这个博文中&#x…

数据结构 实验 1

题目一&#xff1a;用线性表实现文具店的货品管理问题 问题描述&#xff1a;在文具店的日常经营过程中&#xff0c;存在对各种文具的管理问题。当库存文具不足或缺货时&#xff0c;需要进货。日常销售时需要出库。当盘点货物时&#xff0c;需要查询货物信息。请根据这些要求编…

曲面细分技术在AI去衣中的创新应用

引言&#xff1a; 随着人工智能技术的飞速发展&#xff0c;其在图像处理领域的应用日益广泛。其中&#xff0c;AI去衣技术因其独特的应用场景而备受瞩目。在这一技术的发展过程中&#xff0c;曲面细分技术发挥了至关重要的作用。本文将深入探讨曲面细分技术在AI去衣中的作用及其…

容器是什么,通俗易懂的方式带你了解它!

在当今的软件开发领域&#xff0c;容器已经成为了一个热门话题。作为一名开发者&#xff0c;我经常听到人们谈论容器&#xff0c;那么容器到底是什么呢&#xff1f; 简单来说&#xff0c;容器是一种轻量级的虚拟化技术&#xff0c;它允许我们打包应用程序及其依赖环境&#xff…

Python知识点4---循环语句

提前说一点&#xff1a;如果你是专注于Python开发&#xff0c;那么本系列知识点只是带你入个门再详细的开发点就要去看其他资料了&#xff0c;而如果你和作者一样只是操作其他技术的Python API那就足够了。 Python支持两种循环for和while&#xff0c;但是他们和其他的语言有些…

前端Vue小兔鲜儿电商项目实战Day03

一、Home - 整体结构搭建和分类实现 1. 页面结构 ①按照结构新增5个组件&#xff0c;准备最简单的模板&#xff0c;分别在Home模块的入口组件中引入 src/views/Home/components/ HomeCategory.vue HomeBanner.vue HomeNew.vue HomeHot.vue HomeProduct.vue <script …

jupyter notebook更改位置

1.找到jupyer的配置文件 一般在c盘用户的.jupter文件夹下 2. 用记事本打开这个配置文件&#xff0c;定位到c.NotebookApp.notebook_dir /path_to_your_directory 替换你的位置 3.找到jupyer图标的位置&#xff0c;打开属性 添加要存放的位置在目标文件的末尾&#xff0c;重新…

Web安全:软件开发的安全问题与解决方案

「作者简介」&#xff1a;2022年北京冬奥会网络安全中国代表队&#xff0c;CSDN Top100&#xff0c;就职奇安信多年&#xff0c;以实战工作为基础对安全知识体系进行总结与归纳&#xff0c;著作适用于快速入门的 《网络安全自学教程》&#xff0c;内容涵盖系统安全、信息收集等…