专栏首页泰斗贤若如Mybatis案例升级版——小案例大道理

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

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

前言:

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

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

案例准备

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

案例演示

案例结构及代码

表结构

users表
address表
View Code

pom.xml

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

View Code

detail.jsp

View Code

exit.jsp

View Code

home.jsp

View Code

index.jsp

View Code

login.jsp

View Code

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 完整案例分析再加知识整合——艾特工厂方法模式,超详细的

    泰斗贤若如
  • 完整案例分析再加知识整合——艾特抽象工厂模式,超详细的

    泰斗贤若如
  • 抽象类和接口到底是什么“垃圾“——教你分类

      这几天给别人讲JavaSE基础,又把面向对象看了一遍,讲的时候发现一个问题,就是当时讲抽象类和接口的时候说接口也是抽象类,是个特殊的抽象类,当时听的时候别人...

    泰斗贤若如
  • JavaWeb(二)cookie与session的应用

    前言   前面讲了一堆虚的东西,所以这篇我们来介绍一下cookie和session的应用。 一、使用cookie记住用户名 1.1、思路介绍 ? 1.2、实现代...

    用户1195962
  • [Spring Boot] Spring boot 整合mybatis、postgresql [Gradle构建项目]

    架构探险之道
  • 产品前端重构(TypeScript、MVC框架设计)

    最近两周完成了对公司某一产品的前端重构,本文记录重构的主要思路及相关的设计内容。 公司期望把某一管理类信息系统从项目代码中抽取、重构为一个可复用的产品。该系统的...

    用户1172223
  • 百度地图自定义marker(图标),layer(覆盖层)

    本文只要涉及的内容有,web中动态引入百度地图,基于百度地图的本地搜索(公交,地铁,停车场),自定义marker,layer,接入微信内置地图(微信中使用第三方...

    j_bleach
  • 线上应用故障排查之一:高CPU占用

    线上应用故障排查之一:高CPU占用 一个应用占用CPU很高,除了确实是计算密集型应用之外,通常原因都是出现了死循环。 以我们最近出现的一个实际故障为例,介绍怎么...

    小小科
  • Android OkGo网络请求库 自定义回调支持带泛型的对象

    这里写了两种方式请求接口 (文中用了Java和Kotlin两种语言 没有特殊标示的都是Java)

    剑行者
  • dubbo序列化问题(三)子类覆盖父类字段hession反序列化获取不到

    在进行dubbo开发中遇到一个问题,当是用hession2进行序列化时,子类和父类有相同的字段时,hession2反序列化获取不到该字段数据,如下:

    一笠风雨任生平

扫码关注云+社区

领取腾讯云代金券