转载

Mybatis案例升级版——小案例大道理

纯Mybatis案例升级版——小案例大道理

前言:

这几天看了一本书《原则》,在上面看到了一句话叫“每个人都把自己眼界的局限当成世界的局限”,大学生是:fish:,大学就是鱼缸,世界很大,希望大家好好努力,不要让“贫穷”限制了你的思维。

暑假的时候写了一篇《Mybatis案例超详解》 https://www.cnblogs.com/zyx110/p/11363878.html ,遗留了一些问题,欠的债现在该还了,刚开学,学校事比较多,这几天脑子里还装着好几篇博客,一直腾不出时间写,今天咬咬牙,先把这篇补上。

案例准备

因为和之前写的是同一个案例,环境也都一样,我就不重复了,需要的朋友去看之前的博客,我直接上代码了。

案例演示

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

案例结构及代码

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

表结构

users表

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理

address表

Mybatis案例升级版——小案例大道理

Mybatis案例升级版——小案例大道理


 USE moocmybatis;
 CREATE TABLE ADDRESS(
 id INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
 userid INT COMMENT '外键:关联用户表主键',
 defaultAddr BOOLEAN COMMENT '是否默认地址',
 nation VARCHAR(20) COMMENT '国家',
 province VARCHAR(20) COMMENT '省区',
 city VARCHAR(20) COMMENT '市区',
 country VARCHAR(20) COMMENT '县区',
 street VARCHAR(100) COMMENT '街道',
 remark TEXT COMMENT '备注'
 ) CHARSET "UTF8";
 ALTER TABLE address ADD FOREIGN KEY (userid) REFERENCES users(id);

View Code

pom.xml


<dependencies>
     <dependency>
         <groupId>org.mybatis</groupId>
         <artifactId>mybatis</artifactId>
         <version>3.4.6</version>
     </dependency>
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>5.1.38</version>
     </dependency>
     <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.1.0</version>
     </dependency>
     <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>1.2</version>
     </dependency>
     <dependency>
         <groupId>log4j</groupId>
         <artifactId>log4j</artifactId>
         <version>1.2.17</version>
     </dependency>
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
         <scope>test</scope>
     </dependency>
 </dependencies>

View Code

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration
         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>
 ​
     <!--
     properties配置,用于加载外部的properties配置文件
     -->
     <properties resource="db.properties"></properties>
 ​
     <!--
     environments 主要用于进行数据源的配置
     可以配置多个数据源~ 通过default属性来指定当前项目运行过程中使用的是哪个数据源
     -->
     <environments default="development">
         <!--
         environment 用于配置一个具体的独立的数据源
         id属性用于给当前数据源定义一个名称,方便我们的项目指定
         -->
         <environment id="development">
             <!--
             transactionManager用于配置事务管理,默认情况下使用的是JDBC事务管理
             -->
             <transactionManager type="JDBC"/>
             <!--
             dataSource具体数据源的链接信息;type属性用于指定是否使用连接池
             -->
             <dataSource type="POOLED">
                 <property name="driver" value="${driver}"/>
                 <property name="url" value="${url}"/>
                 <property name="username" value="${username}"/>
                 <property name="password" value="${password}"/>
             </dataSource>
         </environment>
     </environments>
     <!-- mappers主要用于配置我们外部的映射配置文件
         在主配置文件中需要引入加载映射配置文件
      -->
     <mappers>
         <!-- mapper主要配置引入某一个具体的映射文件,resource进行路径方式的引入 -->
         <mapper resource="mapper/usersMapper.xml"/>
     </mappers>
 </configuration>

db.properties

driver=com.mysql.jdbc.Driver
 url=jdbc:mysql://localhost:3306/moocmybatis?useUnicode=true&characterEncoding=utf8
 username=root
 password=root

log4j.properties

log4j.rootLogger=DEBUG, A1
 log4j.appender.A1=org.apache.log4j.ConsoleAppender
 log4j.appender.A1.layout=org.apache.log4j.PatternLayout
 log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n

usersMapper.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属性是用来配置命名空间,主要进行session级别的缓存管理
 命名空间默认情况下,使用我们当前操作的实体类的全路径
 -->
 <mapper namespace="com.demo.entity.Users">
     <!--<select id="findUsers" resultType="com.demo.entity.Users">-->
     <select id="findUsers" resultMap="forUsers">
         select * from users
         <if test="id !=null">
             where id=#{id}
         </if>
     </select>
     <select id="findUsersByName" resultMap="forUsers">
         select * from users
         <if test="name !=null">
             where username=#{name}
         </if>
     </select>
 ​
     <!-- 自定义映射关系集合:主要包含对于一些自定义操作的配置,如不一致的属性和字段 -->
     <resultMap id="forUsers" type="com.demo.entity.Users">
         <!-- 绑定id主键 -->
         <id property="id" column="id"></id>
         <!-- result配置,主要配置普通属性,column表示配置的是数据库字段名称 property配置的是实体类的属性名称 -->
         <result column="username" property="name"></result>
         <collection property="addresses" column="id" ofType="com.demo.entity.Address" select="getAddress"></collection>
     </resultMap>
     <select id="getAddress" resultType="com.demo.entity.Address">
         select * from address where userid = #{id}
     </select>
     <sql id="user_fields">
         username, userpass, nickname, age, gender, email, phone, createTime, updateTime, lastLogin, userstatus, remark
     </sql>
 ​
     <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
         insert into users( <include refid="user_fields"></include>)
         values(#{name},#{userpass}, #{nickname}, #{age}, #{gender}, #{email}, #{phone}, #{createTime}, #{updateTime}, #{lastLogin}, #{userStatus}, #{remark})
     </insert>
     <!--<insert id="addUser" useGeneratedKeys="true" keyProperty="id">-->
         <!--insert into users(username,userpass,nickname,age,gender,email,phone,createTime,updateTime,lastLogin,userStatus,remark)-->
         <!--values(#{name},#{userpass}, #{nickname}, #{age}, #{gender}, #{email}, #{phone}, #{createTime}, #{updateTime}, #{lastLogin}, #{userStatus}, #{remark})-->
     <!--</insert>-->
     <!--<select id="findById" resultType="com.demo.entity.Users">-->
         <!--select * from users where id = #{id};-->
     <!--</select>-->
     <update id="updateUser">
         update users
         <set>
             <if test="name != null">username = #{name},</if>
             <if test="userpass != null">userpass = #{userpass},</if>
             <if test="nickname != null">nickname = #{nickname},</if>
             <if test="age != null">age = #{age},</if>
             <if test="gender != null">gender = #{gender},</if>
             <if test="email != null">email = #{email},</if>
             <if test="phone != null">phone = #{phone},</if>
             <if test="createTime != null">createTime = #{createTime},</if>
             <if test="updateTime != null">updateTime = #{updateTime},</if>
             <if test="lastLogin != null">lastlogin = #{lastLogin},</if>
             <if test="userStatus != null">userStatus = #{userStatus},</if>
             <if test="remark != null">remark = #{remark},</if>
         </set>
         where id = #{id}
     </update>
     <!--<update id="updateUser">-->
         <!--update users set-->
             <!--username = #{name},-->
             <!--userpass = #{userpass},-->
             <!--nickname = #{nickname},-->
             <!--age = #{age},-->
             <!--gender = #{gender},-->
             <!--email = #{email},-->
             <!--phone = #{phone},-->
             <!--createTime = #{createTime},-->
             <!--updateTime = #{updateTime},-->
             <!--lastlogin = #{lastLogin},-->
             <!--userStatus = #{userStatus},-->
             <!--remark = #{remark}-->
         <!--where id = #{id}-->
     <!--</update>-->
     <delete id="delUser">
         delete from users where id = #{id}
     </delete>
 </mapper>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
          id="WebApp_ID" version="3.1">
     <display-name>mybatispro</display-name>
 ​
     <welcome-file-list>
         <welcome-file>login.jsp</welcome-file>
     </welcome-file-list>
 ​
 </web-app>

dao

UsersDao

package com.demo.dao;
 ​
 import com.demo.entity.Users;
 import com.demo.utils.SqlSessionFactoryUtils;
 import org.apache.ibatis.session.SqlSession;
 ​
 import java.util.List;
 ​
 public class UsersDao {
     private SqlSession session ;
     private List<Users> list;
     private Users user;
 ​
     public SqlSession getSession(){
         session =  SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
         return session;
     }
 ​
     /**
      * 查询所有用户
      * @return
      */
     public List<Users> findAll(){
         try {
             list = getSession().selectList("findUsers");
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
         return list;
     }
 ​
     /**
      * 根据id查询单个用户
      * @return
      */
     public Users findById(Integer id){
         try {
             user = getSession().selectOne("findUsers",new Users(id));
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
         return user;
     }
 ​
     /**
      * 根据name查询单个用户
      * @return
      */
     public Users findByName(String name){
         try {
             user = getSession().selectOne("findUsersByName",new Users(name));
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
         return user;
     }
 ​
     /**
      * 添加一个用户
      * @param user
      * @return
      */
     public Users addUser(Users user){
         try {
             //返回值是insert执行过程中影响的行数
             getSession().insert("addUser",user);
             session.commit();
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
         return user;
     }
 ​
     /**
      * 修改一个用户
      * @param user
      * @return
      */
     public Users updateUser(Users user){
         try {
             //返回值是insert执行过程中影响的行数
             getSession().update("updateUser",user);
             session.commit();
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
         return user;
     }
 ​
     /**
      * 删除一个用户
      * @param id
      */
     public void delUser(Integer id){
         try {
             //返回值是insert执行过程中影响的行数
             getSession().delete("delUser",id);
             session.commit();
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             session.close();
         }
 ​
     }
 ​
     /**
      * 用户登录
      * @param user
      */
     public boolean login(Users user){
         boolean flag = false;
         try {
            Users users = findByName(user.getName());
                 if (users.getName().equals(user.getName())&&users.getUserpass().equals(user.getUserpass())){
                     flag=true;
                 }
 ​
 ​
 ​
         }catch (Exception e){
             e.printStackTrace();
         }
         return flag;
     }
 }

entity

Address

package com.demo.entity;

/**
 * 地址表,关联用户数据
 *
 * 一个用户可以有多个地址,有一个是默认地址
 */
public class Address {

    private Integer id;         // 编号
    private Users user;         // 所属用户
    private Boolean defaultAddr;  // 是否默认地址
    private String nation;      // 国家
    private String province;    // 省
    private String city;        // 市
    private String country;     // 县
    private String street;      // 街道
    private String remark;      // 描述

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public Boolean getDefaultAddr() {
        return defaultAddr;
    }

    public void setDefaultAddr(Boolean defaultAddr) {
        this.defaultAddr = defaultAddr;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "Address{" +
                "id=" + id +
                ", user=" + user +
                ", isDefault=" + defaultAddr +
                ", province='" + province + '/'' +
                ", city='" + city + '/'' +
                ", country='" + country + '/'' +
                ", street='" + street + '/'' +
                ", remark='" + remark + '/'' +
                '}';
    }
}

Users

package com.demo.entity;

import java.util.Date;
import java.util.List;

/**
 * Created by mouwe on 2017/5/17.
 * resource:mybatis-config.xml
 * InputStream
 * SqlSessionFactory
 * SqlSession
 * 执行我们的配置好的SQL语句
 */
public class Users {

    private Integer id;                 // 用户编号
    //更换与表对应的字段
    private String name;                // 登录账号
    private String userpass;            // 登录密码
    private String nickname;            // 用户昵称
    private Integer age;                // 用户年龄
    private String gender;              // 用户性别
    private String phone;               // 联系方式
    private String email;               // 用户邮箱
    private Date createTime;            // 创建时间
    private Date updateTime;            // 账号最后修改时间
    private Date lastLogin;             // 用户最后登录时间
    private Integer userStatus;         // 用户账号状态 0 正常 1 锁定 2 删除
    private String remark;              // 用户备注信息
    private List<Address> addresses;    // 用户地址信息【地址列表,有一个是默认地址】

    public Users() {
    }

    public Users(Integer id) {
        this.id = id;
    }
    public Users(String name){this.name=name;}

    public Users(String name, String userpass, String nickname, Integer age, String gender, String phone, String email) {
        this.name = name;
        this.userpass = userpass;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
    }

    public Users(Integer id, String nickname, Integer age, String gender, String phone, String email, Date updateTime, String remark) {
        this.id = id;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
        this.updateTime = updateTime;
        this.remark = remark;
    }

    public Users(String name, String userpass, String nickname, Integer age, String gender, String phone, String email, Date createTime, Date updateTime, Date lastLogin, Integer userStatus) {
        this.name = name;
        this.userpass = userpass;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
        this.createTime = createTime;
        this.updateTime = updateTime;
        this.lastLogin = lastLogin;
        this.userStatus = userStatus;
    }

    public Users(Integer id, String nickname, Integer age, String gender, String phone, String email, String remark) {
        this.id = id;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
        this.remark = remark;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUserpass() {
        return userpass;
    }

    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Date getLastLogin() {
        return lastLogin;
    }

    public void setLastLogin(Date lastLogin) {
        this.lastLogin = lastLogin;
    }

    public Integer getUserStatus() {
        return userStatus;
    }

    public void setUserStatus(Integer userStatus) {
        this.userStatus = userStatus;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }



    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", name='" + name + '/'' +
                ", userpass='" + userpass + '/'' +
                ", nickname='" + nickname + '/'' +
                ", age=" + age +
                ", gender='" + gender + '/'' +
                ", phone='" + phone + '/'' +
                ", email='" + email + '/'' +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", lastLogin=" + lastLogin +
                ", userStatus=" + userStatus +
                ", remark='" + remark + '/'' +
                ", addresses=" + addresses +
                '}';
    }
}

listener

InitSqlSessionListener

package com.demo.listener;

import com.demo.utils.SqlSessionFactoryUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitSqlSessionListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("容器加载中。。。。。");
        //初始化SqlSessionFactory对象
        SqlSessionFactoryUtils.initSqlSessionFactory();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("容器销毁中。。。。。");
        //关闭SqlSession对象
        SqlSessionFactoryUtils.close();
    }
}

servlet

UserAddServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/addusers")
public class UserAddServlet extends HttpServlet {
    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要添加的用户数据
        String username = req.getParameter("username");
        String userpass = req.getParameter("userpass");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        //根据用户数据创建一个用户对象
        Users user = new Users(username, userpass, nickname, Integer.parseInt(age), gender, email, phone, new Date(), new Date(), new Date(), 0);
        //将用户对象添加到数据库中
        user =  usersDao.addUser(user);
        //查看刚新增的用户数据
        resp.sendRedirect("/detail?id=" + user.getId());
    }
}

UserDelServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/deluser")
public class UserDelServlet extends HttpServlet {
    private UsersDao usersDao = new UsersDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String id = req.getParameter("id");
        String type = req.getParameter("type");

        //执行删除或者锁定
        if ("lock".equals(type)){
            //执行锁定操作:update操作
        Users user = new Users();
        user.setId(Integer.parseInt(id));
        user.setUserStatus(1);
        usersDao.updateUser(user);
        }else if ("del".equals(type)){
            //执行删除操作:delete操作
            usersDao.delUser(Integer.parseInt(id));
        }else if ("unlock".equals(type)){
            //执行解锁操作:update操作
            Users user = new Users();
            user.setId(Integer.parseInt(id));
            user.setUserStatus(0);
            usersDao.updateUser(user);
        }

        //跳转到首页
        resp.sendRedirect("/index");
    }
}

UserFindByIdServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/detail")
public class UserFindByIdServlet extends HttpServlet {
    /**
     * 创建对应的日志记录对象,通过不同的级别进行日志的记录【DEBUG/WARN/INFO/LOG】
     */
    private Logger log = Logger.getLogger(UserFindByIdServlet.class);

    private UsersDao usersDao = new UsersDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        log.info("获取到查询参数id-->"+id);
        Users user = usersDao.findById(Integer.parseInt(id));
        log.info("查询完成,查询到的数据-->"+user);
        req.setAttribute("user",user);
        req.getRequestDispatcher("detail.jsp").forward(req,resp);

    }
}

UserLoginServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    UsersDao usersDao = new UsersDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Users user = new Users();
        user.setName(username);
        user.setUserpass(password);
        boolean flag = usersDao.login(user);
        HttpSession session = req.getSession();
        if (flag){
            req.setAttribute("user",user);
            String remenber = req.getParameter("remenber");
            if ("true".equals(remenber)){
                //使用cookie
                Cookie cookie1 =new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);
//                cookie1.setPath("/index");
//                cookie2.setPath("/index");
                cookie1.setMaxAge(60*60*24);
                cookie2.setMaxAge(60*60*24);
                resp.addCookie(cookie1);
                resp.addCookie(cookie2);
                //使用session

                session.setAttribute("username",username);
                session.setAttribute("password",password);

            }

            session.setAttribute("user",user);

            req.getRequestDispatcher("/home.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }

    }
}

UsersFindServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class UsersFindServlet extends HttpServlet{

    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Users> list = usersDao.findAll();
        req.setAttribute("usersList",list);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}

UsersUpdateServlet

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/updateusers")
public class UsersUpdateServlet extends HttpServlet {

    private UsersDao usersDao = new UsersDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取用户要更新的数据
        String id = req.getParameter("id");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String remark = req.getParameter("remark");
        //创建用户对象
        Users user = new Users(Integer.parseInt(id), nickname, Integer.parseInt(age), gender, email, phone, new Date(),remark);
        //提交更新
        usersDao.updateUser(user);
        //查看更新后的用户数据
        resp.sendRedirect("/detail?id=" + user.getId());
    }
}

utils

CookieUtils

package com.demo.utils;

import javax.servlet.http.Cookie;

public class CookieUtils {
    public static Cookie findCookie(Cookie[] cookies, String name){
        if (cookies==null){
            //说明客户端没有携带Cookie
            return null;
        }else {
            //说明客户端携带Cookie
            for (Cookie cookie:cookies){
                if (name.equals(cookie.getName())){
                    return cookie;
                }
            }
            return null;
        }
    }
}

SqlSessionFactoryUtils

package com.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    private static String RESOURCE = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /**
     * 创建一个初始化SqlSessionFactory的方法
     */
    public static void initSqlSessionFactory(){
        try {
            InputStream is = Resources.getResourceAsStream(RESOURCE);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取工厂的方法
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

    public static void close(){
        SqlSession session = threadLocal.get();
        if (session!=null){
            session.close();
            threadLocal.set(null);
        }
    }
}

test

TestDemo

import com.demo.dao.UsersDao;
import com.demo.entity.Users;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestDemo {
    @Test
    public void test1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session= sqlSessionFactory.openSession();
        List<Users> list = session.selectList("findUsers");
        for (Users user:list){
            System.out.println(user);
        }
        session.close();
    }
    @Test
    public void test2(){

        UsersDao usersDao = new UsersDao();
        List<Users> l = usersDao.findAll();
        System.out.println(l);
    }
}

addusers.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>用户管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">
        #a1{
            margin-left:80%;
        }
    </style>
</head>
<body>
<%
    Object obj = session.getAttribute("user");
    if (obj==null){
        response.sendRedirect("/login.jsp");
    }
%>
<div class="container">
    <div class="row">
        <div class="page-header">
            <a id="a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录</a>
            <h1>泰斗贤若如后台管理系统 <small>欢迎${sessionScope.user.name}</small></h1>
        </div>
    </div>
    <div class="row">
        <div class="jumbotron">
            <h1>MyBatis基础入门!</h1>
            <p>通过一个项目来完成基础部分的学习</p>
            <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/index" role="button">首页</a></p>
            <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addusers.jsp" role="button">新增用户</a></p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form class="form-horizontal" action="${pageContext.request.contextPath}/addusers">
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label">用户账号</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户账号">
                    </div>
                </div>
                <div class="form-group">
                    <label for="userpass" class="col-sm-2 control-label">登录密码</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="userpass" name="userpass" placeholder="请输入登录密码">
                    </div>
                </div>
                <div class="form-group">
                    <label for="nickname" class="col-sm-2 control-label">昵称</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nickname" name="nickname" placeholder="请输入昵称">
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年龄</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="age" name="age"  placeholder="请输入年龄">
                    </div>
                </div>
                <div class="form-group">
                    <label for="gender" class="col-sm-2 control-label">性别</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="gender" name="gender"  placeholder="请输入性别">
                    </div>
                </div>
                <div class="form-group">
                    <label for="phone" class="col-sm-2 control-label">联系方式</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="phone" name="phone"  placeholder="请输入联系方式">
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">邮箱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
                    </div>
                </div>
                <div class="form-group">
                    <input type="submit" value="点击新增用户" class="btn btn-primary">
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

View Code

detail.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>单个用户查看</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">
        #a1{
            margin-left:80%;
        }
    </style>
</head>
<body>
<%
    Object obj = session.getAttribute("user");
    if (obj==null){
        response.sendRedirect("/login.jsp");
    }
%>
<div class="container">
    <div class="row">
        <div class="page-header">
            <a id="a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录</a>
            <h1>泰斗贤若如后台管理系统 <small>欢迎${sessionScope.user.name}</small></h1>
        </div>
    </div>
    <div class="row">
        <div class="jumbotron">
            <h1>MyBatis基础入门!</h1>
            <p>通过一个项目来完成基础部分的学习</p>
            <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/index" role="button">首页</a></p>
            <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addusers.jsp" role="button">新增用户</a></p>

        </div>
    </div>
    <c:set var="user" value="${user}"></c:set>
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form class="form-horizontal" action="${pageContext.request.contextPath}/updateusers">
                <input type="hidden" name="id" value="${user.id}">
                <div class="form-group">
                    <label class="col-sm-2 control-label">用户账号</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">${user.name}</p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">登录密码</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">********</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="nickname" class="col-sm-2 control-label">昵称</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nickname" value="${user.nickname}" name="nickname" placeholder="请输入昵称">
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年龄</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="age" name="age" value="${user.age}" placeholder="请输入年龄">
                    </div>
                </div>
                <div class="form-group">
                    <label for="gender" class="col-sm-2 control-label">性别</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="gender" name="gender" value="${user.gender}" placeholder="请输入性别">
                    </div>
                </div>
                <div class="form-group">
                    <label for="phone" class="col-sm-2 control-label">联系方式</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="phone" name="phone" value="${user.phone}" placeholder="请输入联系方式">
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">邮箱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="email" name="email" value="${user.email}" placeholder="请输入邮箱">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">账号创建时间</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">
                            <fmt:formatDate value="${user.createTime}" pattern="yyyy-MM-dd"></fmt:formatDate>
                        </p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">最后修改时间</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">
                            <fmt:formatDate value="${user.updateTime}" pattern="yyyy-MM-dd"></fmt:formatDate>
                        </p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">最后登录时间</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">
                            <fmt:formatDate value="${user.lastLogin}" pattern="yyyy-MM-dd"></fmt:formatDate>
                        </p>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">用户状态</label>
                    <div class="col-sm-10">
                        <c:if test="${user.userStatus == 0}">
                            <p class="form-control-static">正常</p>
                        </c:if>
                        <c:if test="${user.userStatus == 1}">
                            <p class="form-control-static">锁定</p>
                        </c:if>
                        <c:if test="${user.userStatus == 2}">
                            <p class="form-control-static">删除</p>
                        </c:if>
                    </div>
                </div>
                <div class="form-group">
                    <label for="remark" class="col-sm-2 control-label">备注</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="remark" value="${user.remark}" name="remark" placeholder="请输入备注">
                    </div>
                </div>
                <div class="form-group">
                    <input type="submit" value="提交数据更新" class="btn btn-primary">
                </div>
            </form>
        </div>
    </div>
    <div class="row">
        <table class="table table-striped">
            <tr>
                <th>地址编号</th>
                <th>国家</th>
                <th>省</th>
                <th>市</th>
                <th>县</th>
                <th>街道</th>
                <th>详细地址</th>
                <th>是否默认</th>
            </tr>
            <c:forEach var="addr" items="${user.addresses}">
                <tr>
                    <td>${addr.id}</td>
                    <td>${addr.nation}</td>
                    <td>${addr.province}</td>
                    <td>${addr.city}</td>
                    <td>${addr.country}</td>
                    <td>${addr.street}</td>
                    <td>${addr.remark}</td>
                    <c:if test="${addr.defaultAddr == true}">
                        <td>默认地址</td>
                    </c:if>
                    <c:if test="${addr.defaultAddr == false}">
                        <td>-----</td>
                    </c:if>
                </tr>
            </c:forEach>
        </table>
    </div>
</div>
</body>
</html>

View Code

exit.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>退出登录</title>
</head>
<body>
<%
    Object obj = session.getAttribute("user");
    if (obj!=null){
        //销毁session
        session.removeAttribute("user");
        response.sendRedirect("/login.jsp");
    }else {
        //页面重定向到登录页面
        response.sendRedirect("/login.jsp");
    }
%>
</body>
</html>

View Code

home.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>跳转</title>
</head>
<body>
<%
    response.sendRedirect("/index");
%>
</body>
</html>

View Code

index.jsp


<%@ page import="com.demo.entity.Users" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>用户管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">
        #a1{
            margin-left:80%;
        }
    </style>
</head>
<body>

<%
 Object obj = session.getAttribute("user");
// Users user = null;
// if (obj instanceof Users){
//     user = (Users)obj;
// }
 if (obj==null){
     response.sendRedirect("/login.jsp");
 }
%>
<div class="container">
    <div class="row">
        <div class="page-header">
            <a id="a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录</a>
            <h1>泰斗贤若如后台管理系统 <small>欢迎${sessionScope.user.name}</small></h1>

        </div>
    </div>
    <div class="row">
        <div class="jumbotron">
            <h1>MyBatis基础入门!</h1>
            <p>通过一个项目来完成基础部分的学习</p>
            <p><a class="btn btn-primary btn-lg" href="https://www.cnblogs.com/zyx110/" role="button">请关注泰斗贤若如博客园</a></p>
            <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addusers.jsp" role="button">新增用户</a></p>
        </div>
    </div>
    <div class="row">
        <table class="table table-hover table-striped">
            <tr>
                <th>用户编号</th>
                <th>登录账号</th>
                <th>用户昵称</th>
                <th>邮箱</th>
                <th>联系方式</th>
                <th>账号创建时间</th>
                <th>用户状态</th>
                <th>操作</th>
            </tr>
            <c:forEach var="user" items="${usersList}">
                <tr>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.nickname}</td>
                    <td>${user.email}</td>
                    <td>${user.phone}</td>
                    <td>
                        <fmt:formatDate value="${user.createTime}" pattern="yyyy-MM-dd HH:mm:ss"></fmt:formatDate>
                    </td>
                    <c:if test="${user.userStatus == 0}">
                        <td>正常</td>
                    </c:if>
                    <c:if test="${user.userStatus == 1}">
                        <td>锁定</td>
                    </c:if>
                    <c:if test="${user.userStatus == 2}">
                        <td>删除</td>
                    </c:if>
                    <td>
                        <a href="${pageContext.request.contextPath}/detail?id=${user.id}">查看</a>
                        <c:if test="${user.userStatus == 0}">
                            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=lock">锁定</a>
                        </c:if>
                        <c:if test="${user.userStatus == 1}">
                            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=unlock">解锁</a>
                        </c:if>
                        <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=del">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </div>
</div>
</body>
</html>

View Code

login.jsp


<%@ page import="com.demo.entity.Users" %>
<%@ page import="com.demo.utils.CookieUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>登录</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<%
    String msg = (String) request.getAttribute("msg");
    String username="";
    String password="";
//    Cookie[] cookies = request.getCookies();
//    Cookie cookie1 = CookieUtils.findCookie(cookies,"username");
//    Cookie cookie2 = CookieUtils.findCookie(cookies,"password");
//
//    if (cookie1!=null&&cookie2!=null){
//        username = cookie1.getValue();
//        password = cookie2.getValue();
//    }
    username = (String)session.getAttribute("username");
    password = (String)session.getAttribute("password");

%>
<div class="container">
    <div class="row">
        <div class="page-header">
            <h1>泰斗贤若如用户管理系统 <small>来登录试试吧!</small></h1>
        </div>
    </div>
    <div class="row">
        <form class="form-horizontal" action="${pageContext.request.contextPath}/login">
            <div class="form-group">
                <label for="username" class="col-sm-2 control-label">用户名</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="username" name="username" value="<%=username%>">
                </div>
            </div>
            <div class="form-group">
                <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="inputPassword3" name="password" value="<%=password%>">
                </div>
            </div>
            <%
            if (msg!=null){
            %>
            <span style="color: red">${msg}</span>
            <%
                }
            %>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" name="remenber" value="true" checked="checked"> 记住我
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-default">登录</button>
                </div>
            </div>
        </form>
    </div>
</div>
</body>
</html>

View Code

Mybatis案例升级版——小案例大道理

*****************************************************************************************************

我的博客园地址: https://www.cnblogs.com/zyx110/

【原创声明】此篇为作者原创,未经本人同意不得转载,经本人同意转载请说明出处。

我不能保证我所说的都是对的,但我能保证每一篇都是用心去写的,我始终认同“分享的越多,你的价值增值越大”,欢迎大家关注我的技术分享“Java匹马行天下”和学习心得分享“匹马行天下”,在分享中进步,越努力越幸运,人生赢在转折处,改变从现在开始!

支持我的朋友们记得点波推荐哦,您的肯定就是我前进的动力。

原文  http://www.cnblogs.com/zyx110/p/11470038.html
正文到此结束
Loading...