EasyUI Spring SpringMVC MyBatis开发环境搭建

在网上看了一遍博客,写的很好,照着例子做了一遍,发现没有问题,结果看到下面的帖子,看到无数同学需要源代码,估计都是新手。于是笔者准备写完博客后,上传一下代码。

1、项目结构:

EasyUI Spring SpringMVC MyBatis开发环境搭建

2、创建表SQL:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `trueName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `roleName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
3、插入一条记录:

INSERT INTO `users` VALUES ('1', 'zhangsan', '123456', '1', '张三', null, null, null);

4、依赖:

net.sf.json-lib:json-lib:jar:2.4下载不了

添加如下代码

<classifier>jdk15</classifier>

参考网址:https://blog.csdn.net/weixin_41907291/article/details/83714551

 

5.1、源代码:TestSpring

package com.liuhai.eshop;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.liuhai.eshop.domain.User;
import com.liuhai.eshop.service.UserService;
 
public class TestSpring {
    @Test
    public void TestUserService() throws Exception{
        @SuppressWarnings("resource")
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService us=(UserService) ac.getBean("userService");
        User user=new User();
        user.setAge(1);
        user.setUserName("zhangsan");
        user.setPassword("123456");
        user.setTrueName("张三");
        us.add(user);
    }
}

5.2、源代码:UserController

package com.liuhai.eshop.controller;
 
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
 
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import org.springframework.web.multipart.MultipartFile;
 
import com.liuhai.eshop.domain.User;
import com.liuhai.eshop.service.UserService;
import com.liuhai.eshop.util.PageBean;
import com.liuhai.eshop.util.ResponseUtil;
import com.liuhai.eshop.util.StringUtil;
 
@Controller
@RequestMapping("/user")
public class UserController {
    private static Logger log=LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    
    @RequestMapping("/showUser.do")
    public String toIndex(HttpServletRequest request,Model model){
        System.out.println("liuhaitest");
        return "showUser";
    }
    // /user/test.do?id=1
    @RequestMapping(value="/test.do",method=RequestMethod.GET)  
    public String test(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
             user = new User();  
             user.setAge(11);
             user.setId(1);
             user.setPassword("123");
             user.setUserName("javen");
        }
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "index";  
    }  
    // /user/showUser.do?id=1
    @RequestMapping(value="/showUser.do",method=RequestMethod.GET)  
    public String toindex(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  
    
 // /user/showUser2.do?id=1
    @RequestMapping(value="/showUser2.do",method=RequestMethod.GET)  
    public String toIndex2(@RequestParam("id") String id,Model model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "showUser";  
    }  
 
    // /user/jsontype.do?id=1
    @RequestMapping(value="/jsontype.do",method=RequestMethod.GET)  
    public @ResponseBody User getUserInJson(@RequestParam("id") String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return user;  
    }  
    // /user/jsontype2.do?id=1
    @RequestMapping(value="/jsontype2.do",method=RequestMethod.GET)  
    public ResponseEntity<User>  getUserInJson2(@RequestParam("id") String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return new ResponseEntity<User>(user,HttpStatus.OK);  
    } 
    
    //文件上传页面
    @RequestMapping(value="/upload.do")
    public String showUploadPage(){
        return "file";
    }
    //文件上传
    @RequestMapping(value="/doUpload.do",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }
    /**
     * 用户管理页面
     * @return
     */
    @RequestMapping(value="/userManage.do")
    public String userManagePage(){
        return "userManage";
    }
    /**
     * 添加或者修改
     * @param user
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/save.do")
    public String save(User user,HttpServletResponse res) throws Exception{
        //操作记录条数,初始化为0
        int resultTotal = 0;
        if (user.getId() == null) {
            resultTotal = userService.add(user);
        }else{
            resultTotal = userService.update(user);
        }
        JSONObject jsonObject = new JSONObject();
        if(resultTotal > 0){   //说明修改或添加成功
            jsonObject.put("success", true);
        }else{
            jsonObject.put("success", false);
        }
        ResponseUtil.write(res, jsonObject);
        return null;
    }
    /**
     * 用户分页查询
     * @param page
     * @param rows
     * @param s_user
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/list.do")
    public String list(@RequestParam(value="page",required=false) String page,@RequestParam(value="rows",required=false) String rows,User s_user,HttpServletResponse res) throws Exception{
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("userName", StringUtil.formatLike(s_user.getUserName()));
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        List<User> userList=userService.find(map);
        Long total=userService.getTotal(map);
        JSONObject result=new JSONObject();
        JSONArray jsonArray=JSONArray.fromObject(userList);
        result.put("rows", jsonArray);
        result.put("total", total);
        ResponseUtil.write(res, result);
        return null;
    }
    /**
     * 删除用户
     * @param ids
     * @param res
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(value="ids") String ids,HttpServletResponse res) throws Exception{
        String[] idStr = ids.split(",");
        JSONObject jsonObject = new JSONObject();
        for (String id : idStr) {
            userService.delete(Integer.parseInt(id));
        }
        jsonObject.put("success", true);
        ResponseUtil.write(res, jsonObject);
        return null;
    }
}

5.3、源代码:UserDao

package com.liuhai.eshop.dao;
 
import java.util.List;
import java.util.Map;
 
import com.liuhai.eshop.domain.User;
/**
 * 用户DAO接口
 * @author Administrator
 *
 */
public interface UserDao {
    /**
     * 用户登录
     * @param user
     * @return
     */
    public User login(User user);
    /**
     * 查询所有用户
     * @return
     */
    public List<User> getAll();
    /**
     * 根据条件查询用户
     * @param user
     * @return
     */
    public User getUser(User user);
    /**
     * 删除用户
     * @param user
     * @return
     */
    public int delete(int id);
    /**
     * 更新用户
     * @param user
     * @return
     */
    public int update(User user);
    /**
     * 添加用户
     * @param user
     * @return
     */
    public int add(User user);
    /**
     * 用户查询
     * @param map
     * @return
     */
    public List<User> find(Map<String,Object> map);
    /**
     * 获取总记录数
     * @param map
     * @return
     */
    public Long getTotal(Map<String,Object> map);
    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public User getUserById(int id);
}

5.4、源代码:User

package com.liuhai.eshop.domain;
 
import java.io.Serializable;
 
/**
 * 用户实体
 * @author Administrator
 *
 */
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String userName;
    private String password;
    private Integer age;
    private String trueName;
    private String email;
    private String phone;
    private String roleName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
 
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getTrueName() {
        return trueName;
    }
    public void setTrueName(String trueName) {
        this.trueName = trueName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
}

6、配置文件: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.liuhai.eshop.dao.UserDao">
     <!-- 定义缓存  一般是一级缓存,如果用同一个sqlsession 那么相同查询直接会从缓存中查找 -->
    <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"></cache>
    <!-- 增加 -->
    <insert id="add" parameterType="com.liuhai.eshop.domain.User">
        insert into users values(null,#{userName},#{password},#{age},#{trueName},#{email},#{phone},#{roleName})
    </insert>
    <resultMap id="userResultMap" type="com.liuhai.eshop.domain.User" >
        <id property="id" column="id"/>
        <result property="userName" column="userName"/>
        <result property="password" column="password"/>
        <result property="age" column="age"/>
        <result property="trueName" column="trueName" />
        <result property="email" column="email" />
        <result property="phone" column="phone" />
        <result property="roleName" column="roleName" />
    </resultMap>
    <select id="getUserById" parameterType="Integer" resultMap="userResultMap">
        select * from users where id=#{id}
    </select>
    <select id="find" parameterType="com.liuhai.eshop.domain.User" resultMap="userResultMap">
        select * from users 
        <where>
            <if test="userName!=null and userName!='' ">
                and userName like #{userName}
            </if>
        </where>
        <if test="start!=null and size!=null">
            limit #{start},#{size}
        </if>
    </select>
    <select id="getTotal" parameterType="Map" resultType="Long">
        select count(*) from users
        <where>
            <if test="userName!=null and userName!='' ">
                and userName like #{userName}
            </if>
        </where>
    </select>
    <!-- 用户删除 -->
    <delete id="delete" parameterType="Integer">
        delete from users where id = #{id}
    </delete>
    <!-- 用户修改 -->
    <update id="update" parameterType="com.liuhai.eshop.domain.User">
        update users
        <set>
            <if test="age != null and age != ''">age = #{age},</if>
            <if test="userName != null and userName != ''">userName = #{userName},</if>
            <if test="password != null and password != ''">password = #{password},</if>
            <if test="trueName != null and trueName != ''">trueName = #{trueName},</if>
            <if test="email != null and email != ''">email = #{email},</if>
            <if test="phone != null and phone != ''">phone = #{phone},</if>
            <if test="roleName != null and roleName != ''">roleName = #{roleName},</if>
        </set>
        where id = #{id}
    </update>
</mapper>