用户登录实验

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ironhide1994/article/details/79465291

本实验完成用户管理功能。用户在登录页面输入账号进行登录,如果验证通过则跳转到用户列表展示页面,验证失败跳转到失败页面。用户管理实验包括对用的增删改查的操作;该实验涉及到主从表的内容,包含主表用户表和从表用户详细信息表。此外,本实验的前端样式使用bootstrap,表格使用datatables.js。

通过用户管理实验,完整的介绍了Spring MVC框架从视图-控制器-模型的整个流程。借此,熟悉从前端数据请求到后台数据的持久化的运转逻辑,有助于加强对MVC思想的掌握。

第一步、编写用户列表前端页面代码

在jsp的demo目录下添加queryuser.jsp文件。queryuser.jsp文件用来作为该项目的前端页面展示,也即view视图层。下面添加静态页面代码。复制如下代码到queryuser.jsp文件中。

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>

<!DOCTYPE html>

<html>

   <head>

      <meta http-equiv="Content-Type" content="text/html";charset=UTF-8">

      <title>用户详细信息</title>

      <!-- 引入css文件 -->

      <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/skin/css/bootstrap.css">

      <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/skin/css/datatables.css">

      <!-- 引入js文件 -->

      <script type="text/javascript" src="<%=request.getContextPath()%>/skin/js/jquery.js"></script>

      <script type="text/javascript" src="<%=request.getContextPath()%>/skin/js/datatables.js"></script>

      <script type="text/javascript" src="<%=request.getContextPath()%>/skin/js/queryuser.js"></script>

   </head>

   <body class="container">

      <div class="input-group" style="margin-top:10px;">

         <div class="input-group col-xs-6 col-md-6">

            <input type="text" id="searchVal" class="form-control" style="width:200px;" placeholder="请输入用户ID">

            <span class="input-group-btn">

                <button class="btn btn-default" type="button" id="search">

                   搜索

                </button>

            </span>

         </div>

       </div>

       <div class="btn-group pull-right" style="margin-top:-35px;padding-bottom:5px;">

         <button type="button" class="btn btn-primary" id="addusers">新增</button>

      </div>

      <div>

         <table id="userList" class="table table-bordered table-hover">

            <thead>

                <tr>

                   <th width="20">用户ID</th>

                   <th width="20">名称</th>

                   <th width="20">昵称</th>

                   <th width="20">是否管理员</th>

                   <th width="20">操作</th>

                </tr>

            </thead>

         </table>

      </div>

   </body>

   <script type="text/javascript">

      var context = "<%=request.getContextPath()%>";

   </script>

</html>

接下来我们添加用户的新增页面在demo文件夹下添加adduser.jsp文件。该页面用来增加新的用户。复制如下代码:

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>

<!DOCTYPE>

<html>

   <head>

      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

      <title>新增用户</title>

      <!-- 引入css文件 -->

      <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/skin/css/bootstrap.css">

      <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/skin/css/datatables.css">

      <!-- 引入js文件 -->

      <script type="text/javascript" src="<%=request.getContextPath() %>/skin/js/jquery.js"></script>

      <script type="text/javascript" src="<%=request.getContextPath() %>/skin/js/adduser.js"></script>

   </head>

   <body>

      <div class="container" style="margin-top:60px;">

         <form id="saveForm" name="saveForm" class="form-horizontal pull-left" onsubmit="return false"style="width:600px;">

            <input name="id" value="${usersInfo.id}" type="hidden">

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">用户ID</label>

                <div class="col-xs-9 col-md-9">

                   <input id="user_id" name="userId" type="text" class="form-control" value="${usersInfo.userId}" placeholder="用户ID不能为空">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">姓名:</label>

                <div class="col-xs-9 col-md-9">

                   <input id="user_name" name="userName" type="text" class="form-control" value="${usersInfo.userName }" placeholder="名字不能为空">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">昵称:</label>

                <div class="col-xs-9 col-md-9">

                   <input id="user_nickname" name="nickname" type="text" class="form-control" value="${usersInfo.nickname }" placeholder="请填写昵称">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">密码:</label>

                <div class="col-xs-9 col-md-9">

                   <input id="user_password" name="password" type="text" class="form-control" value="${usersInfo.password }" placeholder="密码不能为空">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">是否管理员:</label>

                <div class="col-xs-9 col-md-9">

                   <div class="radio" id="user_isAdmin">

                      <label>

                         <input type="radio" name="isAdmin" value="Y">

                      </label>

                      <label>

                         <input type="radio" name="isAdmin" value="N" checked>

                      </label>

                   </div>

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">性别:</label>

                <div class="col-xs-9 col-md-9">

                   <div class="radio" id="gender">

                      <label>

                         <input type="radio" name="archive.gender" id="gender1" value="M" checked>

                      </label>

                      <label>

                         <input type="radio" name="archive.gender" id="gender2" value="F">

                      </label>

                   </div>

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">生日:</label>

                <div class="col-xs-9 col-md-9">

                   <input id="user_birthday" name="archive.birthday" type="text" class="form-control" value="${userArchiveInfo.birthday }" placeholder="请填写生日">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">学历:</label>

                <div class="col-xs-9 col-md-9">

                   <div class="radio" id="educations">

                      <label>

                         <input type="radio" name="archive.education" id="education1" value="0" checked>本科

                      </label>

                      <label>

                         <input type="radio" name="archive.education" id="education2" value="1">硕士

                      </label>

                      <label>

                         <input type="radio" name="archive.education" id="education3" value="2">博士

                      </label>

                   </div>

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label">学校:</label>

                <div class="col-xs-9 col-md-9">

                   <input name="archive.school" type="text" class="form-control" value="${userArchiveInfo.school }" placeholder="请填写学校">

                </div>

            </div>

            <div class="form-group">

                <label class="col-xs-3 col-md-3 control-label"></label>

                <div class="col-xs-9 col-md-9">

                   <button type="button" class="btn btn-primary" id="saveBtn">保存</button>

                   <button type="button" class="btn" id="returnBtn">返回</button>

                </div>

            </div>

         </form>

      </div>

   </body>

   <script type="text/javascript">

      var context = "<%=request.getContextPath()%>";

      var addnew = '<%=request.getParameter("addnew") %>';

      var flags = '${flags}';

      var user_isAdmin = '${usersInfo.isAdmin}';

      var user_gender = '${userArchiveInfo.gender}';

      var user_education = '${userArchiveInfo.education}';

   </script>

</html>

 

至此,前端展示界面完成。但是,还不能进行功能处理,需要接下来的逻辑处理。

第二步 、编写控制层

在src的controller文件夹下创建UserController的Java类。

UserController类代码如下:

@Controller

@RequestMapping("/demo/user")

publicclassUserController{

}

在UserController类中添加用户管理的一些方法,包括对用户的增删改查和页面跳转等。首先添加查询方法代码如下:

//查询用户信息

   @RequestMapping("/query")

   @ResponseBody

   public Map query(){

      returnnull;

   }

因为用到了用户信息,所以,我们需要首先添加一个用户信息的javabean类,里面封装了用户属性及操作属性的方法。在data文件夹下创建User类。

在User类中编写操作用户属性的代码,代码如下:

@Table(name = "demo_user")

publicclass User implements Serializable {

 

    @Id

    private Integer id;

 

    @Column(name = "user_id")

    private String userId;

 

    @Column(name = "user_name")

    private String userName;

 

   private String nickname;

 

    private String password;

 

    @Column(name = "is_admin")

    private String isAdmin = "N";

 

    @Transient

    private UserArchive archive;

 

   public Integer getId() {

      returnid;

   }

 

   publicvoid setId(Integer id) {

      this.id = id;

   }

 

   public String getUserId() {

      returnuserId;

   }

 

   publicvoid setUserId(String userId) {

      this.userId = userId;

   }

 

   public String getUserName() {

      returnuserName;

   }

 

   publicvoid setUserName(String userName) {

      this.userName = userName;

   }

 

   public String getNickname() {

      returnnickname;

   }

 

   publicvoid setNickname(String nickname) {

      this.nickname = nickname;

   }

 

   public String getPassword() {

      returnpassword;

   }

 

   publicvoid setPassword(String password) {

      this.password = password;

   }

 

   public String getIsAdmin() {

      returnisAdmin;

   }

 

   publicvoid setIsAdmin(String isAdmin) {

      this.isAdmin = isAdmin;

   }

 

   public UserArchive getArchive() {

      returnarchive;

   }

 

   publicvoid setArchive(UserArchive archive) {

      this.archive = archive;

   }

 

}

接着,创建用户信息的javabean文件UserArchive类。代码如下:

@Table(name = "demo_archives")

publicclass UserArchive implements Serializable {

 

    @Id

    private Integer id;

   

    private String gender;

 

    private String birthday;

 

    private String education;

 

    private String school;

 

    private String email;

 

    @Transient

    private User user;

 

    public String getGender() {

        returngender;

    }

 

    publicvoid setGender(String gender) {

        this.gender = gender;

    }

 

    public String getBirthday() {

        returnbirthday;

    }

 

    publicvoid setBirthday(String birthday) {

        this.birthday = birthday;

    }

 

    public String getEducation() {

        returneducation;

    }

 

    publicvoid setEducation(String education) {

        this.education = education;

    }

 

   public Integer getId() {

      returnid;

   }

 

   publicvoid setId(Integer id) {

      this.id = id;

   }

    public User getUser() {

        returnuser;

    }

 

    publicvoid setUser(User user) {

        this.user = user;

    }

 

    public String getSchool() {

        returnschool;

    }

 

    publicvoid setSchool(String school) {

        this.school = school;

    }

 

}

 

在controller层我们需要调用service层来处理业务逻辑。所以,我们在service文件夹下创建IUserService接口类。在该类中添加查询用户信息接口findAll,代码如下:

public interface IUserService {

    /**

    * 获取用户信息

    */

   public List<User> findAll();

}

接下来需要实现该接口类,完成业务逻辑处理。在impl文件夹下创建实现类UserServiceImpl类。在该类中首先需要实现IUserService接口。然后,编写findAll方法来进行事务处理。代码如下:

@Service("userService")

publicclass UserServiceImpl implements IUserService{

   /**

    * 查询用户信息

    * @return

    */

   public List<User> findAll(){

      returnnull;

   }    

}

在findAll()方法中我们需要完成获取用户信息的逻辑。在这里我们需要调用持久层,即dao层完成查询数据库的任务。下面我们来编写供findAll方法调用的dao层代码。在dao文件夹下创建UserMapper接口类。

UserMapper类代码如下:

import com.inspur.demo.data.User;

 

publicinterface UserMapper {

       /**

    * 获取用户所有信息

    */

   public List<User> findAll();

}

在UserMapper接口类中我们定义了findAll方法,调用这个方法将会从下面要写的UserMapper.xml中查询出用户数据。接下来,我们需要编写SQL语句去数据库查询用户信息。在dao文件夹下创建UserMapper.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.inspur.demo.dao.UserMapper">

 

       <resultMap type="com.inspur.demo.data.User" id="userResultMap">

       </resultMap>

 

       <select id="findAll" resultMap="userResultMap">

      SELECT * FROM demo_user

   </select>

</mapper>

至此,我们就完成了持久层代码编写。这样,我们就可以在接口实现类UserServiceImpl中调用dao层方法完成数据查询。UserServiceImpl类完成调用dao层的代码如下红色字体代码:

@Service("userService")

publicclass UserServiceImpl implements IUserService{

   

    @Autowired

    private UserMapper userMapper;

   

    /**

    * 查询用户信息

    * @return

    */

   public List<User> findAll(){

      returnuserMapper.findAll();

   }

}

由于上面使用User这个类,所以我们需要引入如下类才能完成编译,代码如下:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.inspur.demo.dao.UserMapper;

import com.inspur.demo.data.User;

import com.inspur.demo.service.IUserService;

到这里,我们就完成了service层的方法调用。这下我们就可以回到前面的controller层来调用service层的逻辑代码了。在controller的query方法中添加调用service方法的代码如下红色字体:

//查询用户信息

   @RequestMapping("/query")

   @ResponseBody

   public Map query(){

      List<User> userList= userService.findAll();

      Map<String,Object> map = new HashMap<String,Object>();

      int dataTotal = userList.size();

      map.put("aaData", userList);

      map.put("iTotalDisplayRecords", dataTotal);

      map.put("iTotalRecords", dataTotal);

      returnmap;

   }

在调用service代码时,用到了userService变量,该变量是IUserService类型的,我们需要在方法的一开始进行声明,代码如下红色字体:

publicclass UserController{

  

   @Autowired

   private IUserService userService;

     

   //查询用户信息

   @RequestMapping("/query")

   @ResponseBody

   public Map query(){

      List<User> userList = userService.findAll();

      Map<String,Object> map = new HashMap<String,Object>();

      intdataTotal = userList.size();

      map.put("aaData", userList);

      map.put("iTotalDisplayRecords", dataTotal);

      map.put("iTotalRecords", dataTotal);

     returnmap;

  }

这样,controller层查询的流程控制就完成了,引入如下类,完成编译:

import java.util.HashMap;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.inspur.demo.data.User;

import com.inspur.demo.service.IUserService;

接下来我们需要建立数据库。在项目根目录建立sql文件夹,在该文件夹里面创建user.sql文件。

在demo.sql文件中添加如下代码:

droptable if exists demo_archives;

droptable if exists demo_user ;

####用户#####

CREATETABLE demo_user (

   id intNOTNULL AUTO_INCREMENT,

   user_id varchar(30) NOTNULL,

   user_name varchar(30) NOTNULL,

   nickname varchar(30),

   password varchar(128) NOTNULL,

   is_admin varchar(1) NOTNULLdefault'N' comment 'N: 普通用户  Y: 管理员',

   primarykey (id)

)DEFAULTCHARACTERSET utf8 COLLATE utf8_general_ci;

 

######用户档案##

CREATETABLE demo_archives (

   id intNOTNULL,

   gender varchar(1) NOTNULL comment 'M: F:',

   birthday varchar(15),

   education varchar(1) comment '学历',

   school varchar(30) comment '学校',

   primarykey (id),

   CONSTRAINT demo_archives_fk1 foreignkey (id) references demo_user(id)

)DEFAULTCHARACTERSET utf8 COLLATE utf8_general_ci;

为了完成前端用户数据展示,我们还需要添加一些前端交互事件,在jsp目录下创建skin文件夹,以及下面包含的css和js文件夹。

在js文件夹下创建用户列表的js文件—queryuser.js,代码如下:

var oTable;

$(document).ready(function(){

   //初始化表格

   initTable();

});

function initTable(){

   oTable = $("#userList").dtable({

                //显示正在加载的图标

                "processing":true,

                "ajax":context + "/service/demo/user/query",

                "serverSide":true,

                "bPaginate": false,

               "ordering":false,

                "columns":[

                   {"data":"userId"},

                   {"data":"userName"},

                   {"data":"nickname"},

                   {"data":"isAdmin"},

                   {"data":"id"},

                ],

                "columnDefs":[

                   {

                      "targets":3,

                      "data":"isAdmin",

                      "render":function(data,type,full){

                         if(data !="" || data != null){

                            if(data == "Y"){

                               data = "";

                            }

                            if (data == "N"){

                               data = "";

                            }

                         }

                         return data;

                      }

                   },

                   {

                      "targets":4,

                      "data":"id",

                      "render":function(data,type,full){

                         return'<div><a id="edit" οnclick="forUpdate('+"'"+ full.id+ "'"+')" href="#">编辑</a>'+'<span>&nbsp;&nbsp</span>'

                         +'<a id="del" οnclick="del('+"'"+ full.id+ "'"+')" href="#">删除</a></div>'

                      }

                   }

                ]

            });

      return oTable;

}

根据前端引入的文件,我们需要额外在css文件下添加bootstrap.css和datatables.css,在js文件夹下添加datatables.js和jquery.js。

至此,用户展示列表完成,启动tomcat输入:http://localhost:8080/mvc_demo/jsp/demo/queryuser.jsp进入登录页面,输入正确的登录信息,点击登录。

至此,我们完成了用户的登录及登录成功后用户列表展示。以上根据springmvc思想介绍了用户管理展示列表的实现方法。按照这个思路我们可以完成剩余功能的实现。以下直接给出剩余步骤的实现代码:

    首先,完善dao层。UserMapper.java代码如下:

publicinterface UserMapper {

   /**

    * 获取用户所有信息

    */

   public List<User> findAll();

  

   /**

    * 保存用户信息

    */

   publicint save(User user);

  

   /**

    * 查询用户信息

    */

   public User findOne(intid);

  

   /**

    * 根据用户名称查询

    */

   public User getByUserName(String name);

  

   /**

    * 根据用户ID查询

    */

   public List<User> findUserByUserId(String userId);

  

   /**

    * 删除用户

    */

   publicvoid delete(intid);

 

   /**

    * 更新用户数据

    */

   publicvoid update(User user);

  

   /**

    * 获取新增用户的ID

    */

   publicint getNewId();

}

 

引入相应的类如下:

import java.util.List;

 

import com.inspur.demo.data.User;

完善UserMapping.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.inspur.demo.dao.UserMapper">

   <resultMap type="com.inspur.demo.data.User" id="userResultMap">

   </resultMap>

  

   <select id="findAll" resultMap="userResultMap">

      SELECT * FROM demo_user

   </select>

  

   <insert id="save" parameterType="com.inspur.demo.data.User">

      INSERT INTO demo_user (user_id,user_name,nickname,password,is_admin) VALUES (#{userId},#{userName},#{nickname},#{password},#{isAdmin})

      <selectKey keyProperty="id" resultType="int">

         SELECT LAST_INSERT_ID()

      </selectKey>

   </insert>

  

   <select id="findOne" parameterType="int" resultMap="userResultMap">

      SELECT * FROM demo_user WHERE id=#{id}

   </select>

  

   <select id="getByUserName" parameterType="string" resultMap="userResultMap">

      SELECT * FROM demo_user WHERE user_name=#{userName}

   </select>

  

   <select id="findUserByUserId" parameterType="string" resultMap="userResultMap">

      SELECT * FROM demo_user WHERE user_id=#{userId}

   </select>

  

   <delete id="delete" parameterType="int">

      DELETE FROM demo_user WHERE id=#{id}

   </delete>

  

   <update id="update" parameterType="com.inspur.demo.data.User">

      UPDATE demo_user SET user_id=#{userId},user_name=#{userName},nickname=#{nickname},password=#{password},is_admin=#{isAdmin} WHERE id=#{id}

   </update>

</mapper>

ArchiveMapper.java代码如下:

publicinterface ArchiveMapper {

  

   /**

    * 保存用户档案信息

    */

   publicvoid save(UserArchive userArchive);

  

   /**

    * 查询用户信息

    */

   public UserArchive findOne(intid);

  

   /**

    * 删除用户

    */

   publicvoid delete(intid);

 

   /**

    * 更新用户数据

    */

   publicvoid update(UserArchive userArchive);

}

 

引入相应的类如下:

import com.inspur.demo.data.UserArchive;

ArchiveMapper.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.inspur.demo.dao.ArchiveMapper">

   <resultMap type="com.inspur.demo.data.UserArchive" id="userArchiveResultMap">

   </resultMap>

  

   <insert id="save" parameterType="com.inspur.demo.data.UserArchive">

      INSERT INTO demo_archives (id,gender,birthday,education,school) VALUES (#{id},#{gender},#{birthday},#{education},#{school})

   </insert>

  

   <select id="findOne" parameterType="int" resultMap="userArchiveResultMap">

      SELECT * FROM demo_archives WHERE id=#{id}

   </select>

  

   <delete id="delete" parameterType="int">

      DELETE FROM demo_archives WHERE id=#{id}

   </delete>

  

   <update id="update" parameterType="com.inspur.demo.data.UserArchive">

      UPDATE demo_archives SET id=#{id},gender=#{gender},birthday=#{birthday},education=#{education},school=#{school} WHERE id=#{id}

   </update>

</mapper>

完成了dao层的代码后,接下来我们完善service层代码。首先,完善接口类IUserService.java代码如下:

publicinterface IUserService {

   /**

    * 获取用户信息

    */

   public List<User> findAll();

  

   /**

    * 保存用户信息

    */

   publicvoid save(User user);

  

   /**

    * 根据用户名字查询用户信息

    */

   public User getByUserName(String name);

  

   /**

    * 查询用户信息

    */

   public User findOne(intid);

  

   /**

    * 根据用户ID查询

    */

   public List<User> findUserByUserId(String userId);

  

   /**

    * 删除用户

    *

    */

   publicvoid delete(intid);

 

   /**

    * 更新用户信息

    */

   publicvoid update(User user);

  

   /**

    * 根据id查询用户档案信息

    */

   public UserArchive findArchive(intid);

}

引入相应的类如下:

import java.util.List;

 

import com.inspur.demo.data.User;

import com.inspur.demo.data.UserArchive;

接着,完善接口实现类UserServiceImpl.java代码如下:

@Service("userService")

publicclass UserServiceImpl implements IUserService{

  

   @Autowired

   private UserMapper userMapper;

   @Autowired

   private ArchiveMapper archiveMapper;

  

   /**

    * 查询用户信息

    * @return

    */

   public List<User> findAll(){

      List<User> bb= userMapper.findAll();

      returnbb;

   }

  

   /**

    * 保存用户信息

    */

   @Transactional("mybatisTransactionManager")

   publicvoid save(User user){

      //保存用户信息

      userMapper.save(user);

      //保存用户档案信息

      user.getArchive().setId(user.getId());

      archiveMapper.save(user.getArchive()); 

   }

  

   /**

    * 根据用户名字查询用户信息

    */

   public User getByUserName(String name){

      returnuserMapper. getByUserName (name);

   }

  

   /**

    * 查询用户信息

    *

    */

   public User findOne(intid){

      returnuserMapper.findOne(id);

   }

  

   /**

    * 根据用户ID查询

    */

   public List<User> findUserByUserId(String userId){

      returnuserMapper.findUserByUserId(userId);

   }

  

   /**

    * 删除用户

    */

   @Transactional("mybatisTransactionManager")

   publicvoid delete(intid){

      //删除用户档案信息

      archiveMapper.delete(id);

      //删除用户信息

      userMapper.delete(id);

   }

 

   /**

    * 更新用户信息

    *

    */

   //@Transactional("mybatisTransactionManager")

   publicvoid update(User user) {

      //更新用户信息

      userMapper.update(user);

      //更新用户档案信息

      user.getArchive().setId(user.getId());;

      archiveMapper.update(user.getArchive());

   }

 

   /**

    * 根据id查询用户档案信息

    */

   public UserArchive findArchive(intid) {

      UserArchive aa = archiveMapper.findOne(id);

      returnaa;

   }

 

}

引入相应的类如下:

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

 

import com.inspur.demo.dao.ArchiveMapper;

import com.inspur.demo.dao.UserMapper;

import com.inspur.demo.data.User;

import com.inspur.demo.data.UserArchive;

import com.inspur.demo.service.IUserService;      

然后,我们完成controller层UserController.java的代码如下:

@Controller

@RequestMapping("/demo/user")

publicclass UserController {

  

   @Autowired

   private IUserService userService;

  

   //返回主页

   @RequestMapping("/home")

   public String homePage(){

      return"/demo/queryuser";

   }

  

   //查询用户信息

   @RequestMapping("/query")

   @ResponseBody

   public Map query(){

      List<User> userList = userService.findAll();

      Map<String,Object> map = new HashMap<String,Object>();

      intdataTotal = userList.size();

      map.put("aaData", userList);

      map.put("iTotalDisplayRecords", dataTotal);

      map.put("iTotalRecords", dataTotal);

      returnmap;

   }

  

   //保存用户信息

   @RequestMapping("/save")

   public String save(User user){

      userService.save(user);

      return"redirect:/service/demo/user/home";

   }

  

   //查询用户

   @RequestMapping("search")

   @ResponseBody

   public Map search(@RequestParam(value="userId",required=false) String userId){

      List<User> user = userService.findUserByUserId(userId);

      Map<String,Object> map = new HashMap<String,Object>();

      intdataTotal = user.size();

      map.put("aaData", user);

      map.put("iTotalRecords", dataTotal);

      map.put("iTotalDisplayRecords", dataTotal);

      returnmap;

   }

  

   //根据用户名查询用户信息

   @RequestMapping("getUserByName")

   @ResponseBody

   public Map getUserByName(@RequestParam(value="name",required=false)String name){

      User user = userService.getByUserName(name);

      Map<String,Object> map = new HashMap<String,Object>();

      map.put("userInfo", user);

      returnmap;

   }

  

   //删除用户

   @RequestMapping("del")

   @ResponseBody

   publicvoid del(@RequestParam(value="id",required=false) intid){

      userService.delete(id);

   }

  

   // 更新用户信息

   @RequestMapping("update")

   public String update(User user) {

      userService.update(user);

      return"redirect:/service/demo/user/home";

   }

  

   //跳转到编辑页面

   @RequestMapping("edits")

   public ModelAndView edits(@RequestParam(value="id",required=false) intid,@RequestParam(value="isOrdinary",required=false) String isOrdinary) {

      User users = userService.findOne(id);

      UserArchive userArchive = userService.findArchive(id);

      Map<String, Object> map = new HashMap<String, Object>();

      map.put("usersInfo", users);

      map.put("userArchiveInfo", userArchive);

      map.put("flags", "edit");

      map.put("isOrdinary", isOrdinary);

      returnnew ModelAndView("/demo/adduser", map);

   }

}

 引入相应的类如下:

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.servlet.ModelAndView;

 

import com.inspur.demo.data.User;

import com.inspur.demo.data.UserArchive;

import com.inspur.demo.service.IUserService;

最后,完成前端js代码。queryuser.js如下:

var oTable;

$(document).ready(function(){

   //初始化表格

   initTable();

   $("#addusers").on("click",function(){

      window.location.href=context+"/jsp/demo/adduser.jsp?addnew=Y";

   });

   $("#search").on("click",function(){

      var tmp = $("#searchVal").val();

      query(tmp);

 

   });

  

   //回车查询事件

   $("#searchVal").keydown(function(event) {

      if (event.keyCode == 13) {

         var srcName = $("#searchVal").val();

         query(srcName);

      }

   });

});

 

function initTable(){

   oTable = $("#userList").dtable({

                //显示正在加载的图标

                "processing":true,

                "ajax":context + "/service/demo/user/query",

                "serverSide":true,

                "bPaginate": false,

                "ordering":false,

                "columns":[

                   {"data":"userId"},

                   {"data":"userName"},

                   {"data":"nickname"},

                   {"data":"isAdmin"},

                   {"data":"id"},

                ],

                "columnDefs":[

                   {

                      "targets":3,

                      "data":"isAdmin",

                      "render":function(data,type,full){

                         if(data !="" || data != null){

                            if(data == "Y"){

                               data = "";

                            }

                            if (data == "N"){

                               data = "";

                            }

                         }

                         return data;

                      }

                   },

                   {

                      "targets":4,

                      "data":"id",

                      "render":function(data,type,full){

                         return'<div><a id="edit" οnclick="forUpdate('+"'"+ full.id+ "'"+')" href="#">编辑</a>'+'<span>&nbsp;&nbsp</span>'

                         +'<a id="del" οnclick="del('+"'"+ full.id+ "'"+')" href="#">删除</a></div>'

                      }

                   }

                ]

            });

      return oTable;

}

 

//查询

function query(tmp){

   if ((tmp == "" || tmp == null)) {

      oTable.ajax.url(context + "/service/demo/user/query").load();

   } else {

      var url=context + "/service/demo/user/search?userId=" + tmp;

      oTable.ajax.url(url).load();

   }

}

 

//删除用户信息

function del(args){

   $.ajax({

      url:context+"/service/demo/user/del?id="+args,

      type:"get",

      async:false,

      success:function(){

         oTable.ajax.url(context + "/service/demo/user/query").load();

      },

   error:function(data){

      alert(data);

   }

   });

}

 

//编写用户信息

function forUpdate(args){

   window.location.href=context+"/service/demo/user/edits?id="+args+"&isOrdinary=N";

}

添加adduser.js文件,并赋值代码如下:

$(document).ready(function(){

   if(flags=="edit"){

       $("#user_name").attr("readonly",true);

       $(":radio[value='"+user_isAdmin+"']").attr("checked",true);

       $(":radio[value='"+user_gender+"']").attr("checked",true);

       $(":radio[value='"+user_education+"']").attr("checked",true);

   }

   $("#saveBtn").on("click",function(){

      if($("#user_id").val()==null || $("#user_id").val()==""){

         alert("用户id不能为空");

         returnfalse;

      }elseif($("#user_name").val()==null || $("#user_name").val()==""){

         alert("用户名字不能为空");

         returnfalse;

      }elseif($("#user_password").val()==null || $("#user_password").val()==""){

         alert("用户密码不能为空");

         returnfalse;

      }

      if(flags=="edit"){

         var url = context + "/service/demo/user/update";

         saveForm.action = url;

         saveForm.method = "POST";

         saveForm.submit();

      }else{

         var url = context + "/service/demo/user/save";

         saveForm.action = url;

         saveForm.method = "POST";

         saveForm.submit();

      }

   });

   $("#returnBtn").on("click",function(){

      window.location.href=context+"/service/demo/user/home";

   });

   $("#user_name").blur(function(){

      $.ajax({

         url:context+"/service/demo/user/getUserByName?name="+$("#user_name").val(),

         type:"POST",

         success:function(data){

            if(data.userInfo!=null){

                if(addnew=="Y"){

                   $("#saveBtn").attr("disabled", true);

                   alert("用户已存在,请修改用户名");

                }

            }else{

                $("#saveBtn").attr("disabled", false);

            }

         }

      });

   });

});

 


 


展开阅读全文

没有更多推荐了,返回首页