In the last chapter, we completed the RMS background management system. In this chapter, we will implement the function of inputting game configuration on this system. Currently we need to configure four items, character attributes for each level, upgrade experience for each level, game map, and monsters in the map. Here we take the game map configuration as an example to realize the function of adding, deleting and checking it.

Implementation of data access layer

First, we need to define the map class, which is common across modules, and therefore in the Facade module. Create a package com.idlewow.map.model and create a WowMap class in it.

package com.idlewow.map.model;

import com.idlewow.common.model.BaseModel;
import lombok.Data;

import java.io.Serializable;

@Data
public class WowMap extends BaseModel implements Serializable {
    private String name;
    private Integer occupy;
    private String description;
}
Copy the code

Then, we implement the logic of the data access layer in the core module. Create com.idlewow.map.mapper package, and create an interface class WowMapMapper, in the interface definition we need to use some add, delete, check and change methods, the code is as follows:

package com.idlewow.map.mapper;

import com.idlewow.map.model.WowMap;
import com.idlewow.query.model.WowMapQueryParam;

import java.util.List;

public interface WowMapMapper {
    int insert(WowMap wowMap);

    int batchInsert(List<WowMap> list);

    int update(WowMap levelProp);

    int delete(String id);

    WowMap find(String id);

    List<WowMap> list(WowMapQueryParam queryParam);

    int count(WowMapQueryParam queryParam);
}
Copy the code

Mapper interface class, only defines the method, the concrete implementation requires us to create a wowMapmapper. XML file under the package, in this file, through SQL statements to implement the method in the interface:

<? The 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.idlewow.map.mapper.WowMapMapper"> <resultMap id="BaseResultMap" type="com.idlewow.map.model.WowMap"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="occupy" property="occupy"/> <result column="description" property="description"/> <result column="create_user" property="createUser"/> <result column="update_user" property="updateUser"/> <result column="create_time" property="createTime"/> <result column="update_time" property="updateTime"/> <result column="is_delete" property="isDelete"/> <result column="version" property="version"/> </resultMap> <! <insert ID ="insert"> insert into map (name, Occupy, description, create_user) values (#{name}, #{occupy}, #{description}, #{createUser}) </insert> <! <insert ID ="batchInsert"> insert into map (name, Occupy, description, create_user) values <foreach collection="list" item="item" separator=","> (#{item.name}, #{item.occupy}, #{item.description}, #{item.createUser}) </foreach> </insert> <! <update ID ="update"> Update map set name = #{name}, Occupy = #{Occupy}, description = #{description}, update_user = #{updateUser}, version = version + 1 where id = #{id} and is_delete = 0 </update> <! ParameterType ="String"> update map set is_delete = 1 where id= #{id} </update> <! <select id="find" resultMap="BaseResultMap"> select * from map where id= #{id} and is_delete = 0 <! <select id="count" resultType="int"> select count(1) from map <where> is_delete = 0 <if test="name! = null and name ! = ''"> and name like concat('%', #{name}, '%') </if> </where> </select> <! <select id="list" resultMap="BaseResultMap"> select * from map <where> is_delete = 0 <if test="name! = null and name ! = ''"> and name like concat('%', #{name}, '%') </if> </where> <if test="pageParam ! = null"> limit ${(pageParam.pageIndex - 1) * pageParam.pageSize}, ${pageParam.pageSize} </if> </select> </mapper>Copy the code

WowMapMapper.xml

Finally, we create a new com.idlewow.map.manager package and create a new class WowMapManager, which uses Mapper to implement specific services:

package com.idlewow.map.manager; import com.idlewow.common.model.PageList; import com.idlewow.map.mapper.WowMapMapper; import com.idlewow.map.model.WowMap; import com.idlewow.query.model.WowMapQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; @Component public class WowMapManager { @Autowired WowMapMapper wowMapMapper; public void insert(WowMap wowMap) { int effected = wowMapMapper.insert(wowMap); if (effected == 0) { throw new RuntimeException("sql effected 0 rows"); } } public void batchInsert(List<WowMap> list) { int splitSize = 100; int index = 0; int total = list.size(); while (index <= total) { int end = index + splitSize; if (end > total) { end = total; } List<WowMap> sublist = list.subList(index, end); int effected = wowMapMapper.batchInsert(sublist); if (effected == 0) { throw new RuntimeException("sql effected 0 rows"); } index += splitSize; } } public void update(WowMap t) { int effected = wowMapMapper.update(t); if (effected == 0) { throw new RuntimeException("sql effected 0 rows"); } } public void delete(String id) { int effected = wowMapMapper.delete(id); if (effected == 0) { throw new RuntimeException("sql effected 0 rows"); } } public WowMap find(String id) { WowMap wowMap = wowMapMapper.find(id); return wowMap; } public PageList<WowMap> list(WowMapQueryParam queryParam) { PageList<WowMap> pageList = new PageList<WowMap>(); int count = wowMapMapper.count(queryParam); List<WowMap> list = wowMapMapper.list(queryParam); pageList.setTotalCount(count); pageList.setData(list); pageList.setPageParam(queryParam.getPageParam()); return pageList; }}Copy the code

In addition, the @Componet annotation needs to rely on the Spring-Context package. In addition, the XML file we write SQL is a resource file, but for the convenience of viewing and editing, we directly put it in the code directory, so it will not be packaged when compiling. We need to add the following configuration in POM:

</dependencies> ........ . <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.6.RELEASE</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> </resources> </build>Copy the code

At this point, our data access layer logic is fully implemented. Access to the underlying data is achieved by injecting the Manager into the CONTROLLER of the RMS module.

2. Implementation of controller layer

In com. Idlewow. RMS. The controller in the package, a new kind of MapController, in Contoller, we add or delete the data check change was preliminarily realized. Note the list () method, which returns the string “/ manage/map/list”, on behalf of the view in the path, according to the spring – the MVC. XML configuration view routing parsing rules, namely return/WEB – INF/views/manage/map/list. The JSP page. But if you annotate this method with @responseBody, it means that the string is returned directly, without looking for the view. In the POST method, we just return a JSON string of data directly. The code is as follows:

package com.idlewow.rms.controller; import com.idlewow.common.model.CommonResult; import com.idlewow.common.model.PageList; import com.idlewow.map.manager.WowMapManager; import com.idlewow.map.model.WowMap; import com.idlewow.query.model.WowMapQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/manage/map") public class MapController extends BaseController { @Autowired WowMapManager wowMapManager; @RequestMapping("/list") public Object list() { return "/manage/map/list"; } @ResponseBody @RequestMapping(value = "/list", method = RequestMethod.POST) public Object list(@RequestParam(value = "page", defaultValue = "1") int pageIndex, @RequestParam(value = "limit", defaultValue = "10") int pageSize, WowMapQueryParam queryParam) { queryParam.setPage(pageIndex, pageSize); PageList<WowMap> pageList = wowMapManager.list(queryParam); return this.parseTable(pageList); } @RequestMapping("/add") public Object add() { return "/manage/map/add"; } @ResponseBody @RequestMapping(value = "/add", method = RequestMethod.POST) public Object add(@RequestBody WowMap wowMap) { try { wowMap.setCreateUser(this.currentUserName()); wowMapManager.insert(wowMap); return CommonResult.success(); } catch (Exception ex) { return CommonResult.fail(); } } @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public Object edit(@PathVariable String id, Model model) { WowMap wowMap = wowMapManager.find(id); model.addAttribute(wowMap); return "/manage/map/edit"; } @ResponseBody @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public Object edit(@PathVariable String id, @RequestBody WowMap wowMap) { try { if (! Id.equals (wowmap.getid ())) {return commonResult.fail (" ID not consistent "); } wowMap.setUpdateUser(this.currentUserName()); wowMapManager.update(wowMap); return CommonResult.success(); } catch (Exception ex) { return CommonResult.fail(); } } @ResponseBody @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) public Object delete(@PathVariable String id) { try { wowMapManager.delete(id); return CommonResult.success(); } catch (Exception ex) { return CommonResult.fail(); }}}Copy the code

MapController.java

The CommonResult class is a generic result return class I defined, PageList and PageParam are page-related helper classes, and WowMapQueryParam is a parameter class for list queries.

In addition, the front end list shows the datatable using Layui and needs to return the corresponding data structure to it. Therefore, we define an abstract class BaseController that transforms the list data structure and provides methods to query the currently logged user. Other controllers inherit BaseController unless otherwise specified. The code is as follows:

package com.idlewow.rms.vo;

import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
public class LayuiDataTable<T> implements Serializable {
    private Integer code;
    private String message;
    private Integer count;
    private List<T> data;
}
Copy the code

LayuiDataTable.java

package com.idlewow.rms.controller; import com.idlewow.admin.model.SysAdmin; import com.idlewow.common.model.PageList; import com.idlewow.rms.vo.LayuiDataTable; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpSession; public abstract class BaseController { private static final String LoginUserKey = "loginuser"; @Autowired protected HttpSession httpSession; protected SysAdmin currentUser() { return (SysAdmin) httpSession.getAttribute(LoginUserKey); } protected String currentUserName() { return this.currentUser().getUsername(); } protected LayuiDataTable parseTable(PageList pageList) { LayuiDataTable dataTable = new LayuiDataTable(); Datatable. setMessage(" Read successfully "); dataTable.setCode(0); dataTable.setCount(pageList.getTotalCount()); dataTable.setData(pageList.getData()); return dataTable; }}Copy the code

BaseController.java

After writing the controller, the front page, we directly apply the X-Admin template. Create a page in /WEB-INF/views/manage/map:

<%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ include file="/authorize.jsp" %> <! DOCTYPE HTML > < HTML class="x-admin-sm"> <head> <meta charset=" utF-8 "> <title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" The content = "width = device - width, user - scalable = yes, minimum - scale = 0.4, /> <link rel="stylesheet" href="<%=path%>/ CSS /font. CSS "> <link rel="stylesheet" href="<%=path%>/css/xadmin.css"> <script type="text/javascript" src="<%=path%>/lib/layui/layui.js" charset="utf-8"></script> <script type="text/javascript" src="<%=path%>/js/xadmin.js"></script> </head> <body> <div Class = "x - nav" > < span class = "layui - breadcrumb" > < a href = "" > home page < / a > < a href =" "> background management < / a > < a > < cite > map < cite > < / a > < / span > < a Class = "layui - BTN layui BTN - small" style = "line - height: 1.6 em; margin-top:3px; Float :right" onclick="location.reload()" title=" refresh" > < I class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a> </div> <div class="layui-fluid"> <div class="layui-row layui-col-space15"> <div class="layui-col-md12"> <div class="layui-card"> <div class="layui-card-body "> <form id="queryForm" class="layui-form layui-col-space5" method="post"> <div class="layui-inline layui-show-xs-block"> <input type="text" name="name" Placeholder =" please input map name "autocomplete="off" class="layui-input"> </div> <div class="layui-inline layui-show-xs-block"> <button class="layui-btn" lay-submit lay-filter="search" type="button" onclick="search();" > <i class="layui-icon">&#xe615; </ I > query </button> <div class="layui-inline layui-show-xs-block"> <button class="layui-btn" type="button" onclick="reset();" </button> <div > <div class="layui-inline layui-show-xs-block"> <button type="button" class="layui-btn" Onclick ="xadmin.open(' add map ','add',500,500)"> < I class="layui-icon"></ I > add map </button> </div> <div class="layui-upload layui-inline layui-show-xs-block"> <button type="button" class="layui-btn layui-btn-normal" Id ="btnSelectFile"> Select Excel</button> <button type="button" class="layui-btn" id="btnImport"> </button> </div> </form> </div> <div class="layui-card-body "> <table class="layui-table layui-form" id="datatable"></table> </div> </div> </div>  </div> </div> </body> <script type="text/javascript" src="<%=path%>/js/helper.js? v=0530"></script> <script type="text/javascript" src="<%=path%>/js/wow/manage/map/list.js? v=0530"></script> </html>Copy the code

list.jsp

<%@ page import="com.idlewow.rms.util.DropDownUtil" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ include file="/authorize.jsp" %> <! DOCTYPE HTML > < HTML class="x-admin-sm"> <head> <meta charset=" utF-8 "> <title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" The content = "width = device - width, user - scalable = yes, minimum - scale = 0.4, /> <link rel="stylesheet" href="<%=path%>/ CSS /font. CSS "> <link rel="stylesheet" href="<%=path%>/css/xadmin.css"> <script type="text/javascript" src="<%=path%>/lib/layui/layui.js" charset="utf-8"></script> <script type="text/javascript" src="<%=path%>/js/xadmin.js"></script> </head> <body> <div class="layui-fluid"> <div class="layui-row"> <form:form class="layui-form" method="post" modelAttribute="wowMap"> <form:hidden path="id"/> <div class="layui-form-item"> <form:label path="name" class="layui-form-label"> <span Class ="x-red">*</span> map name </form:label> <div class="layui-input-inline"> <form:input path="name" lay-verify="required" autocomplete="off" class="layui-input"/> </div> </div> <div class="layui-form-item"> <form:label path="occupy" Class ="layui-form-label"> < SPAN class=" X-red ">*</ SPAN > Territorial attribution </form:label> <div class="layui-input-inline"> <form:select path="occupy" items="<%= DropDownUtil.OccupyMap %>"></form:select> </div> </div> <div class="layui-form-item"> <form:label path="description" class="layui-form-label"> map description </form:label> <form:textarea path="description" class="layui-textarea"></form:textarea> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"></label> <div class="layui-input-inline"> <button class="layui-btn" lay-filter="edit" </form:form> </div> </div> <script type="text/javascript" src="<%=path%>/js/helper.js? v=0531"></script> <script type="text/javascript" src="<%=path%>/js/wow/manage/map/edit.js? v=0510"></script> </body> </html>Copy the code

edit.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page import="com.idlewow.rms.util.DropDownUtil" %> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <%@ include file="/authorize.jsp" %> <! DOCTYPE HTML > < HTML class="x-admin-sm"> <head> <meta charset=" utF-8 "> <title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" The content = "width = device - width, user - scalable = yes, minimum - scale = 0.4, /> <link rel="stylesheet" href="<%=path%>/ CSS /font. CSS "> <link rel="stylesheet" href="<%=path%>/css/xadmin.css"> <script type="text/javascript" src="<%=path%>/lib/layui/layui.js" charset="utf-8"></script> <script type="text/javascript" src="<%=path%>/js/xadmin.js"></script> </head> <body> <div class="layui-fluid"> <div class="layui-row"> <form class="layui-form" method="post"> <div class="layui-form-item"> <label for="name" class="layui-form-label"> <span class="x-red">*</span> map name </label> <div class="layui-input-inline"> <input type="text" id="name" name="name" required lay-verify="required" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <label for=" Occupy "class="layui-form-label"> < SPAN class=" X-red ">*</ SPAN > Territorial ownership </label> <div class="layui-input-inline"> <% request.setAttribute("occupyMap", DropDownUtil.OccupyMap); %> <select name=" Occupy "ID =" Occupy "> <option value=""> Please select the ownership of territory </option> <c:forEach items="${occupyMap}" var="item > <option value="${item.key}">${item.value}</option> </c:forEach> </select> </div> </div> <div class="layui-form-item"> <label for="description" class="layui-form-label"> map description </label> <div class="layui-input-inline"> <textarea name="description" id="description" class="layui-textarea"></textarea> </div> </div> <div class="layui-form-item"> <label class="layui-form-label"></label> <div class="layui-input-inline"> <button class="layui-btn" lay-filter="add" </button> </div> </form> </div> </div> </div> <script type="text/javascript" src="<%=path%>/js/helper.js? v=0531"></script> <script type="text/javascript" src="<%=path%>/js/wow/manage/map/add.js? v=0531"></script> </body> </html>Copy the code

add.jsp

Create the appropriate JS script under /js/wow/manage/map:

layui.use(['upload', 'table', 'form'], function () { var table = layui.table; table.render({ elem: '#datatable' , url: '/manage/map/list' , method: 'post' , cellMinWidth: 80 , cols: [[ {field: 'id', width: 50, title: 'id', {field: 'name', title: 'map name'}, {field:' Occupy ', title: 'territory ownership ', templet: Function (d) {return enumUtil. Occupy (d.occupy) + enumUtil. Occupy (d.occupy);}}, {title: 'occupy ', templet: Function (d) {return '<button class=" button layui-btn layui-btn-xs" onclick="xadmin.open(\' edit map \',\'edit/' + d.id + '\', 500, </ I > edit </ I >' + '<button class="layui-btn-danger Layui-btn layui-btn-xs" onclick="remove(this, D.i \ '+ d +' \ ') "type =" button "> < I class =" layui - icon "> & # xe640; < / I > delete < / button >";}}]], page: {layout: [' limit ', 'count', 'prev' and 'page' and 'next' and 'skip'] / / custom page layout, limits: [10, 20, 30, 40, 50], groups: 3 // display only one consecutive page, first: 'first', last: 'last'}}); }); function search() { var table = layui.table; table.reload('datatable', { where: { name: $('input[name="name"]').val() }, page: { curr: 1 } }); } function reset(){ $('#queryForm').reset(); } function remove(obj, id) {layer.confirm(' do you want to delete? ', function () { $.ajax({ url: '/manage/map/delete/' + id, type: 'post', success: function (result) { if (result.code === 1) { $(obj).parents("tr").remove(); Layer. MSG (' delete successfully ', {icon: 1, time: 1000}); } else {layer.alert(" delete failed ", {icon: 5}); }}, error: function () {layer.alert(" request failed ", {icon: 5}); }}); }); }Copy the code

list.js

layui.use(['form', 'layer'], function () { var form = layui.form; form.render(); form.verify({}); form.on('submit(edit)', function (data) { $.ajax({ url: '/manage/map/edit/' + data.field.id, type: 'post', contentType: "application/json; charset=utf-8", data: JSON.stringify(data.field), success: function (result) { if (result.code === 1) { layer.alert(result.message, {icon: 6}, function () { xadmin.close(); xadmin.father_reload(); }); } else { layer.alert(result.message, {icon: 5}); }}, error: function () {layer.alert(" request failed ", {icon: 5}); }}); }); });Copy the code

edit.js

layui.use(['form', 'layer'], function () { var form = layui.form; form.verify({}); form.on('submit(add)', function (data) { $.ajax({ url: '/manage/map/add', type: 'post', contentType: "application/json; charset=utf-8", data: JSON.stringify(data.field), success: function (result) { if (result.code === 1) { layer.alert(result.message, {icon: 6}, function () { xadmin.close(); xadmin.father_reload(); }); } else { layer.alert(result.message, {icon: 5}); }}, error: function () {layer.alert(" request failed ", {icon: 5}); }}); }); });Copy the code

add.js

Iii. Project launch

This time, we changed the facade and core projects, which were referenced as JAR packages by the RMS module and therefore had to be compiled and packaged first. Here we repackaged the entire project directly using the package command defined in Chapter (2). In the future, any jar package project changes, we will repackage the web project before starting.

In addition, the default plugin for Maven may be JDK 1.5. Let’s configure it to 1.8 in poM.

<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> ………… ..................... </plugins> </build>Copy the code

OK, when all is done, let’s run it and see what it looks like:

  

 

summary

In this chapter, we have preliminarily realized the adding, deleting, checking and modifying of data configuration of background management system, but there are still many imperfect functions.

For example, data added and edited is not verified; It is too troublesome to input data individually, so I want to input data in batches through Excel. Lack of logging when exceptions occur, and so on.

These are all things that we will continue to refine in later chapters.

This chapter source code download address: idlestudio.ctfile.com/fs/14960372…

In this paper, the original address: www.cnblogs.com/lyosaki88/p…