zoukankan      html  css  js  c++  java
  • SSM(Spring+SpringMVC+Mybatis)+Mysql 框架整合搭建流程以及其间注意事项

    复习SSM框架,太久没用自己手动撘一个,发现自己还是有很多地方忘记了和没注意的事项。。。

    首先,直接给出总流程

    零、引jar包

      1、引包(或者写maven.pom)

    一、数据库部分

      设计数据库各表结构,主键、外键等

    二、Model部分

      1、根据表结构写相对应的bean(*.java)

      2、配置mybatis.xml

        主要写typeAlias(别名)

      3、根据别名编写  *Mapper.xml  放在beanMapper包下

    三、Controller部分

      1、根据  *Map.xml 编写 *Dao.java 与 *DaoImp.java

      2、根据 *Dao.java 编写 *Service.java 与 *ServiceImp.java(属性:*Dao)

      3、根据  *Service.java 编写 *Controller.java (属性:*Service)

        注释实现 *.action 映射

    四、配置部分

      1、db.properties

        里面设置MySql或者其他数据库的连接属性,以及连接池的参数设置

      2、applicationContext.xml

        a. 引入db.properties数据库配置文件

        b. 建立连接池

          将数据库配置的配置设置成参数传入

        c. 建立sqlSessionFactory

          将 mybatis.xml + 连接池 + *Mapper.xml所在文件夹位置   三个属性传入

        d. 建立事务管理器

          将连接池传入

        e. 配置事务管理器(声明事务切入的包和类)

          注解实现 or 配置实现

        f. controller层的bean的注册

          注册各个DaoImp

          注册各个ServiceImp(将对应Dao 以property注入)

      3、spring-mvc.xml

        1、配置Action层

          注解实现 or 配置实现(记得将Service注入)

        2、映射器配置

        3、适配器配置

        4、视图解析器配置

      4、 web.xml

        1、设置listener

        2、设置applicationContext.xml位置

        3、配置前段控制器

          servlet(此时声明spring-mvc.xml位置)、servlet-mapping

        4、配置编码过滤器

          filter、filter-mapping

        5、设置起始页面

    五、View部分

      1、编写jsp

    下面是整个流程的细节以及注意事项,(注意事项会用蓝色底色标注)

    整个框架的功能为:两个页面分别为学生和班级的增删改查功能(在此以学生页面为例)

    零、引jar包

      

       至于每个lib下有哪些jar,网上搜一下就行了,不赘述。

       不过还是有几个需要注意的地方:

    • 如果使用Myeclipse的自动配置Spring的话(右键项目——“properties”——“project facets”——勾选Spring)
      • 这样产生的Spring Library是最小系统的lib,里面的jar不包含与Spring-MVC有关的jar
      •   所以很多还是需要自己重新引入,还不如一开始就建立自己的Spring-SpringMVC的userlib(Config Build Path里面可以设置,不再赘述)
    • Mybatis的包引入后还需要引入Mybatis-Spring-XX.jar,里面包括连两个框架集成所需的class
    • 最后一个最忽视的地方:Spring-mvc的相关包必须放在web-inf/lib包下,否则会说找不到,而我们经常是用的USER-LIB,所以最后应该配置一下:

        右键项目——properties——Deployment——Depolyment Assembly  然后选择右边的add,然后选择“Java Build Path Entries”,将所有的User-lib都添加进来。

    一、数据库部分

      先不着急建表,首先分析表间的关系,很明显为多对一,所以“多”这边的表就应该设置外键指向“一”,外键的作用(1.一致性、2完整性)不再赘述。

      例如本项目,就是应该在“多”的一方表 students 这边设置外键 cid 指向 classes表的cid。(其实students表这边的cid 应该起名为s_cid以示区分

      classes表:

    CREATE TABLE `classes` (
      `cid` int(5) NOT NULL AUTO_INCREMENT,
      `cname` varchar(10) NOT NULL,
      PRIMARY KEY (`cid`)
    ) 
    classes.sql

      students表:

    CREATE TABLE `students` (
      `sid` int(5) NOT NULL AUTO_INCREMENT,
      `sname` varchar(10) NOT NULL,
      `sage` int(5) DEFAULT NULL,
      `ssex` int(1) DEFAULT NULL,
      `cid` int(5) DEFAULT NULL,
      PRIMARY KEY (`sid`),
      KEY `cid` (`cid`),
      CONSTRAINT `students_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `classes` (`cid`)
    )
    students.sql

      我是用 SQLyog 设置然后自动生成的。

    二、Model部分

      1、根据表结构写相对应的bean(*.java)

        创建bean包,之后把所有bean都放在这

        

        根据表结构编写 *.java(项目最好不要像我起Cass这种java内已有的类名,以免引入的时候混淆)

          作为主表student的话它的属性中cid那一个应该写为Class类,以此最后查询返回的时候能直接进行映射

    package bean;
    
    public class Class {
        Integer cid;
        String cname;
        
        public Class() {
            super();
        }
    
        public Class(Integer cid, String cname) {
            super();
            this.cid = cid;
            this.cname = cname;
        }
        
        public Class(String cname) {
            super();
            this.cname = cname;
        }
        public Integer getCid() {
            return cid;
        }
        public void setCid(Integer cid) {
            this.cid = cid;
        }
        public String getCname() {
            return cname;
        }
        public void setCname(String cname) {
            this.cname = cname;
        }
    
        @Override
        public String toString() {
            return "Class [cid=" + cid + ", cname=" + cname + "]";
        }
    }
    Class.java
    package bean;
    
    public class Student {
        Integer sid;
        String sname;
        Integer ssex;
        Integer sage;
        Class cls;
        
        public Student() {
            super();
        }
        
        public Student(Integer sid, String sname, Integer ssex, Integer sage, Class cls) {
            super();
            this.sid = sid;
            this.sname = sname;
            this.ssex = ssex;
            this.sage = sage;
            this.cls = cls;
        }
        
        public Student(String sname, Integer ssex, Integer sage, Class cls) {
            super();
            this.sname = sname;
            this.ssex = ssex;
            this.sage = sage;
            this.cls = cls;
        }
    
        public Integer getSid() {
            return sid;
        }
        public void setSid(Integer sid) {
            this.sid = sid;
        }
        public String getSname() {
            return sname;
        }
        public void setSname(String sname) {
            this.sname = sname;
        }
        public Integer getSage() {
            return sage;
        }
        public void setSage(Integer sage) {
            this.sage = sage;
        }
        public Integer getSsex() {
            return ssex;
        }
        public void setSsex(Integer ssex) {
            this.ssex = ssex;
        }
        public Class getCls() {
            return cls;
        }
        public void setCls(Class cls) {
            this.cls = cls;
        }
    
        @Override
        public String toString() {
            return "Student [sid=" + sid + ", sname=" + sname + ", sage=" + sage + ", ssex=" + ssex + ", cls=" + cls + "]";
        }
    }
    Student.java

        其间的各种构造器必须要无参构造器——Mybatis返回结果的时候默认调用,其他的构造器可以根据自己需要来)以及setter和getter方法也一定要设置。

      2、配置mybatis.xml

        主要写typeAlias(别名)

    mybatis.xml
    •     此处需要注意头文件说明中: "http://mybatis.org/dtd/mybatis-3-config.dtd" 设置 XMLcatalog
      •   点击IDE里的“windows”——“preference”——“Files 安定Editors”——“XML”——“XML Files”——“XML”——“XML catalog”
      •   点击右边的add
      •   location选择项目中“mybatis-3-config.dtd”的位置(没有则下载复制过来,一般直接放在src目录下)
      •   key type选择 url;key 直接复制头文件中的 ***.dtd 即可

      3、编写 *Mapper.xml 放在beanMapper包下

    ClassMapper.xml
    StudentMapper.xml

      此处有一些需要注意的地方:

    •   头文件的 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"也需要引入XML catalog
    •   <resultMap>标签中的属性与列匹配是有一定顺序的: 顺序为(constructor?, id*, result*, association*, collection*, discriminator?),不按顺序来回报错。
    •   主键一定要以 id 的子标签进行匹配,否则在进行其他表的连接的时候可能会报空指针错误
    •   动态sql进行foreach的时候,如果传入的属性只有一个List或者Array,则collection=“list”或则collection=“array”,此时不再需要写“parameterType”属性,但是注意写item,以及${item}
    •   <where>标签中的<if>标签内后面的 “,” 可写可不写。但是前面“and”必须写
    •   如果xml内需要写逻辑语句例如 “&”“>”"<"等 ,此时不能直接写(包括sql语句内),因为会与标签符“<>”混淆,所以应该采用xml内的转义字符(实体引用):
      • 例如StudnetMapper.xml中的 <if test="sname!=null &amp; sname != ''"> 

    三、Controller部分

      1、根据  *Map.xml 编写 *Dao.java (接口)与 *DaoImp.java(实现类)

        (上面的名字是建议,下面的名字是我当时临时写的,可能不一致)

    package daoIntf;
    
    import java.util.List;
    import bean.Class;
    
    public interface ClassDaoIntf {
        public void addClass(Class cls) throws Exception;
        
        public void deleteClass(Class cls) throws Exception;
        
        public void updateClass(Class cls) throws Exception;
        
        public List<Class> findClass(Class cls) throws Exception;
    
        public void addClass(String string)  throws Exception;
        
        public List<Class> findClass(String string)  throws Exception;
    }
    ClassDaoInf.java(接口)
    package daoIntf;
    
    import java.util.List;
    import bean.Student;
    
    public interface StudentDaoIntf {
        public void addStudent(Student stu) throws Exception;
        
        public void deleteStudent(List<Integer> sids) throws Exception;
        
        public void updateStudent(Student stu) throws Exception;
        
        public List<Student> findStudent(Student stu) throws Exception;
    }
    StudentDaoInf.java(接口)
    package dao;
    
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import bean.Class;
    import daoIntf.ClassDaoIntf;
    
    
    public class ClassDao implements ClassDaoIntf {
        
        private SqlSessionFactory sqlSessionFactory;
        
        public ClassDao() {
        }
        
    //    public ClassDao(SqlSessionFactory sqlSessionFactory) {
    //        super();
    //        this.sqlSessionFactory = sqlSessionFactory;
    //    }
        
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            this.sqlSessionFactory = sqlSessionFactory;
        }
    
        
        @Override
        public void addClass(Class cls) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.insert("ClassNameSpace.add", cls);
            System.out.println("插入班级"+cls+"成功");
            sqlSession.commit();
            sqlSession.close();
        }
        
        public void addClass(String cname) throws Exception {
            addClass(new Class(cname));
        }
    
        @Override
        public void deleteClass(Class cls) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.delete("ClassNameSpace.delete", cls);
            System.out.println("删除班级"+cls+"成功");
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Override
        public void updateClass(Class cls) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("ClassNameSpace.update", cls);
            System.out.println("更新班级"+cls+"成功");
            sqlSession.commit();
            sqlSession.close();
        }
    
        @Override
        public List<Class> findClass(Class cls) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<Class> result =  sqlSession.selectList("ClassNameSpace.find", cls);
            System.out.println("查询班级"+result+"成功");
            sqlSession.close();
            return result;
        }
        
        public List<Class> findClass(String cname) throws Exception {
            return findClass(new Class(cname));
        }
        
        public List<Class> findClass() throws Exception {
            return findClass(new Class());
        }
    }
    ClassDao.java(实现类)
    package dao;
    
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    
    import bean.Student;
    import daoIntf.StudentDaoIntf;
    
    
    
    public class StudentDao implements StudentDaoIntf {
        
        private SqlSessionFactory sqlSessionFactory;
        
        public StudentDao() {
        }
        
    //    public StudentDao(SqlSessionFactory sqlSessionFactory) {
    //        super();
    //        this.sqlSessionFactory = sqlSessionFactory;
    //    }
        
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            this.sqlSessionFactory = sqlSessionFactory;
        }
    
        
        @Override
        public void addStudent(Student stu) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.insert("StudentNameSpace.add", stu);
            System.out.println("插入学生"+stu+"成功");
            sqlSession.close();
        }
    
        @Override
        public void deleteStudent(List<Integer> sids) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            System.out.println(sids);
            sqlSession.delete("StudentNameSpace.delete", sids);
            System.out.println("删除学生"+sids+"成功");
            sqlSession.close();
        }
    
        @Override
        public void updateStudent(Student stu) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("StudentNameSpace.update", stu);
            System.out.println("更新学生"+stu+"成功");
            sqlSession.close();
        }
    
        @Override
        public List<Student> findStudent(Student stu) throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List<Student> result =  sqlSession.selectList("StudentNameSpace.find", stu);
            System.out.println("查询学生"+result+"成功");
            sqlSession.close();
            return result;
        }
    }
    StudentDao.java(实现类)

      建议使用set方法属性注入,因为如果使用构造器的注入的话Junit进行测试会报错“只能拥有一个构造器”。

      2、根据 *Dao.java 编写 *Service.java 与 *ServiceImp.java(属性:*Dao)

      所有涉及业务操作都应该在此完成(业务操作就是与传过来的数据之间计算有关的操作,例如:分页计算、股票预测),不过本案例主要是增删改查,所以不涉及业务操作,直接调用Dao即可。

    package serviceIntf;
    
    import java.util.List;
    
    import bean.Class;
    
    public interface ClassServiceInf {
        public void addClass(Class cls) throws Exception;
        
        public void deleteClass(Class cls) throws Exception;
        
        public void updateClass(Class cls) throws Exception;
        
        public List<Class> findClass(Class cls) throws Exception;
    }
    ClassServiceInf.java(接口)
    package serviceIntf;
    
    import java.util.List;
    
    import bean.Class;
    
    public interface ClassServiceInf {
        public void addClass(Class cls) throws Exception;
        
        public void deleteClass(Class cls) throws Exception;
        
        public void updateClass(Class cls) throws Exception;
        
        public List<Class> findClass(Class cls) throws Exception;
    }
    StudentServiceInf.java(接口)
    package service;
    
    import java.util.List;
    
    import bean.Class;
    import dao.ClassDao;
    import daoIntf.ClassDaoIntf;
    import serviceIntf.ClassServiceInf;
    
    public class ClassService implements ClassServiceInf {
    
        private ClassDaoIntf classDao;
        
        public void setClassDao(ClassDaoIntf classDao) {
            this.classDao = classDao;
        }
        
        @Override
        public void addClass(Class cls) throws Exception {
            classDao.addClass(cls);
        }
    
        @Override
        public void deleteClass(Class cls) throws Exception{
            classDao.deleteClass(cls);
        }
    
        @Override
        public void updateClass(Class cls) throws Exception {
            classDao.updateClass(cls);
        }
    
        @Override
        public List<Class> findClass(Class cls) throws Exception {
            return classDao.findClass(cls);
        }
        
    }
    ClassService.java(实现类)
    package service;
    
    import java.util.List;
    
    import bean.Class;
    import bean.Student;
    import dao.ClassDao;
    import daoIntf.ClassDaoIntf;
    import daoIntf.StudentDaoIntf;
    import serviceIntf.ClassServiceInf;
    import serviceIntf.StudentServiceInf;
    
    public class StudentService implements StudentServiceInf {
    
        private StudentDaoIntf studentDao;
    
        public void setStudentDao(StudentDaoIntf studentDao) {
            this.studentDao = studentDao;
        }
        
        @Override
        public void addStudent(Student stu) throws Exception {
            studentDao.addStudent(stu);
        }
    
        @Override
        public void deleteStudent(List<Integer> sids) throws Exception {
            studentDao.deleteStudent(sids);
        }
    
        @Override
        public void updateStudent(Student stu) throws Exception {
            studentDao.updateStudent(stu);
        }
    
        @Override
        public List<Student> findStudent(Student stu) throws Exception {
            return studentDao.findStudent(stu);
        }
    }
    StudentService.java(实现类)

      3、根据  *Service.java 编写 *Controller.java (属性:*Service)

        Action层主要就是在此处实现对表单传过来的数据进行校验(也可由js完成)、加工、封装、以及返回(重定向or转发),并不涉及业务操作

        注释实现 *.action 映射比较方便,也可以选择xml配置实现

        @requestMapping中还有个method属性可以指定接受的访问类型eg.:GET:  method=RequestMethod.GET )

    package action;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import bean.Class;
    import service.ClassService;
    import serviceIntf.ClassServiceInf;
    
    @Controller
    @RequestMapping(value="/class")
    public class ClassAction {
        private ClassServiceInf classService;
        @Resource(name="classService")
        public void setClassService(ClassServiceInf classService) {
            this.classService = classService;
        }
        
        @RequestMapping(value="/add")
        public ModelAndView addClass(Class cls) throws Exception {
            ModelAndView mv = new ModelAndView();
            //调用业务层方法
            classService.addClass(cls);
            mv.addObject("action", "addClass");
            mv.setViewName("success");
            return mv;
        }
        
        @RequestMapping(value="/find")
        public ModelAndView findClass(Class cls) throws Exception {
            ModelAndView mv = new ModelAndView();
            //调用业务层方法
            List<Class> classList = classService.findClass(cls);
            
            if (classList.isEmpty()) {
                mv.addObject("isNull", true);
            }
            mv.addObject("cid", cls.getCid());
            mv.addObject("cname", cls.getCname());
            mv.addObject("classList", classList);
            mv.setViewName("class");
            return mv;
        }
    }
    ClassAction.java
    package action;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import bean.Class;
    import bean.Student;
    import service.StudentService;
    import serviceIntf.ClassServiceInf;
    import serviceIntf.StudentServiceInf;
    
    @Controller
    @RequestMapping(value="/student")
    public class StudentAction {
        
        @Resource(name="studentService")
        private StudentServiceInf studentService;
        
        @Resource(name="classService")
        private ClassServiceInf classService;
        
        public void setStudentService(StudentServiceInf studentService) {
            this.studentService = studentService;
        }
        
        @RequestMapping(value="/start")
        public ModelAndView startStudent() throws Exception {
            ModelAndView mv = new ModelAndView();
            //调用业务层方法
            Class cls = new Class();
            List<Class> classList = classService.findClass(cls);
            if (classList.isEmpty()) {
                mv.addObject("clsIsNull", true);
            }
            mv.addObject("classList", classList);
            mv.setViewName("student");
            return mv;
        }
        
        @RequestMapping(value="/add")
        public ModelAndView addStudent(Student stu, Integer cid) throws Exception {
            stu.setCls(new Class(cid, ""));
            ModelAndView mv = new ModelAndView();
            //调用业务层方法
            studentService.addStudent(stu);
            mv.addObject("action", "addStudent");
            mv.setViewName("success");
            return mv;
        }
        
        @RequestMapping(value="/delete")
        public ModelAndView deleteStudent(Integer[] sids) throws Exception {
            System.out.println(Arrays.asList(sids));
            ModelAndView mv = new ModelAndView();
            //调用业务层方法
            studentService.deleteStudent(new ArrayList<Integer>(Arrays.asList(sids)));
            mv.addObject("action", "deleteStudent");
            mv.setViewName("success");
            return mv;
        }
        
        @RequestMapping(value="/find")
        public ModelAndView findStudent(Student stu, Integer cid) throws Exception {
            ModelAndView mv = new ModelAndView();
            
            //调用业务层方法
            stu.setCls(new Class(cid, ""));
            List<Student> studentList = studentService.findStudent(stu);
            
            if (studentList.isEmpty()) {
                mv.addObject("stuIsNull", true);
            }
            
            mv.addObject("student", stu);
            mv.addObject("studentList", studentList);
            mv.setViewName("forward:/student/start.action");
            return mv;
        }
    }
    StudentAction.java
    •   在此处写了一个“/studdent/start.action”的起始action 目的是为了向 “所属班级” 的下拉选项动态传入数据库的值
    •   注意,如果需要接受表单传来的多个同类对象(例如:多个需要删除的id)应该使用数组进行接收(Integer[] sids),形参数组名必须与jsp中的name属性保持一致

    四、配置部分

      1、db.properties

        里面设置MySql或者其他数据库的连接属性,以及连接池的参数设置

    mysql.driver=com.mysql.jdbc.Driver
    mysql.url=jdbc:mysql://localhost:3306/ssm
    mysql.user=root
    mysql.password=tiger
    
    initialSize=0
    maxActive=20  
    maxIdle=20  
    minIdle=1  
    maxWait=60000
    jdbc.properties

      2、applicationContext.xml

        a. 引入db.properties数据库配置文件

        b. 建立连接池

          将数据库配置的配置设置成参数传入

        c. 建立sqlSessionFactory

          将 mybatis.xml + 连接池 + *Map.xml所在文件夹位置   三个属性传入

        d. 建立事务管理器

          将连接池传入

        e. 配置事务管理器(声明事务切入的包和类)

          注解实现 or 配置实现

        f. controller层的bean的注册

          注册各个DaoImp

          注册各个ServiceImp(将对应Dao 以property注入)

    <?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:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd
            
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
            
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
            
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    
            <!-- 引入jdbc文件 -->
            <context:property-placeholder location="classpath:config/jdbc.properties"/>
            
            <!-- 通过上面的文件,配置连接池 -->
            <bean id="dataSourceID" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="${mysql.driver}"></property>
                <property name="jdbcUrl" value="${mysql.url}"></property>
                <property name="user" value="${mysql.user}"></property>
                <property name="password" value="${mysql.password}"></property>
            </bean>
            
            <!-- 加载mybatis文件 -->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="dataSource" ref="dataSourceID"></property>
                
                <property name="configLocation" value="classpath:config/mybatis.xml"></property>
                
                <property name="mapperLocations" value="classpath:beanMapper/*Mapper.xml"></property>
            </bean>
            
            <!-- 配置事务管理器 -->
            <bean id="transactionManager"
                class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
                <property name="dataSource" ref="dataSourceID"></property>
            </bean>
            
            <!-- 注释实现事务 -->
            <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
            
            <!-- 配置实现事务——指定方法 -->
            <tx:advice id="txAdvice" transaction-manager="transactionManager">
                <tx:attributes>
                    <tx:method name="add*" propagation="REQUIRED"/>
                    <tx:method name="delete*" propagation="REQUIRED"/>
                    <tx:method name="update*" propagation="REQUIRED"/>
                    <tx:method name="find*" propagation="SUPPORTS"/>
                </tx:attributes>
            </tx:advice>
            
            <!-- 配置实现事务————指定事务切入的包和类 -->
            <aop:config>
                <aop:pointcut expression="execution(* dao.*.*(..))" id="pointcut"/>    
                <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
            </aop:config>
            
            <!-- 实例化Dao -->
            <bean id="classDao" class="dao.ClassDao">
                <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
            </bean>
            <bean id="studentDao" class="dao.StudentDao">
                <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
            </bean>
            
            
            <!-- 实例化Service -->
            <bean id="classService" class="service.ClassService">
                <property name="classDao" ref="classDao"></property>
            </bean>
            <bean id="studentService" class="service.StudentService">
                <property name="studentDao" ref="studentDao"></property>
            </bean>
    </beans>
    applicationContext.xml

      3、spring-mvc.xml

        1、配置Action层

          注解实现(扫描action包) or 配置实现(记得将Service注入)

          必须把Action层的声明和扫描放在spring-mvc.xml里面(因为是前端控制器完成action 的 mapping),否则报错

        2、映射器配置

        3、适配器配置

        4、视图解析器配置

    <?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:mvc="http://www.springframework.org/schema/mvc" 
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd
            
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    
            
            <!-- 实例化Action:因为是用注解实现的actionMapper所以用扫描的方式 -->
            <context:component-scan base-package="action"></context:component-scan>    
            
            <!-- 配置映射器(注解实现所以略) -->
            
            <!-- 配置适配器(略) -->
            
            <!-- 配置视图解析器 -->
            <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/jsp/"></property>
                <property name="suffix" value=".jsp"></property>
            </bean>
    
    </beans>
    spring-mvc.xml

      4、 web.xml

        1、设置listener

        2、设置applicationContext.xml位置

          不要和spring-mvc.xml弄混了

        3、配置前段控制器

          servlet(此时用<init-para>声明spring-mvc.xml位置)、servlet-mapping

        4、配置编码过滤器

          filter、filter-mapping

        5、设置起始页面

    <?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" 
            version="3.1">
            
      <display-name>SSM-test</display-name>
      
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      
      
      <!-- 前段控制器(Spring核心控制器) -->
      <servlet>
          <servlet-name>springmvc</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:config/springmvc.xml</param-value>
          </init-param>
      </servlet>
      <servlet-mapping>
          <servlet-name>springmvc</servlet-name>
          <url-pattern>*.action</url-pattern>
      </servlet-mapping>
      
      
        <!-- 编码过滤器 -->
        <filter>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        
        <!-- 起始界面 -->
        <welcome-file-list>
            <welcome-file>jsp/MyJsp.jsp</welcome-file>
        </welcome-file-list>
    </web-app>
    web.xml

    五、View部分

      1、编写jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'MyJsp.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
              <a href="${pageContext.request.contextPath}/jsp/class.jsp">班级页面</a>
              <a href="${pageContext.request.contextPath}/student/start.action">学生页面</a>
      </body>
    </html>
    MyJsp.jsp(起始页)
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'MyJsp.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
            <form action="${pageContext.request.contextPath}/class/add.action" method="post">
                <table align="center" border="2">
                    <caption>添加班级</caption>
                    <tr>
                        <th>班级名</th>
                        <td><input type="text" name="cname"></td>
                    </tr>
                    <tr align="center">
                        <td colspan="2">
                            <input type="submit" value="添加">
                        </td>
                    </tr>
                </table>
            </form>  
      
              <form action="${pageContext.request.contextPath}/class/find.action" method="get">
                  <table border="2" align="center">
                  <caption> 搜索班级  </caption>
                      <tr>
                        <th>班级id</th>
                        <td><input type="text" name="cid" value="${cid}"></td>
                    </tr>
                    <tr>
                        <th>班级名</th>
                        <td><input type="text" name="cname" value="${cname}"></td>
                    </tr>
                  <tr align="center">
                      <td colspan="2"><input type="submit"></td>
                  </tr>
                  <tr>
                      <th>班级号</th>
                      <th>班级名</th>
                  </tr>
                  <tr>
                      <td colspan="2" align="center">
                          <c:if test="${isNull}"> 无相关记录 </c:if>
                      </td>
                  </tr>
                  <c:forEach items="${classList}" var="cls">
                      <tr>
                          <td>${cls.cid}</td>
                          <td>${cls.cname}</td>
                      </tr>
                  </c:forEach>
              </table>
              </form>
      </body>
    </html>
    class.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'MyJsp.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
            <form action="${pageContext.request.contextPath}/student/add.action" method="post">
                <table align="center" border="2">
                    <caption>添加学生</caption>
                    <tr>
                        <th>学生号</th>
                        <td><input type="text" name="sid"></td>
                    </tr>
                    <tr>
                        <th>学生名</th>
                        <td><input type="text" name="sname"></td>
                    </tr>
                    <tr>
                        <th>性别</th>
                        <td>
                            <select name="ssex">
                                <option value="1" selected="selected"></option>    
                                <option value="0"></option>    
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th>学生年龄</th>
                        <td><input type="text" name="sage"></td>
                    </tr>
                    <tr>
                        <th>所属班级</th>
                        <td>
                            <select name="cid">
                                <c:forEach items="${classList}" var="cls">
                                    <option value="${cls.cid}">${cls.cname}</option>
                                </c:forEach>
                            </select>
                        </td>
                    </tr>
                    <tr align="center">
                        <td colspan="2">
                            <input type="submit" value="添加">
                        </td>
                    </tr>
                </table>
            </form>  
      
              <form action="${pageContext.request.contextPath}/student/find.action" method="get">
                  <table border="2" align="center">
                  <caption> 搜索学生  </caption>
                      <tr>
                        <th>学生号</th>
                        <td><input type="text" name="sid" value="${student.sid}"></td>
                    </tr>
                    <tr>
                        <th>学生名</th>
                        <td><input type="text" name="sname" value="${student.sname}"></td>
                    </tr>
                    <tr>
                        <th>性别</th>
                        <td>
                            <select name="ssex">
                                
                                <option value="1" ${(student.ssex == 1)?'selected="selected"':''}></option>    
                                <option value="0" ${(student.ssex == 0)?'selected="selected"':''}></option>
                                <option value="-1" ${(student.ssex == -1 || student == null )?'selected="selected"':''}>
                                    请选择
                                </option>    
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th>学生年龄</th>
                        <td><input type="text" name="sage">${student.sage}</td>
                    </tr>
                    <tr>
                        <th>所属班级</th>
                        <td>
                            <select name="cid">
                                <c:forEach items="${classList}" var="cls">
                                    <option value="${cls.cid}"  ${(student.cls.cid == cls.cid )?'selected="selected"':''}>${cls.cname}</option>
                                </c:forEach>
                                <option value="-1" ${(student.cls.cid == -1 || student == null )?'selected="selected"':''}>
                                    请选择
                                </option>
                                <c:if test="${clsIsNull}">
                                    <option value="-1">
                                        无班级可选
                                    </option>
                                </c:if>
                            </select>
                        </td>
                    </tr>
                  <tr align="center">
                      <td colspan="2"><input type="submit"></td>
                  </tr>
              </table>
            </form>
    
            <form action="${pageContext.request.contextPath}/student/delete.action" method="get">
              <table border="2" align="center">
                  <caption>学生信息表</caption>
                  <tr>
                      <th>学号</th>
                      <th>姓名</th>
                      <th>性别</th>
                      <th>年龄</th>
                      <th>班级</th>
                  </tr>
                  <c:if test="${stuIsNull}">
                      <tr>
                          <td colspan="5" align="center">
                              无相关记录
                          </td>
                      </tr>
                  </c:if>
                  <c:forEach items="${studentList}" var="stu">
                      <tr>
                          <td><input type="checkbox" value="${stu.sid}" name="sids">${stu.sid}</td>
                          <td>${stu.sname}</td>
                          <td>
                              <c:if test="${stu.ssex==0}"></c:if>
                              <c:if test="${stu.ssex==1}"></c:if>
                          </td>
                          <td>${stu.sage}</td>
                          <td>${stu.cls.cname}</td>
                      </tr>
                  </c:forEach>
                  <c:if test="${!stuIsNull}">
                      <tr>
                          <td colspan="5" align="center">
                              <input type="submit" value="删除">
                          </td>
                      </tr>
                  </c:if>
              </table>
              </form>
      </body>
    </html>
    student.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'success.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
              ${action}成功
      </body>
    </html>
    success.jsp

      几个注意事项:(作为一个做后端的强迫症患者,每次写jsp都是莫大煎熬————希望好看,但是不会写。。。)

    •   表单验证一般用js来做,注意在jsp中将js引入

    •   下拉框的赋值同步(提交表单返回值后,传过去的值仍然是选中的)可以使用取值符的三目运算符来实现,例如:
    <c:forEach items="${classList}" var="cls">
        <option value="${cls.cid}"  ${(student.cls.cid == cls.cid )?'selected="selected"':''}>${cls.cname}</option>
    </c:forEach>

        这段代码解决了“动态下拉框”,以及下拉框的赋值同步(单引号‘’在 <>中可以忽略)

    • ${pageContext.request.contextPath} 与 <%=basePath%> 与 <%=path%>的区别
      •   首先看jsp内的java代码
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    显然 path

        只是显示项目的名称例如(SSM-test)

      basePath

         会显示 访问协议://服务器名:端口号/项目名                例如(http://127.0.0.1:8080/SSM-test/

        并且,在jsp眼里,这只是一个字符串,不能跟表单数据,就算往后加上表单的数据(http://127.0.0.1:8080/SSM-test/add.action?sname='qqq'&sid=111)

        进行访问最后也只是访问(http://127.0.0.1:8080/SSM-test/add.action)

      ${pageContext.request.contextPath} 

      也是完整的域名路径,不过有两点不同:1、最后没有“/”,而basePath有  2、在form的action中可以跟表单数据

    最后附上项目的文件放置:

    以及SSM框架的流程图:

      

    导图连接:https://www.processon.com/view/57eefd3ee4b0300f4fd1c3b9

    其中Controller就是本文中的Action层啦。

    SSM的流程其实主要就是Spring-mvc的流程: 

    图出处:https://blog.csdn.net/zuoluoboy/article/details/19766131

  • 相关阅读:
    [UVA1149]Dominating Patterns
    [HDOJ1358]Period
    [HDOJ3065]病毒侵袭持续中
    【RQNOJ356】myt的格斗
    【rqnoj39】 饮食问题
    【rqnoj28】[Stupid]愚蠢的宠物
    【rqnoj378】 约会计划
    layer弹框在实际项目中的一些应用
    layer弹框在实际项目中的一些应用
    移动开发之css3实现背景几种渐变效果
  • 原文地址:https://www.cnblogs.com/Xieyang-blog/p/9168158.html
Copyright © 2011-2022 走看看