为用户分配角色及将js 数组转化为字符串数组传给后端,后端接受并使用(学习笔记)

为用户分配角色及将js 数组转化为字符串数组传给后端,后端接受并使用
在这里插入图片描述

示例:

编辑user.html,修改点击在这里插入图片描述
按钮,跳转到角色分配页面assignRole.html
在这里插入图片描述

1.静态资源
1.1.它们三个可官网下载:
我的百度网盘:
链接:https://pan.baidu.com/s/17TzgQX0OVSef49aAawXf6w
提取码:0mqm

在这里插入图片描述
1.2.主启动类 CrowdManagerApplication.java:
在这里插入图片描述

1.3.工具类 ResultEntity.java:

public class ResultEntity<T> {
    //常量
    public static final String CODE_SUCCESS="SUCCESS";
    public static final String CODE_FAILED="FAILED";

    //设定状态码,前端根据状态码,判断成功、失败的响应
    private String code;
    //返回的消息
    private String msg;
    //回显的数据
    T data;

    //成功,并返回消息
    public static ResultEntity successWithData(Object data){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_SUCCESS;
        tResultEntity.setData(data);
        return tResultEntity;
    }

    //失败,并返回消息
    public static ResultEntity failedWithData(Object data){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_FAILED;
        tResultEntity.setData(data);
        return tResultEntity;
    }

    //成功,并返回消息
    public static ResultEntity successWithData(String msg,Object data){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_SUCCESS;
        tResultEntity.setMsg(msg);
        tResultEntity.setData(data);
        return tResultEntity;
    }

    //失败,并返回消息
    public static ResultEntity failedWithData(String msg,Object data){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_FAILED;
        tResultEntity.setMsg(msg);
        tResultEntity.setData(data);
        return tResultEntity;
    }

    //成功
    public static ResultEntity success(){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_SUCCESS;
        return tResultEntity;
    }

    //失败
    public static ResultEntity failed(){
        ResultEntity<Object> tResultEntity = new ResultEntity<>();
        tResultEntity.code=CODE_FAILED;
        return tResultEntity;
    }

    public ResultEntity() {
        super();
    }

    public ResultEntity(String code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

注:部分代码省略

2.user.html模板:
该模板中只用到该连接,点击角色分配按钮进行页面跳转

<a type="button" class="btn btn-success btn-xs" th:href="@{/assignRole.html(id=${manager.id})}"><i
        class=" glyphicon glyphicon-check" ></i></a>

3.assignRole.html模板:
注意:css、js等静态资源映入的顺序

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

	<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
	<link rel="stylesheet" th:href="@{/css/font-awesome.min.css}">
	<link rel="stylesheet" th:href="@{/css/main.css}">
	<link rel="stylesheet" th:href="@{/css/doc.min.css}">
	<style>
	.tree li {
        list-style-type: none;
		cursor:pointer;
	}
	</style>
  </head>

  <body>

  <!--导航模块-->
  <div th:replace="common :: nav"></div>

    <div class="container-fluid">
      <div class="row">
		  <!--左侧菜单-->
		  <div th:replace="common :: left(lv1='null',lv2='user.html')"></div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
				<ol class="breadcrumb">
				  <li><a th:href="@{/#}">首页</a></li>
				  <li><a th:href="@{/#}">数据列表</a></li>
				  <li class="active">分配角色</li>
				</ol>
			<div class="panel panel-default">
			  <div class="panel-body">
				<form role="form" class="form-inline">
				  <div class="form-group" >
					  <!--result.data.assginRoles      result.data.unAssginRoles-->
					<label for="">未分配角色列表</label><br>
					<select id="unassignList" class="form-control" multiple size="10" style="width:100px;overflow-y:auto;">
                        <option th:value="${unAssginRole.id}" th:text="${unAssginRole.name}" th:each="unAssginRole : ${result.data.unAssginRoles}"></option>
                    </select>
				  </div>
				  <div class="form-group">
                        <ul>
                            <li id="rightBtn" class="btn btn-default glyphicon glyphicon-chevron-right"></li>
                            <br>
                            <li id="leftBtn" class="btn btn-default glyphicon glyphicon-chevron-left" style="margin-top:20px;"></li>
                        </ul>
				  </div>
				  <div class="form-group" style="margin-left:40px;" >
					<label for="">已分配角色列表</label><br>
					<select id="assignList" class="form-control" multiple size="10" style="width:100px;overflow-y:auto;">
                        <option th:value="${assginRole.id}" th:text="${assginRole.name}" th:each="assginRole : ${result.data.assginRoles}"></option>
                    </select>
				  </div>
				</form>
				  <button id="commitBtn" class="btn btn-success">分配角色</button>
			  </div>
			</div>
        </div>
      </div>
    </div>

    <script th:src="@{/jquery/jquery-2.1.1.min.js}"></script>
  	<script th:src="@{/layer/layer.js}"></script>
    <script th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
	<script th:src="@{/script/docs.min.js}"></script>
        <script type="text/javascript">
            $(function () {
				//为提交修改角色绑定按钮commitBtn
            	$("#commitBtn").click(function () {
					//1、获取右侧已分配的角色们的ID
					// 选中右侧所有已分配的选项们
					$("#assignList>option").prop("selected","selected");
					var assignValues = $("#assignList").val();
					var ids="";
					$(assignValues).each(function(index,value){
						ids+=value+",";
					});
					ids= ids.substring(0,ids.length-1);
					//2、异步提交
					$.ajax({
						url:"[[@{/assignRoles.json}]]",
						data:{
							"managerId":[[${param.id}]],
							"ids":ids
						},
						type:"POST",
						dataType:"json",
						success:function(result){
							if(result.code == 'SUCCESS'){
								layer.msg('分配成功', {
									icon: 6
								});
							}else{
								layer.msg('分配失败', {
									icon: 6
								});
							}
						}
					});
				});
				//向左、向右
				$("#rightBtn").click(function () {
					$("#unassignList>option:selected").appendTo("#assignList");
				});
				$("#leftBtn").click(function () {
					$("#assignList>option:selected").appendTo("#unassignList");
				}); 
            });
        </script>
  </body>
</html>

4.RoleController.java控制层:

@RestController
public class RoleController {
    @Autowired
    RoleService roleService;

    //通过id为manager分配角色
    @PostMapping("/assignRoles.json")
    public ResultEntity assignRoles(String managerId,String ids){
        String[] split = ids.split(",");
        List<String> roleIds = Arrays.asList(split);
        boolean b= roleService.assignRoles(managerId,roleIds);
        if (b) {
            return ResultEntity.success();
        }else{
            return ResultEntity.failed();
        }
    }
}

5.RoleService.java接口类:

public interface RoleService extends IService<Role> {

    boolean assignRoles(String managerId, List<String> roleIds);
}

6.RoleServiceImpl.java实现类:

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    RoleMapper roleMapper;

    @Override
    public boolean assignRoles(String managerId, List<String> roleIds) {
        //分配角色
        //1、应该将表中原来的该用户的角色清空
        boolean b1 =  roleMapper.deleteRoleIdsByManagerId(managerId);

        //2、插入新的用户:角色
        boolean b2 =  roleMapper.insertManagerIdRoleId(managerId,roleIds);
        return b1 && b2;
    }
}

7.RoleMapper.java

public interface RoleMapper extends BaseMapper<Role> {
	boolean deleteRoleIdsByManagerId(String managerId);

    boolean insertManagerIdRoleId(@Param("id") String managerId, @Param("roleIds")List<String> roleIds);
}

8.RoleMapper.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.kmu.mapper.RoleMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.kmu.entity.Role">
        <id column="id" property="id" />
        <result column="name" property="name" />
    </resultMap>

    <delete id="deleteRoleIdsByManagerId">
        delete from inner_manager_role where manager_id = #{managerId}
    </delete>

    <insert id="insertManagerIdRoleId">
        insert inner_manager_role values
        <foreach collection="roleIds" item="roleId" separator=",">
            (#{id},#{roleId})
        </foreach>
    </insert>
</mapper>

将js 数组转化为字符串数组传给后端,后端接受并使用:
后端接受:
在这里插入图片描述
前端Ajax发送:
在这里插入图片描述
9.application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kmu_crowd?characterEncoding=utf8
    username: root
    password: root

10.pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kmu</groupId>
    <artifactId>crowd-manager</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>crowd-manager</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.7</version>
        </dependency>

        <!--mybatisPlus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>**/*.woff</exclude>
                    <exclude>**/*.woff2</exclude>
                    <exclude>**/*.ttf</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <includes>
                    <include>**/*.woff</include>
                    <include>**/*.woff2</include>
                    <include>**/*.ttf</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值