day08

SSM

SSM 应用搭建

1. 部署 Spring + Spring MVC

  1. 导入包
    

        
            org.mybatis
            mybatis
            3.4.5
        

        
            mysql-connector-java
            mysql-connector-java
            5.1.37
        

        
            junit
            junit
            4.7
        

        
            org.mybatis
            mybatis-spring
            1.3.1
        

        
            org.springframework
            spring-webmvc
            4.3.8.RELEASE
        

        
            org.springframework
            spring-jdbc
            4.3.11.RELEASE
        

        
            commons-dbcp
            commons-dbcp
            1.4
        

    

  1. 配置Spring MVC的前端控制器 web.xml:
    
        
        DispatcherServlet
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:conf/spring-*.xml
        
        1
    
    
        DispatcherServlet
        *.do
    

Spring 配置文件存在conf 文件夹中,并且其文件名符合spring-*.xml 规则。

  1. 添加数据库连接参数文件 conf/db.properties
    url=jdbc:mysql://localhost:3306/tedustore
    driver=com.mysql.jdbc.Driver
    user=root
    password=root
    initsize=1
    maxsize=5
  1. 添加数据库连接池配置文件 spring-db.xml
    
    
        
        
        
        
        
            
        
        
        
            
            
            
            
            
            
        
        
    
  1. 添加 Spring MVC 配置文件 spring-mvc.xml:
    
    
        
        
        
        
        
        
            
            
        
        
    
  1. 部署测试...

2. 部署 Spring MyBatis

  1. 导入包(略)

  2. 添加Spring MyBatis配置文件 spring-mybatis.xml

        
        
            
            
                  
                
            
            
                
                 
            
        

其中mapperLocations属性被临时注释掉了,再以后有Mapper文件以后打开。

  1. 利用 JUnit 进行离线测试:
    public class MyBatisTest {

        ClassPathXmlApplicationContext ctx;
        
        @Before
        public void init() {
            ctx = new ClassPathXmlApplicationContext("conf/spring-db.xml","conf/spring-mybatis.xml");
        }
        
        @Test
        public void testSqlSession() {
            SqlSessionFactory factory = ctx.getBean("sqlSessionFactory", SqlSessionFactory.class);
            SqlSession session = factory.openSession();
            
            System.out.println(session);
            
            session.close();
        }
        
    }

实现用户列表功能

原理:

1.png

1. 数据层

实现步骤:

  1. 数据表结构:
        desc user;
        +-------------+-------------+------+-----+-------------------+-----------------------------+
        | Field       | Type        | Null | Key | Default           | Extra                       |
        +-------------+-------------+------+-----+-------------------+-----------------------------+
        | id          | int(11)     | NO   | PRI | NULL              | auto_increment              |
        | username    | varchar(20) | YES  |     | NULL              |                             |
        | password    | varchar(30) | YES  |     | NULL              |                             |
        | email       | varchar(20) | YES  |     | NULL              |                             |
        | mobile      | varchar(20) | YES  |     | NULL              |                             |
        | create_time | timestamp   | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
        +-------------+-------------+------+-----+-------------------+-----------------------------+
  1. 添加实体类 User
    public class User implements Serializable {
        private static final long serialVersionUID = -7291170424207323214L;
    
        private Integer id;
        private String username;
        private String password;
        private String mobile;
        private String email;
        private Date createTime;
        
        public User() {
        }
    
        public User(Integer id, String username, String password, String mobile, String email, Date createTime) {
            super();
            this.id = id;
            this.username = username;
            this.password = password;
            this.mobile = mobile;
            this.email = email;
            this.createTime = createTime;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getMobile() {
            return mobile;
        }
    
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
    
        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;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", username=" + username + ", password=" + password + ", mobile=" + mobile
                    + ", email=" + email + ", createTime=" + createTime + "]";
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            User other = (User) obj;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            return true;
        }
        
    }
  1. 声明Dao接口
    public interface UserDao {
        /**
            * 查询全部的用户信息
            * @return 用户信息列表
            */
        List findAllUsers();
    }   
  1. 添加映射配置文件 mapping/userMapper.xml
    
    
    
        
        
        
        
    
  1. 更新db.properties

    url=jdbc:mysql://localhost:3306/tedustore

  2. 更新 spring-mybatis.xml

     
  1. 利用JUnit进行离线测试
    public class UserDaoTest {
        ClassPathXmlApplicationContext ctx;
        UserDao dao;
        @Before //在全部测试案例之前执行的方法
        public void init(){
            ctx = new ClassPathXmlApplicationContext(
                    "conf/spring-db.xml",
                    "conf/spring-mybatis.xml");
            dao = ctx.getBean("userDao",UserDao.class);
        }
        @After //全部测试案例执行之后执行 destory方法
        public void destory(){
            ctx.close();
        }
        
        @Test
        public void testFindAllUsers(){
            List list=dao.findAllUsers();
            for (User user : list) {
                System.out.println(user);
            }
        }
    }

2. 业务层

步骤

  1. 声明业务层接口
    public interface UserService {
        /**
        * 获取全部用户信息
        * @return 用户信息
        */
        List list();
    }
  1. 实现业务层
    @Service("userService") //当前类是业务层组件
    public class UserServiceImpl implements UserService {
        
        @Resource
        private UserDao userDao;
        
        public List list() {
            //调用数据层处理业务
            return userDao.findAllUsers();
        }
    }
  1. 添加配置文件 spring-service.xml
    
    
        
        
        
        
    
  1. 测试:
    public class UserServiceTest {
        ClassPathXmlApplicationContext ctx;
        UserService service;
        @Before 
        public void init(){
            ctx=new ClassPathXmlApplicati onContext(
                    "conf/spring-service.xml",
                    "conf/spring-mybatis.xml",
                    "conf/spring-db.xml");
            service = ctx.getBean("userService",
                    UserService.class);
        }
        @After
        public void destory(){
            ctx.close();
        }
        
        @Test
        public void testList(){
            List list=service.list();
            for (User user : list) {
                System.out.println(user);
            }
        }
    }

3. 控制器 和 界面

  1. 添加控制器类
    /**
    * 控制器,用于处理用户有关的业务功能 
    *
    */
    @Controller
    @RequestMapping("/user")
    public class UserController {
        
        @Resource
        private UserService userService;
        
        @RequestMapping("/users.do")
        public String users(ModelMap map){
            //访问业务层获取全部用户信息
            List list=userService.list();
            map.put("users", list);
            //System.out.println(list);
            //转发到JSP页面,显示结果
            return "user/list";
        }
    }
  1. 重用Servlet项目的界面
3.png
  1. 测试
2.png

翻页功能

原理:

1. 重构数据层

  1. 重构Dao接口, 添加翻页参数和行数统计方法
    /**
    * 查询全部的用户信息
    * @return 用户信息列表
    */
    List findAllUsers(
            @Param("start") int start, 
            @Param("size") int size);
    
    /**
    * 统计用户的数量
    */
    int countUsers();
  1. 在 userMapper.xml 中声明SQL
    
    
    

SQL 语句需要使用 resultType="int" 声明返回值,DML语句不需要声明返回值类型,会自动返回int值。

  1. 测试
    @Test
    public void testFindAllUsers(){
        List list=dao.findAllUsers(4,4);
        for (User user : list) {
            System.out.println(user);
        }
    }
    
    @Test
    public void testCountUsers(){
        int n = dao.countUsers();
        System.out.println(n); 
    }

2. 重构业务层

  1. 重构业务层方法 UserService
    /**
    * 获取全部用户信息
    * @return 用户信息
    */
    List list(Integer page);
    
    /**
    * 获取用户信息的页数
    */
    int listPages();
  1. 实现方法 UserServiceImpl
    public List list(Integer page) {
        if(page==null){
            page=1;
        }
        //计算页面范围
        int size = 8;
        int start = (page-1)*size;
        
        //调用数据层处理业务
        return userDao.findAllUsers(start, size);
    }
    
    public int listPages() {
        int rows = userDao.countUsers();
        int size = 8;
        int pages = rows/size;
        if(rows%size==0){
            return pages;
        }
        return pages+1;
    }
  1. 测试
    @Test
    public void testList(){
        List list=service.list(null);
        for (User user : list) {
            System.out.println(user);
        }
    }
    
    @Test
    public void testListPages(){
        int n = service.listPages();
        System.out.println(n); 
    }

3. 重构控制器

    @RequestMapping("/users.do")
    public String users(ModelMap map, 
            @RequestParam(
            required=false,
            value="page") Integer page){
        //访问业务层获取全部用户信息
        List list=userService.list(page);
        int pages = userService.listPages();
        map.put("users", list);
        map.put("pages", pages);
        //System.out.println(list);
        //转发到JSP页面,显示结果
        return "user/list";
    }
  1. JSP页面重用即可

  2. 测试...

实现添加用户功能

原理:

4.png

1. 显示添加界面

  1. 在控制器中添加方法,显示添加页面
    /**
        * 在控制器中添加方法,显示添加页面
        */
    @RequestMapping("/add.do")
    public String add(){
        return "user/add";
    }
  1. 测试

2. 实现保存功能

  1. 添加dao方法
    int insertUser(User user);
  1. 添加SQL
     
        insert into user(
            id,
            username,
            password,
            mobile,
            email,
            create_time
        )values(
            null,
            #{username},
            #{password},
            #{mobile},
            #{email},
            #{createTime}
        )
    
  1. 测试
    @Test
    public void testInsertUser(){
        User user=new User(null, "Andy", 
        "123", "119", "[email protected]", new Date());
        int n = dao.insertUser(user);
        System.out.println(n);
    }

3. 业务层

  1. 添加业务层方法
User save(String username,String password,String mobile,String email);
  1. 实现业务层方法
    public User save(String username, 
            String password, String mobile, 
            String email) {
        User user=new User(null,
                username, password, mobile, 
                email, new Date()); 
        int n = userDao.insertUser(user);
        if(n!=1){
            throw new RuntimeException("添加失败!");
        }
        return user;
    }
  1. 测试
    @Test
    public void testSave() {
        User user = service.save("Wang", "123", "12345678", "[email protected]");
        System.out.println(user);
    }

4. 控制器

  1. 添加控制器方法
    @RequestMapping("/save.do")
    public String save(String username, 
            String password, String mobile, 
            String email){
        User user=userService.save(
                username, password, mobile, email);
        return "redirect:users.do";
    }
  1. 测试

作业

  1. 利用SSM实现用户信息的管理。

你可能感兴趣的:(day08)