关于搭建SSM框架的步骤以及相关配置(一)

关于搭建SSM框架的步骤以及相关配置

学习搭建一个SSM框架,模拟实现登录功能:

1,在mysql中创建数据库和表

    库名:db
    表名:t_user 
    字段:
        id         int   auto_increment primary key
        username   varchar(50) unique
        password   varchar(32)
        email      varchar(50)
        phone      varchar(32)
    代码:
        create table t_user(
            id int auto_increment primary key,
            username varchar(50) unique,
            password varchar(32),
            email varchar(50),
            phone varchar(32)
        )
    插入数据:
    insert into t_user values(1,'admin','123456','[email protected]','13800138000');

2,在eclipse中创建一个maven工程ssm

2.1:添加web.xml:

在JavaEE视图下展开工程,在DeploymentDescriptor.ssm上右键,点击Generate Deployment Descriptor Stub;

2.2:添加Tomcat运行环境:

在工程上右键,选择Properties属性,在maven下选择TargetedRuntimes,勾选Apache Tomcat v8.5,点击Apply and Close;

2.3:添加依赖jar包:

spring-webmvc,junit,commons-dbcp,mysql,mybatis,mybatis-spring,jstl,spring-jdbc打开http://mvnrepository.com/,按以上关键字搜索选择合适版本,拖入pom.xml文件中;




    org.springframework
    spring-webmvc
    5.0.8.RELEASE



    junit
    junit
    4.12
    test



    commons-dbcp
    commons-dbcp
    1.4



    mysql
    mysql-connector-java
    8.0.11



 org.mybatis
  mybatis
  3.4.6



    org.mybatis
    mybatis-spring
    1.3.2



    javax.servlet
    jstl
    1.2



    org.springframework
    spring-jdbc
    5.0.8.RELEASE
   

2.4:在src/main/resources文件夹下添加配置文件:

2.4.1:db.properties———配置数据库连接池
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://LOCALHOST:3306/db?useUnicode=true&characterEncoding=UTF-8
username=root
password=


driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://LOCALHOST:3306/db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=

注:com.mysql.jdbc.Driver是mysql-connector-java 5中的,而com.mysql.cj.jdbc.Driver是mysql-connector-java 6以后的。区别可借鉴https://blog.csdn.net/u012999325/article/details/80619511

2.4.2:spring-mvc.xml ——-控制器
< ?xml version=”1.0” encoding=”UTF-8”?>
< beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:jdbc=”http://www.springframework.org/schema/jdbc”
xmlns:jee=”http://www.springframework.org/schema/jee”
xmlns:tx=”http://www.springframework.org/schema/tx”
xmlns:aop=”http://www.springframework.org/schema/aop”
xmlns:mvc=”http://www.springframework.org/schema/mvc”
xmlns:util=”http://www.springframework.org/schema/util”
xmlns:jpa=”http://www.springframework.org/schema/data/jpa”
xsi:schemaLocation=”
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd“>





    
    



< /beans>

2.4.3:application-service.xml——–业务层
在bean中插入:
< !– 扫描包 base-package表示可以扫描到当前包和其子包下的所有类 –>
< context:component-scan base-package=”cn.tedu.service”/>

2.4.4:application-dao.xml———-持久层
在bean中插入:

  
           
       
       
        
        
        
           
       
       
       
       
           
       
       
       
            
            
            
            
       

2.5:在src/main/resources下新建mappers文件夹,用于存放dao层sql执行语句配置文件

 






    insert into t_dept(
        dept_name,dept_loc
    )values(
        #{deptName},#{deptLoc}
    )






    delete from t_dept 
    where 
        id=#{id}    





    update t_dept set
         dept_name=#{deptName},
         dept_loc=#{deptLoc}
    where id=#{id}  



2.6:在web.xml中配置前端控制器——读spring-mvc.xml, 配置读取application-service.xml和application-dao.xml



    contextConfigLocation
    classpath:application-*.xml


    org.springframework.web.context.ContextLoaderListener



    filter
    org.springframework.web.filter.CharacterEncodingFilter
    
        encoding
        utf-8
    


    filter
    /*



    dispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
        contextConfigLocation
        classpath:spring-mvc.xml
    
    1


    dispatcherServlet
    *.do

3,持久层

注:
请求处理顺序:浏览器发送请求–>控制器–>业务层–>持久层–>数据库 ,搭建工程时按反向顺序准备

3.1:在cn.tedu.bean包中创建实体类User,属性名和类型匹配t_user表字段;

public class User {
private int id;
private String username;
private String password;
private String email;
private String phone;
setter和getter方法……
重写toString方法
}

3.2:在cn.tedu.dao包中定义接口UserDao,定义方法

public interface UserDao {
    User selectByUsername(String username);
}

3.3:在cn.tedu.dao包中定义接口的实现类UserDaoImpl,实现UserDao接口,加@Repository注解实例化;

package cn.tedu.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.stereotype.Repository;
import cn.tedu.bean.User;
/**
 *@Component:通用的注解:实例化对象
 *@Controller:实例化控制器类的对象
 *@Service:实例化业务层类的对象
 *@Repository:实例化持久层类的对象
 * 1,@Repository表示实例化持久层的注解
 * 2,id名默认为类名第一个字母小写
 * 3,id名可以自定义:("userDao") 
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao{
//1,@Resource 是tomcat运行环境依赖jar包中定义的注解
//2,@Resource 用来实现依赖注入
//3,@Resource 实现依赖注入,可以省略set方法
//4,@Resource 默认通过byName方式依赖注入
//5,@Resource 如果没有匹配的属性,那么自动按照byType方式实现依赖注入
//6,@Resource(name="dataSource")表示找指定id名字为dataSource的对象依赖注入(参考2.4.4持久层配置文件)
@Resource
private DataSource dataSource;//关于Datasource与数据库连接池的区别请参考(https://www.xuebuyuan.com/3222156.html)
public User selectByUsername(String username)  {
    //1,获取Connection
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    User user = null;       
    try {
        conn = dataSource.getConnection();
        //2,获取PreparedStatement对象
        String sql = "select * from t_user where username=?";
        ps = conn.prepareStatement(sql);
        //3,给?占位符赋值
        ps.setString(1, username);
        //4,执行sql语句,返回ResultSet
        rs = ps.executeQuery();         
        //5,遍历集合rs,把数据封装成User对象,返回
        if(rs.next()) {
            int id = rs.getInt("id");
            String password = rs.getString("password");
            String email = rs.getString("email");
            String phone = rs.getString("phone");
            user = new User();
            user.setId(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setPhone(phone);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage());
    }finally {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(ps!=null) {
                ps.close();
            }
            if(conn!=null) {
                conn.close();
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        }           
    }       
    return user;
}

}

3.4:在src/test/java中新建test包,包中创建测试类TestUser,写测试方法;

public class TestUser { 
@Test
public void testSelectByName(){
    //获取spring容器对象
    AbstractApplicationContext ac = new ClassPathXmlApplicationContext("application-dao.xml");
    //获取bean对象
    UserDao userDao = ac.getBean("userDaoImpl",UserDaoImpl.class);
    //调用方法
        System.out.println(userDao.selectByUsername("admin"));
    //关闭容器
        ac.close();

}
}

4,业务层

4.1:在cn.tedu.service包中新建UserService接口,定义调用持久层的方法;

public interface UserService {
    User getUserByUsername(String username,String password);
}

4.2:在cn.tedu.serevice包中新建接口的实现类UserServiceImpl,重写接口方法实现查询登录功能;

//@Service 表示实例化业务层对象
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserDao userDao;
public User getUserByUsername(String username,String password) {
    User user = userDao.selectByUsername(username);
    if(user!=null) {
        if(password.equals(user.getPassword())) {
            return user;
        }else {
            throw new RuntimeException("密码不正确!");
        }
    }else {
        throw new RuntimeException("用户名不存在!");
    }       
}

}

4.3:在test包的TestUser类中测试业务类

@Test
public void testGetByUsername() {
    AbstractApplicationContext ac = new ClassPathXmlApplicationContext(
            "application-service.xml","application-dao.xml");
    UserService userService = ac.getBean("userService",UserService.class);
    User user = userService.getUserByUsername("admin", "123456");
    System.out.println(user);       
    ac.close();
}

业务层测试没问题后准备写控制层

5,控制层

5.1:在cn.tedu.controller包中新建UserController类

//@Controller   表示实例化控制层对象
//@RequestMapping("/user")表示添加模块名,登录时应加上模块名:user/showLogin.do
@Controller 
@RequestMapping("/user")
public class UserController {
    @Resource(name="userService")
    private UserService us;
    //显示登录页面
    @RequestMapping("/showLogin.do")
    public String showLogin() {     
        return "login";
    }
    //登录功能
    @RequestMapping("/login.do")
    public String login(@RequestParam("username") String username,String password,
                                        ModelMap map,HttpSession session) {
        try {
            User user = us.getUserByUsername(username, password);
            session.setAttribute("user", user);
            return "index";
        } catch (RuntimeException ex) {
            map.addAttribute("error", ex.getMessage());
            return "login";
        }               
    }
}

5.2:在WEB-INF下新建web文件夹,在web中新建index.jsp; login.jsp;

login.jsp :

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


用户登录


    
用户名
密 码
${error }

index.jsp :

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


首页


    用户${user.username }登录成功!
显示个人信息

5.3:在工程上右键Run As // run on server 部署,在浏览器输入:http://localhost:8080/ssm/user/showLogin.do登录测试。

你可能感兴趣的:(学习笔记)