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

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

前言:

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

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

案例准备

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

案例演示

Mybatis案例升级版——小案例大道理_第1张图片

 

 Mybatis案例升级版——小案例大道理_第2张图片

 Mybatis案例升级版——小案例大道理_第3张图片

 Mybatis案例升级版——小案例大道理_第4张图片

 

 Mybatis案例升级版——小案例大道理_第5张图片

案例结构及代码

 Mybatis案例升级版——小案例大道理_第6张图片

 

 

 Mybatis案例升级版——小案例大道理_第7张图片

 

 

 

表结构

users表

Mybatis案例升级版——小案例大道理_第8张图片

 

 Mybatis案例升级版——小案例大道理_第9张图片

 

 

address表

Mybatis案例升级版——小案例大道理_第10张图片

 

 Mybatis案例升级版——小案例大道理_第11张图片

 

 

 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

 

     
         org.mybatis
         mybatis
         3.4.6
     
     
         mysql
         mysql-connector-java
         5.1.38
     
     
         javax.servlet
         javax.servlet-api
         3.1.0
     
     
         javax.servlet
         jstl
         1.2
     
     
         log4j
         log4j
         1.2.17
     
     
         junit
         junit
         4.12
         test
     
 
View Code

 

mybatis-config.xml

 
 
 
     
     
         
         
             
             
             
             
                 
                 
                 
                 
             
         
     
     
     
         
         
     
 

  

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

 
 
 
 
     
     
     
     
         
         
         
         
         
     
     
     
         username, userpass, nickname, age, gender, email, phone, createTime, updateTime, lastLogin, userstatus, remark
     
         insert into users( )
         values(#{name},#{userpass}, #{nickname}, #{age}, #{gender}, #{email}, #{phone}, #{createTime}, #{updateTime}, #{lastLogin}, #{userStatus}, #{remark})
     
     
         
         
     
     
         
     
     
         update users
         
             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}
     
     
         
             
             
             
             
             
             
             
             
             
             
             
             
         
     
     
         delete from users where id = #{id}
     
 

  

web.xml

 
 
     mybatispro
         login.jsp
     

  

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 list;
     private Users user;
 ​
     public SqlSession getSession(){
         session =  SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
         return session;
     }
 ​
     /**
      * 查询所有用户
      * @return
      */
     public List 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
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
getAddresses() { return addresses; } public void setAddresses(List
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 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 threadLocal = new ThreadLocal();

    /**
     * 创建一个初始化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 list = session.selectList("findUsers");
        for (Users user:list){
            System.out.println(user);
        }
        session.close();
    }
    @Test
    public void test2(){

        UsersDao usersDao = new UsersDao();
        List 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" %>


    用户管理中心
    "stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    
    
    


<%
    Object obj = session.getAttribute("user");
    if (obj==null){
        response.sendRedirect("/login.jsp");
    }
%>
class="container">
class="row">
class="page-header"> "a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录

泰斗贤若如后台管理系统 欢迎${sessionScope.user.name}

class="row">
class="col-md-8 col-md-offset-2">
class="form-horizontal" action="${pageContext.request.contextPath}/addusers">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="username" name="username" placeholder="请输入用户账号">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="userpass" name="userpass" placeholder="请输入登录密码">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="nickname" name="nickname" placeholder="请输入昵称">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="age" name="age" placeholder="请输入年龄">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="gender" name="gender" placeholder="请输入性别">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="phone" name="phone" placeholder="请输入联系方式">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
class="form-group"> "submit" value="点击新增用户" class="btn btn-primary">
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" %>


    单个用户查看
    "stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    
    
    


<%
    Object obj = session.getAttribute("user");
    if (obj==null){
        response.sendRedirect("/login.jsp");
    }
%>
class="container">
class="row">
class="page-header"> "a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录

泰斗贤若如后台管理系统 欢迎${sessionScope.user.name}

set var="user" value="${user}">set>
class="row">
class="col-md-8 col-md-offset-2">
class="form-horizontal" action="${pageContext.request.contextPath}/updateusers"> "hidden" name="id" value="${user.id}">
class="form-group">
class="col-sm-10">

class="form-control-static">${user.name}

class="form-group">
class="col-sm-10">

class="form-control-static">********

class="form-group">
class="col-sm-10"> "text" class="form-control" id="nickname" value="${user.nickname}" name="nickname" placeholder="请输入昵称">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="age" name="age" value="${user.age}" placeholder="请输入年龄">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="gender" name="gender" value="${user.gender}" placeholder="请输入性别">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="phone" name="phone" value="${user.phone}" placeholder="请输入联系方式">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="email" name="email" value="${user.email}" placeholder="请输入邮箱">
class="form-group">
class="col-sm-10">

class="form-control-static"> "${user.createTime}" pattern="yyyy-MM-dd">

class="form-group">
class="col-sm-10">

class="form-control-static"> "${user.updateTime}" pattern="yyyy-MM-dd">

class="form-group">
class="col-sm-10">

class="form-control-static"> "${user.lastLogin}" pattern="yyyy-MM-dd">

class="form-group">
class="col-sm-10"> if test="${user.userStatus == 0}">

class="form-control-static">正常

if> if test="${user.userStatus == 1}">

class="form-control-static">锁定

if> if test="${user.userStatus == 2}">

class="form-control-static">删除

if>
class="form-group">
class="col-sm-10"> "text" class="form-control" id="remark" value="${user.remark}" name="remark" placeholder="请输入备注">
class="form-group"> "submit" value="提交数据更新" class="btn btn-primary">
class="row"> class="table table-striped"> var="addr" items="${user.addresses}"> if test="${addr.defaultAddr == true}"> if> if test="${addr.defaultAddr == false}"> if>
地址编号 国家 街道 详细地址 是否默认
${addr.id} ${addr.nation} ${addr.province} ${addr.city} ${addr.country} ${addr.street} ${addr.remark} 默认地址 -----
View Code

 

exit.jsp

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


    退出登录


<%
    Object obj = session.getAttribute("user");
    if (obj!=null){
        //销毁session
        session.removeAttribute("user");
        response.sendRedirect("/login.jsp");
    }else {
        //页面重定向到登录页面
        response.sendRedirect("/login.jsp");
    }
%>

View Code

 

home.jsp

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


    跳转


<%
    response.sendRedirect("/index");
%>

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" %>


    用户管理中心
    "stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    
    
    



<%
 Object obj = session.getAttribute("user");
// Users user = null;
// if (obj instanceof Users){
//     user = (Users)obj;
// }
 if (obj==null){
     response.sendRedirect("/login.jsp");
 }
%>
class="container">
class="row">
class="page-header"> "a1" class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/exit.jsp" role="button" >退出登录

泰斗贤若如后台管理系统 欢迎${sessionScope.user.name}

class="row"> class="table table-hover table-striped"> var="user" items="${usersList}"> if test="${user.userStatus == 0}"> if> if test="${user.userStatus == 1}"> if> if test="${user.userStatus == 2}"> if>
用户编号 登录账号 用户昵称 邮箱 联系方式 账号创建时间 用户状态 操作
${user.id} ${user.name} ${user.nickname} ${user.email} ${user.phone} "${user.createTime}" pattern="yyyy-MM-dd HH:mm:ss"> 正常 锁定 删除 "${pageContext.request.contextPath}/detail?id=${user.id}">查看 if test="${user.userStatus == 0}"> "${pageContext.request.contextPath}/deluser?id=${user.id}&type=lock">锁定 if> if test="${user.userStatus == 1}"> "${pageContext.request.contextPath}/deluser?id=${user.id}&type=unlock">解锁 if> "${pageContext.request.contextPath}/deluser?id=${user.id}&type=del">删除
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" %>


    登录
    "stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    
    


<%
    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");

%>
class="container">
class="row">
class="page-header">

泰斗贤若如用户管理系统 来登录试试吧!

class="row">
class="form-horizontal" action="${pageContext.request.contextPath}/login">
class="form-group">
class="col-sm-10"> "text" class="form-control" id="username" name="username" value="<%=username%>">
class="form-group">
class="col-sm-10"> "password" class="form-control" id="inputPassword3" name="password" value="<%=password%>">
<% if (msg!=null){ %> "color: red">${msg} <% } %>
class="form-group">
class="col-sm-offset-2 col-sm-10">
class="checkbox">
class="form-group">
class="col-sm-offset-2 col-sm-10">
View Code

 

                                                                Mybatis案例升级版——小案例大道理_第12张图片

 

 

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

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

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

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

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

               

你可能感兴趣的:(Mybatis案例升级版——小案例大道理)