ssm项目 --简单的分页展示以及图片上传

**分页查询部分参考[https://blog.csdn.net/qq_41875817/article/details/80499303]

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="account/findAll?page=1&pageSize=4">分页</a><br>
    <a href="account/findAll01">不分页</a><br>
    <hr>
    <form action="account/save" method="post" enctype="multipart/form-data">
        <div>
            <table>
                <tr>
                    <td>账户名称</td>
                    <td><input type="text" name="name" placeholder="输入2-4个中文字符" required pattern="/^[\u4e00-\u9fa5]{2,4}$/"></td>
                </tr>
                <tr>
                    <td>账户金额</td>
                    <td><input type="text" name="money" required></td>
                </tr>
                <tr>
                    <td>账户图片</td>
                    <td><input type="file" name="upload"></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="提交"></td>
                </tr>
            </table>
        </div>

    </form>

</body>
</html>

不分页,展示上传的图片(在此处图片展示问题困扰许久,图片原因上传到target目录,但是因为静态资源拦截,导致图片不显示 ,需要在mvc配置文件中添加配置)

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"  %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>SUCCESS</h1>
    <c:forEach var="account" items="${accounts}" >
        <c:out value="${account.id}" />
        <c:out value="${account.name}" />
        <c:out value="${account.money}" />
        <c:out value="${account.image}" />
        <img src="http://localhost:8080/uploads/${account.image}" width="100px" height="100px" />

        <br><hr>
    </c:forEach>

</body>
</html>

分页展示页面

 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>SUCCESS</h1>


    <table frame="box" rules="all">
        <tr>
            <td>序号</td>
            <td>姓名</td>
            <td>金额</td>

        </tr>
        <c:if test="${list!= null || fn:length(list) != 0}">
            <c:forEach items="${list}" var="account" begin="0" end="${fn:length(list) }">
                <tr>
                    <td>${account.id}</td>
                    <td>${account.name}</td>
                    <td>${account.money}</td>
                </tr>
            </c:forEach>
        </c:if>
    </table>
    <table>
        <tr items="${page}">
            <%-- ${pageContext.request.contextPath}  获得应用的web目录的名称  --%>
            <form method="post" action="${pageContext.request.contextPath}/account/findAll">
                <td><input type="hidden" name="page" value="1"></td>
                <%--获取当前的pageSize--%>
                <td><input type="hidden" name="pageSize" value="${requestScope.pageSize}"></td>
                <td><input type="submit" value="首页"></td>
            </form>

            <form method="post" action="${pageContext.request.contextPath}/account/findAll">
                <td><input type="hidden" name="page" value="${page.prefPage}"></td>
                <td><input type="hidden" name="pageSize" value="${requestScope.pageSize}"></td>
                <td><input type="submit" value="上一页"></td>
            </form>

            <td>当前:第${page.currentPage}页<--></td>
            <td>共:${page.totalPages}页</td>

            <form method="post" action="${pageContext.request.contextPath}/account/findAll">
                <td><input type="hidden" name="page" value="${page.nextPage}"></td>
                <td><input type="hidden" name="pageSize" value="${requestScope.pageSize}"></td>
                <td><input type="submit" value="下一页"></td>
            </form>

            <form method="post" action="${pageContext.request.contextPath}/account/findAll">
                <td><input type="hidden" name="page" value="${page.totalPages}"></td>
                <td><input type="hidden" name="pageSize" value="${requestScope.pageSize}"></td>
                <td><input type="submit" value="尾页"></td>
            </form>


            <form method="post" action="${pageContext.request.contextPath}/account/findAll">
                <td><input type="hidden" name="page" value="1"></td>
                <td>每页展示记录数<input type="text" name="pageSize" style="width: 40px"></td>
                <td><input type="submit" value="确定"></td>
            </form>

        </tr>
    </table>
    <form method="post" action="${pageContext.request.contextPath}/account/findAll">
        <table>
            <tr>
                <td>跳转到第:<input type="text" name="page" />页</td>
                <td><input type="hidden" name="pageSize" value="${requestScope.pageSize}" style="width: 40px"></td>
                <td><input type="submit" value="确定"></td>
            </tr>
        </table>
    </form>

</body>
</html>

分页界面page实体类

@Component
public class Page {
    private int currentPage=1;    //当前页数
    private int totalPages;       //总页数
    private int totalUsers;            //总行数
    private int pageSize;    //每页记录行数
    private int nextPage;        //下一页
    private int prefPage;       //前一页

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getTotalPages() {
        totalPages = totalUsers % pageSize == 0 ? totalUsers / pageSize : totalUsers / pageSize + 1;
        return totalPages;
    }

    public int getTotalUsers() {
        return totalUsers;
    }

    public void setTotalUsers(int totalUsers) {
        this.totalUsers = totalUsers;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getNextPage() {
        if (currentPage < totalPages) {
            nextPage = currentPage + 1;
        } else {
            nextPage = currentPage;
        }
        return nextPage;
    }

    public int getPrefPage() {
        if (currentPage > 1) {
            prefPage = currentPage - 1;
        } else {
            prefPage = currentPage;
        }
        return prefPage;
    }
}

控制器

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;
    @Autowired
    Page p;

    /**
     * 分页
     * @param model
     * @param page
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model,int page,int pageSize){

        System.out.println("方法执行了。。。。");
        List<Account> accounts = accountService.findAll();

        p.setTotalUsers(accounts.size());  //记录总数据数
        p.setCurrentPage(page);   //根据前台数据  当前页数
        p.setPageSize(pageSize);  //传入每页显示记录数

        //当前页数减1,乘页面大小获得已经显示的记录数
        List<Account> list = accountService.findUsersByPage((page - 1) * p.getPageSize(), p.getPageSize());
        model.addAttribute("list", list);
        model.addAttribute("page", p);
        model.addAttribute("pageSize",pageSize);  //存储当前每页展示记录数

        return "page";
    }

    /**
     * 不分页
     * @param model
     * @return
     */
    @RequestMapping("/findAll01")
    public String findAll(Model model){

        System.out.println("方法执行了。。。。");
        List<Account> accounts = accountService.findAll();
        model.addAttribute("accounts",accounts);

        return "success";
    }

    /**
     * 文件上传,使用fileupload   springmvc文件解析器
     * @param request
     * @param upload
     * @param account
     * @return
     * @throws IOException
     */
    @RequestMapping("/save")
    public String save(HttpServletRequest request, MultipartFile upload,Account account) throws IOException {

        // 上传的位置(获取Web项目的全路径target)
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(path);
        // 判断,路径是否存在
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        // 获取上传文件的名称
        String filename = upload.getOriginalFilename();
        // 把文件的名称设置唯一值
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+"_"+filename;
        // 完成文件上传
        upload.transferTo(new File(path,filename));


        System.out.println(filename);
        account.setImage(filename);
        System.out.println(account);

        accountService.saveAccount(account);


        return "success";
    }
}

dao层

@Repository
public interface AccountDao {

    /**
     * 查询所有账户信息
     * @return  Account
     */
    @Select("select * from account")
    List<Account> findAll();

    /**
     * 保存账户信息
     * @param account
     */
    @Insert("insert into account(name,money,image) values(#{name},#{money},#{image})")
    boolean saveAccount(Account account);
    /**
     * 分页查询
     */
    @Select("select * from account limit #{start},#{perPageUsers}")
    List<Account> findUsersByPage(@Param("start") int start, @Param("perPageUsers") int perPageUsers) ;

}

解决图片读取不出来

  <!-- 设置静态资源不过滤 -->
     <mvc:resources location="/static/**" mapping="/static/**" />
    <mvc:resources mapping="/uploads/**" location="/uploads/"/>  <!--配置图片上传的maven编译目录不拦截   报错因为是不存在工程之中-->
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个基于SSM框架和layui前端框架实现的分页实例: 首先,在Maven中引入相关依赖: ```xml <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.4</version> </dependency> <!-- C3P0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!-- layui --> <dependency> <groupId>com.layui</groupId> <artifactId>layui</artifactId> <version>2.5.6</version> </dependency> ``` 接着,创建一个实体类`User`,对应数据库中的`user`表: ```java public class User { private Integer id; private String name; private Integer age; //省略getter/setter方法 } ``` 然后,创建DAO层接口`UserMapper`,以及对应的XML文件`UserMapper.xml`,实现分页查询: ```java public interface UserMapper { List<User> getUserList(@Param("start") Integer start, @Param("pageSize") Integer pageSize); Integer getUserCount(); } ``` ```xml <select id="getUserList" resultType="User"> select * from user limit #{start},#{pageSize} </select> <select id="getUserCount" resultType="Integer"> select count(*) from user </select> ``` 再创建Service层接口`UserService`及其实现类`UserServiceImpl`,调用DAO层方法实现业务逻辑: ```java public interface UserService { PageInfo<User> getUserList(Integer pageNum, Integer pageSize); } @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public PageInfo<User> getUserList(Integer pageNum, Integer pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.getUserList((pageNum - 1) * pageSize, pageSize); PageInfo<User> pageInfo = new PageInfo<>(userList); int totalCount = userMapper.getUserCount(); pageInfo.setTotal(totalCount); return pageInfo; } } ``` 最后,创建Controller类`UserController`,处理前端请求并返回分页数据: ```java @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/user/list") @ResponseBody public TableResult<User> getUserList(@RequestParam(value = "page", defaultValue = "1") Integer pageNum, @RequestParam(value = "limit", defaultValue = "10") Integer pageSize) { PageInfo<User> pageInfo = userService.getUserList(pageNum, pageSize); TableResult<User> result = new TableResult<>(); result.setCode(0); result.setMsg(""); result.setCount(pageInfo.getTotal()); result.setData(pageInfo.getList()); return result; } } ``` 其中,`TableResult`是一个通用的分页返回结果类: ```java public class TableResult<T> { private Integer code; private String msg; private Long count; private List<T> data; //省略getter/setter方法 } ``` 最后,在前端页面中引入layui的分页组件: ```html <table id="userTable" lay-filter="userTable"></table> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a> </script> <script> layui.use(['table', 'layer'], function () { var table = layui.table; var layer = layui.layer; table.render({ elem: '#userTable', url: '/user/list', method: 'get', page: true, cols: [[ {field: 'id', title: 'ID', width: 70}, {field: 'name', title: '姓名', width: 120}, {field: 'age', title: '年龄', width: 70}, {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150} ]] }); }); </script> ``` 这样,一个基于SSM和layui的分页实例就完成了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值