SSM酒店管理系统项目Day12


建议配合视频学习食用(8-5~9-2):
https://www.bilibili.com/video/BV1rr4y1F7Y2?p=1

16.房型管理

16.1 添加房型管理页面

1.roomTypeManager.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <!-- 获取CSRF Token -->
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- 获取CSRF头,默认为X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/statics/layui/lib/layui-v2.5.5/css/layui.css"
          media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/statics/layui/css/public.css" media="all">
    <style>
        .thumbBox{ height:200px; overflow:hidden; border:1px solid #e6e6e6; border-radius:2px; cursor:pointer; position:relative; text-align:center; line-height:200px;width: 210px;}
        .thumbImg{ max-width:100%; max-height:100%; border:none;}
        .thumbBox:after{ position:absolute; width:100%; height:100%;line-height:200px; z-index:-1; text-align:center; font-size:20px; content:"缩略图"; left:0; top:0; color:#9F9F9F;}
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <%-- 搜索条件 --%>
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">房型名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="typeName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn"><i
                                    class="layui-icon layui-icon-search"></i>搜索
                            </button>
                            <button type="reset" class="layui-btn layui-btn-warm"><i
                                    class="layui-icon layui-icon-refresh-1"></i>重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <%-- 表格工具栏 --%>
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"><i
                        class="layui-icon layui-icon-add-1"></i>添加
                </button>
            </div>
        </script>

        <%-- 数据表格 --%>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <%-- 行工具栏 --%>
        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit"><i
                    class="layui-icon layui-icon-edit"></i>编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete"><i
                    class="layui-icon layui-icon-close"></i>删除</a>
        </script>

        <%-- 添加和修改窗口 --%>
        <div style="display: none;padding: 5px" id="addOrUpdateWindow">
            <form class="layui-form" style="width:90%;" id="dataFrm" lay-filter="dataFrm">
                <!-- 隐藏域,保存房型id -->
                <input type="hidden" name="id">
                <div class="layui-col-md12 layui-col-xs12">
                    <div class="layui-row layui-col-space10">
                        <div class="layui-col-md9 layui-col-xs7">
                            <div class="layui-form-item magt3" style="margin-top: 8px;">
                                <label class="layui-form-label">房型名称</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" name="typeName" lay-verify="required"  placeholder="请输入房型名称">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">房型状态</label>
                                <div class="layui-input-block">
                                    <select name="status" id="status" lay-verify="required">
                                        <option value="">请选择房型状态</option>
                                        <option value="1">可预订可入住</option>
                                        <option value="1">房型已满</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">房型备注</label>
                                <div class="layui-input-block">
                                    <textarea class="layui-textarea" name="remark" id="remark"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md3 layui-col-xs5">
                            <div class="layui-upload-list thumbBox mag0 magt3">
                                <input type="hidden" name="photo" id="photo" value="/statics/images/defaultimg.jpg">
                                <img class="layui-upload-img thumbImg" src="/statics/images/defaultimg.jpg">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item magb0">
                        <div class="layui-inline">
                            <label class="layui-form-label">参考价格</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" name="price" lay-verify="required|number"
                                       placeholder="请输入参考价格">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">可住人数</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" name="liveNum" lay-verify="required|number"
                                       placeholder="请输入可住人数">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">床位数</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" name="bedNum" lay-verify="required|number" placeholder="请输入床位数">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">房间数</label>
                            <div class="layui-input-inline">
                                <input type="text" class="layui-input" name="roomNum" lay-verify="required|number"
                                       placeholder="请输入房间数">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block" style="text-align: center;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit" id="doSubmit"><span
                                    class="layui-icon layui-icon-add-1"></span>提交
                            </button>
                            <button type="reset" class="layui-btn layui-btn-warm"><span
                                    class="layui-icon layui-icon-refresh-1"></span>重置
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>

    </div>
</div>
<script src="${pageContext.request.contextPath}/statics/layui/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'laydate', 'jquery', 'layer','upload'], function () {
        var $ = layui.jquery,
            form = layui.form,
            laydate = layui.laydate,
            upload = layui.upload,
            layer = layui.layer,
            table = layui.table;

        //获取<meta>标签中封装的CSRF Token
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        //将头中的CSRF Token信息进行发送
        $(document).ajaxSend(function (e,xhr,options) {
            xhr.setRequestHeader(header,token);
        });

        //渲染表格组件
        var tableIns = table.render({
            elem: '#currentTableId',
            url: '${pageContext.request.contextPath}/admin/roomType/list',
            toolbar: '#toolbarDemo',
            cols: [[
                {field: 'id', width: 60, title: '编号', align: "center"},
                {field: 'typeName', minWidth: 150, title: '名称', align: "center"},
                {field: 'price', minWidth: 100, title: '价格', align: "center"},
                {field: 'liveNum', minWidth: 100, title: '可住人数', align: "center"},
                {field: 'bedNum', minWidth: 100, title: '床位数', align: "center"},
                {field: 'roomNum', minWidth: 100, title: '房间数', align: "center"},
                {field: 'avilableNum', minWidth: 100, title: '可用房间数', align: "center"},
                {field: 'reservedNum', minWidth: 100, title: '已预订数', align: "center"},
                {field: 'livedNum', minWidth: 100, title: '已入住数', align: "center"},
                {field: 'status', minWidth: 100, title: '状态', align: "center",templet:function (d) {
                        return d.status == 1 ?"<font color='blue'>可预订</font>" : "<font color='red'>房型已满</font>";
                    }},
                {field: 'remark', minWidth: 100, title: '备注', align: "center"},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            page: true,
            done: function (res, curr, count) {
                //判断当前页码是否是大于1并且当前页的数据量为0
                if (curr > 1 && res.data.length == 0) {
                    var pageValue = curr - 1;
                    //刷新数据表格的数据
                    tableIns.reload({
                        page: {curr: pageValue}
                    });
                }
            }
        });


        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });

        //渲染文件上传组件
        upload.render({
            elem:".thumbBox",//绑定元素
            url:"/admin/roomType/uploadFile",//提交地址
            acceptMime: 'image/*',//规定打开文件选择框时,筛选出的文件类型
            field: 'attach',//文件上传的字段值,等同于input标签的name属性值,该值必须与控制器中的方法参数名一致
            method: "post",//提交方式
            //文件上传成功后的回调函数
            done:function (res, index, upload) {
                //图片回显
                $(".thumbImg").attr("src",res.data.src);
                $('.thumbBox').css("background", "#fff");
                //隐藏域赋值
                $("#photo").val(res.imagePath);
            }
        });


        //监听表格头部工具栏事件
        table.on("toolbar(currentTableFilter)",function (obj) {
            switch (obj.event) {
                case 'add':
                    openAddWindow();
                    break;
            }
        });

        //监听表格行工具栏事件
        table.on("tool(currentTableFilter)",function (obj) {
            switch (obj.event) {
                case 'edit':
                    openUpdateWindow(obj.data);
                    break;
                case 'delete':
                    deleteById(obj.data);
                    break;
            }
        });

        //定义变量,分别保存提交地址和窗口索引
        var url,mainIndex;

        /**
         * 打开添加窗口
         */
        function openAddWindow() {
            mainIndex = layer.open({
                type:1,
                title:"添加房型",
                area: ["800px", "500px"],//窗口宽高
                content: $("#addOrUpdateWindow"),//引用的内容窗口
                success:function () {
                    //提交地址
                    url = "/admin/roomType/addRoomType";
                    //清空表单数据
                    $("#dataFrm")[0].reset();
                    //设置隐藏域默认值
                    $("#photo").val("static/layui/images/defaultimg.jpg");
                    //设置默认图片
                    $(".thumbImg").attr("src","/hotel/show/images/defaultimg.jpg");
                }
            });
        }

        /**
         * 打开修改窗口
         * @param data
         */
        function openUpdateWindow(data) {
            mainIndex = layer.open({
                type:1,
                title:"修改房型",
                area: ["800px", "500px"],//窗口宽高
                content: $("#addOrUpdateWindow"),//引用的内容窗口
                success:function () {
                    //提交地址
                    url = "/admin/roomType/updateRoomType";
                    //数据回显
                    form.val("dataFrm",data);
                    //图片回显
                    $(".thumbImg").attr("src","/hotel/show/"+data.photo);
                }
            });
        }

        //监听表单提交事件
        form.on("submit(doSubmit)",function (data) {
            //发送请求
            $.post(url,data.field,function(result){
                if(result.success){
                    //提示
                    layer.alert(result.message,{icon:1});
                    //刷新当前数据表格
                    tableIns.reload();
                    //关闭当前窗口
                    layer.close(mainIndex);
                }else{
                    //提示
                    layer.alert(result.message,{icon:2});
                }
            },"json");
            return false;
        });

        /**
         * 删除房型
         * @param data
         */
        function deleteById(data) {
            //查询该房型是否存在房间信息
            $.get("/admin/roomType/checkRoomTypeHasRoom",{"roomTypeId":data.id},function(result){
                if(result.exist){
                    layer.alert(result.message,{icon:2});
                }else{
                    //提示用户是否删除该房型
                    layer.confirm("确定要删除[<font color='red'>"+data.typeName+"</font>]房型吗?",{icon:3,title:"提示"},function (index) {
                        //发送删除请求
                        $.post("/admin/roomType/deleteById",{"id":data.id},function(result){
                            if(result.success){
                                layer.alert(result.message,{icon:1});
                                //刷新数据表格
                                tableIns.reload();
                            }else{
                                layer.alert(result.message,{icon:2});
                            }
                        },"json");

                        layer.close(index);
                    });
                }
            },"json");
        }

    });
</script>

</body>
</html>

2.PageController.java

    /**
     * 去到房型管理页面
     * @return
     */
    @RequestMapping("/toRoomTypeManager")
    public String toRoomTypeManager(){
        return "roomType/roomTypeManager";
    }

3.数据库
在这里插入图片描述
或者直接在页面修改,修改后记得给超级管理员添加权限
在这里插入图片描述
在这里插入图片描述

16.2 房型管理的增删改查

16.2.1 实体类

RoomType.java

package com.manong.entity;

import lombok.Data;

@Data
public class RoomType {
    private Integer id;
    private String typeName;
    private String photo;
    private Double price;
    private Integer liveNum;
    private Integer bedNum;
    private Integer roomNum;
    private Integer reservedNum;
    private Integer avilableNum;
    private Integer livedNum;
    private Integer status;
    private String remark;
}

RoomTypeVo.java

package com.manong.vo;

import com.manong.entity.RoomType;
import lombok.Data;

@Data
public class RoomTypeVo extends RoomType {

    private Integer page;//当前页码
    private Integer limit;//每页显示数量

}

16.2.2 数据层

RoomTypeMapper.java

package com.manong.dao;

import com.manong.entity.RoomType;
import com.manong.vo.RoomTypeVo;


import java.util.List;

public interface RoomTypeMapper {

    /**
     * 查询房型列表
     * @param roomTypeVo
     * @return
     */
    List<RoomType> findRoomTypeList(RoomTypeVo roomTypeVo);

    /**
     * 添加房型
     * @param record
     * @return
     */
    int insert(RoomType record);

    /**
     * 修改房型
     * @param roomType
     * @return
     */
    int updateRoomType(RoomType roomType);

    /**
     * 根据房型ID查询该房型下的房间数量
     * @param roomTypeId
     * @return
     */
    int getRoomCountByRoomTypeId(Integer roomTypeId);

    /**
     * 删除房型
     * @param id
     * @return
     */
    int deleteById(Integer id);

}

RoomTypeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.manong.dao.RoomTypeMapper">

    <resultMap id="BaseResultMap" type="com.manong.entity.RoomType">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="typeName" jdbcType="VARCHAR" property="typeName" />
        <result column="photo" jdbcType="VARCHAR" property="photo" />
        <result column="price" jdbcType="DECIMAL" property="price" />
        <result column="liveNum" jdbcType="INTEGER" property="liveNum" />
        <result column="bedNum" jdbcType="INTEGER" property="bedNum" />
        <result column="roomNum" jdbcType="INTEGER" property="roomNum" />
        <result column="reservedNum" jdbcType="INTEGER" property="reservedNum" />
        <result column="avilableNum" jdbcType="INTEGER" property="avilableNum" />
        <result column="livedNum" jdbcType="INTEGER" property="livedNum" />
        <result column="status" jdbcType="INTEGER" property="status" />
        <result column="remark" jdbcType="VARCHAR" property="remark" />
    </resultMap>

    <insert id="insert">
        insert into t_room_type (typeName, photo,
          price, liveNum, bedNum,
          roomNum, reservedNum, avilableNum,
          livedNum, status, remark
          )
        values (#{typeName,jdbcType=VARCHAR}, #{photo,jdbcType=VARCHAR},
          #{price,jdbcType=DECIMAL}, #{liveNum,jdbcType=INTEGER}, #{bedNum,jdbcType=INTEGER},
          #{roomNum,jdbcType=INTEGER}, #{reservedNum,jdbcType=INTEGER}, #{avilableNum,jdbcType=INTEGER},
          #{livedNum,jdbcType=INTEGER}, #{status,jdbcType=INTEGER}, #{remark,jdbcType=VARCHAR}
          )
    </insert>

    <update id="updateRoomType">
        update t_room_type
        <set>
            <if test="typeName != null">
                typeName = #{typeName,jdbcType=VARCHAR},
            </if>
            <if test="photo != null">
                photo = #{photo,jdbcType=VARCHAR},
            </if>
            <if test="price != null">
                price = #{price,jdbcType=DECIMAL},
            </if>
            <if test="liveNum != null">
                liveNum = #{liveNum,jdbcType=INTEGER},
            </if>
            <if test="bedNum != null">
                bedNum = #{bedNum,jdbcType=INTEGER},
            </if>
            <if test="roomNum != null">
                roomNum = #{roomNum,jdbcType=INTEGER},
            </if>
            <if test="reservedNum != null">
                reservedNum = #{reservedNum,jdbcType=INTEGER},
            </if>
            <if test="avilableNum != null">
                avilableNum = #{avilableNum,jdbcType=INTEGER},
            </if>
            <if test="livedNum != null">
                livedNum = #{livedNum,jdbcType=INTEGER},
            </if>
            <if test="status != null">
                status = #{status,jdbcType=INTEGER},
            </if>
            <if test="remark != null">
                remark = #{remark,jdbcType=VARCHAR},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>

    <delete id="deleteById">
        delete from t_room_type where id = #{id}
    </delete>

    <select id="findRoomTypeList" resultMap="BaseResultMap">
        select * from t_room_type
        <where>
            <if test="typeName!=null and typeName!=''">
                and typeName like concat('%',#{typeName},'%')
            </if>
        </where>
    </select>

    <select id="getRoomCountByRoomTypeId" resultType="int">
        select count(1) from t_room where `roomTypeId` = #{roomTypeId}
    </select>

</mapper>

16.2.3 业务层

RoomTypeService.java

package com.manong.service;

import com.manong.entity.RoomType;
import com.manong.vo.RoomTypeVo;

import java.util.List;

public interface RoomTypeService {
    /**
     * 查询房型列表
     * @param roomTypeVo
     * @return
     */
    List<RoomType> findRoomTypeList(RoomTypeVo roomTypeVo);

    /**
     * 添加房型
     * @param record
     * @return
     */
    int insert(RoomType record);

    /**
     * 修改房型
     * @param roomType
     * @return
     */
    int updateRoomType(RoomType roomType);

    /**
     * 根据房型ID查询该房型下的房间数量
     * @param roomTypeId
     * @return
     */
    int getRoomCountByRoomTypeId(Integer roomTypeId);

    /**
     * 删除房型
     * @param id
     * @return
     */
    int deleteById(Integer id);
}

RoomTypeServiceImpl.java

package com.manong.service.impl;

import com.alibaba.fastjson.JSON;
import com.manong.dao.RoomTypeMapper;
import com.manong.entity.RoomType;
import com.manong.service.RoomTypeService;
import com.manong.utils.JedisPoolUtils;
import com.manong.utils.RedisKey;
import com.manong.vo.RoomTypeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class RoomTypeServiceImpl implements RoomTypeService {

    @Resource
    private RoomTypeMapper roomTypeMapper;

    /**
     * 查询房型列表
     *
     * @param roomTypeVo
     * @return
     */
    public List<RoomType> findRoomTypeList(RoomTypeVo roomTypeVo) {
        return roomTypeMapper.findRoomTypeList(roomTypeVo);
    }

    public int insert(RoomType roomType) {
        //设置已预订数量
        roomType.setReservedNum(0);
        //设置可入住房间数量
        roomType.setAvilableNum(roomType.getRoomNum());
        //设置已入住房间数量
        roomType.setLivedNum(0);
        return roomTypeMapper.insert(roomType);
    }

    public int updateRoomType(RoomType roomType) {
        //修改可用房间数
        roomType.setAvilableNum(roomType.getRoomNum());
        return roomTypeMapper.updateRoomType(roomType);
    }

    public int getRoomCountByRoomTypeId(Integer roomTypeId) {
        return roomTypeMapper.getRoomCountByRoomTypeId(roomTypeId);
    }

    public int deleteById(Integer id) {
        return roomTypeMapper.deleteById(id);
    }

}

16.2.4 控制层

RoomTypeController.java

package com.manong.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.manong.entity.RoomType;
import com.manong.service.RoomTypeService;
import com.manong.utils.DataGridViewResult;
import com.manong.utils.SystemConstants;
import com.manong.utils.UUIDUtils;
import com.manong.vo.RoomTypeVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/roomType")
public class RoomTypeController {

    @Resource
    private RoomTypeService roomTypeService;


    @RequestMapping("/list")
    public DataGridViewResult list(RoomTypeVo roomTypeVo){
        PageHelper.startPage(roomTypeVo.getPage(),roomTypeVo.getLimit());
        List<RoomType> roomTypeList = roomTypeService.findRoomTypeList(roomTypeVo);
        PageInfo<RoomType> pageInfo = new PageInfo<RoomType>(roomTypeList);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }


    /**
     * 添加房型
     * @param roomType
     * @return
     */
    @RequestMapping("/addRoomType")
    public String addRoomType(RoomType roomType){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roomTypeService.insert(roomType)>0){
            map.put(SystemConstants.SUCCESS,true);
            map.put(SystemConstants.MESSAGE,"添加成功");
        }else{
            map.put(SystemConstants.SUCCESS,false);
            map.put(SystemConstants.MESSAGE,"添加失败");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 修改房型
     * @param roomType
     * @return
     */
    @RequestMapping("/updateRoomType")
    public String updateRoomType(RoomType roomType){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roomTypeService.updateRoomType(roomType)>0){
            map.put(SystemConstants.SUCCESS,true);
            map.put(SystemConstants.MESSAGE,"修改成功");
        }else{
            map.put(SystemConstants.SUCCESS,false);
            map.put(SystemConstants.MESSAGE,"修改失败");
        }
        return JSON.toJSONString(map);
    }


    /**
     * 检查该房型下是否存在房间
     * @param roomTypeId
     * @return
     */
    @RequestMapping("/checkRoomTypeHasRoom")
    public String checkRoomTypeHasRoom(Integer roomTypeId){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roomTypeService.getRoomCountByRoomTypeId(roomTypeId)>0){
            map.put(SystemConstants.EXIST,true);
            map.put(SystemConstants.MESSAGE,"该房型下存在房间信息,无法删除");
        }else{
            map.put(SystemConstants.EXIST,false);
        }
        return JSON.toJSONString(map);
    }

    /**
     * 删除房型
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    public String deleteById(Integer id){
        Map<String,Object> map = new HashMap<String,Object>();
        if(roomTypeService.deleteById(id)>0){
            map.put(SystemConstants.SUCCESS,true);
            map.put(SystemConstants.MESSAGE,"删除成功");
        }else{
            map.put(SystemConstants.SUCCESS,false);
            map.put(SystemConstants.MESSAGE,"删除失败");
        }
        return JSON.toJSONString(map);
    }

 

}

16.3 添加房型窗口的图片上传功能

在这里插入图片描述

1.roomTypeManager.jsp
在这里插入图片描述

2.RoomTypeController.java,记得修改文件上传路径

 @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile attach){
        //创建Map集合保存数据(响应到前台页面的数据)
        Map<String,Object> map = new HashMap<String,Object>();
        //判断是否有选中文件
        if(!attach.isEmpty()){
            //获取文件上传地址
            String path = "E:/ssm_hotel/upload/";
            //获取源文件名称
            String oldName = attach.getOriginalFilename();
            //获取文件后缀名
            String extension = FilenameUtils.getExtension(oldName);
            //重命名文件名称
            String newFileName = UUIDUtils.randomUUID()+"."+extension;
            //为了解决同一个文件夹下文件过多的问题,使用日期作为文件夹管理
            String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
            //组装最终的文件名
            String finalName = datePath + "/" + newFileName;
            //创建文件对象
            File destFile = new File(path,finalName);
            //判断文件夹是否存在,文件夹不存在则创建该文件夹
            if(!destFile.getParentFile().exists()){
                destFile.getParentFile().mkdirs();
            }
            try {
                //将文件保存到硬盘
                attach.transferTo(destFile);
                //保存响应的数据
                map.put("code",0);
                map.put("msg","");
                Map<String,Object> dataMap = new HashMap<String,Object>();
                dataMap.put("src","/hotel/show/"+finalName);//文件上传成功的回显地址
                map.put("data",dataMap);
                map.put("imagePath",finalName);//图片名称,目的是给photo隐藏域赋值
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JSON.toJSONString(map);
    }

3.设置
在这里插入图片描述
选择本地图片的位置,就是之前**/ssm_hote/upload
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值