1504—SpringMVC建立SSM整合

一、基本用法(IDEA)

       环境基本:idea空项目,新增modular(maven骨架webapp)。存储于项目文件夹下。文件夹结构如下

       

        1—pom依赖         

  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!--      mybatis   -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <!--      mysql      -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <!--     alibaba  德鲁依     -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>

        配置插件

<resources>
        <resource>
                 <directory>src/main/java</directory>
                 <includes>
                 <!--     包括目录下的.properties  , .xml都会扫描到     -->
                          <include>**/*.properties     </include>
                          <include>**/*.xml</include>
                 </includes>
                 <filtering>false</filtering>
        </resource>
</resources>

         2—配置文件

         spring配置文件applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--        spring的配置文件:声明service,dao,工具类,事务配置            -->
    <context:component-scan base-package="com.myST.service"     />

    <context:property-placeholder location="classpath:conf/jdbc.properties"         />
<!--       德鲁依配置        -->
    <bean id="dataSource"   class="com.alibaba.druid.pool.DruidDataSource"
                init-method="init"      destroy-method="close">
                <property name="url"        value="${jdbc.url}" />
                <property name="username"   value="${jdbc.username}"        />
                <property name="password"   value="${jdbc.password}"        />
    </bean>

    <bean id="factory"  class="org.mybatis.spring.SqlSessionFactoryBean"    >
                <property name="dataSource" ref="dataSource"      />
                <property name="configLocation" value="classpath:conf/mybatis.xml"  />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
            <property name="sqlSessionFactoryBeanName"      value="factory" />
            <property name="basePackage" value="com.myST.dao"   />
    </bean>
    <!--            事务配置            -->
</beans>

         springMVC配置文件DispatcherServlet.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

        <!--        springMVC的配置 文件 :声明controllers,视图解析器等web开发中的对象        -->
        <context:component-scan base-package="com.myST.controller"              />

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
                <property name="prefix" value="/WEB-INF/jsp/"    />
                <property name="suffix" value=".jsp"            />
        </bean>
        <!--
                 1—创建接口的7个实现类对象,处理java对象到json的转换
                 2—解决静态资源中,动态资源访问 失败的问题。
        -->
        <mvc:annotation-driven          />
</beans>

         myBatis的配置文件mybatis.xml,样例如下图

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置别名  
    typeAliases和environments是平等级别的标签  
        type是实体类的完整类名  
        alias是类的别名  
    -->
    <typeAliases>
<!--        <typeAlias type="com.soft.domain.User" alias="User"/>-->
<!--                domain包中的类名就是别名             -->
                <package name="com.myST.domain"/>
    </typeAliases>
    <!--    设置日志    -->
    <mappers>
        <!--        加载dao包中的所有mapper文件          -->
        <package name="com.myST.dao"/>
    </mappers>
</configuration>

           jdbc数据库连接信息jdbc.properties,样例如下 

<!--    schema01——数据库名称        -->
jdbc.url=jdbc:mysql://localhost:3306/schema01
jdbc.username=root
jdbc.password=super

           3—Java代码部分

           文件夹如下图

           

          domain/Java Bean实体类 

public class Student {

    private  Integer id;
    private  String  name;
    private  Integer  age;

    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 Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}';
    }
}

            dao持久层 

public interface StudentDao {
    //新增
    int insertStudent(Student  student);
    //返回列表
    List<Student> selectStudents();
}

          myBatis mapper配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.myST.dao.StudentDao">
    <!--        使用insert,update,delete,select标签sql  -->
    <!--    id值取自Dao接口中的方法名称        -->
    <insert id="insertStudent">
            insert into student(name ,age)   values(#{name },#{age})
    </insert>

    <select id="selectStudents" resultType="com.myST.domain.Student">
            select id,name,age from student order by id desc
    </select>
</mapper>

           service业务层

//业务层接口
public interface StudentService {

    int addStudent(Student student);

    List<Student>   queryStudents();

}

          service业务层接口实现类

/**
 *  @ Service注解
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao dao;

    @Override
    public int addStudent(Student student) {
        /**
         *  dao 是引用 类型。StudentDao类型的对象 是在spring的配置 文件中创建的对象
         *  引用类型自动 注入 @Autowired,@Resource
         */
        int rows=dao.insertStudent(student);
       
        return rows;
    }

    @Override
    public List<Student> queryStudents() {

        List<Student>   list=dao.selectStudents();

        return list;
    }
}

           Controller方法

@Controller
@RequestMapping("/student")
public class StudentController {

    /*
            声明引用类型,调用 引用类型的业务 方法
            @Autowired,@Resource注解用来将值传递到持久层/业务层中
     */
    @Autowired
    private StudentService    service;

    //  添加新学生     
    @RequestMapping("/addStudent.do")
    public ModelAndView   addStudent(Student student){

        ModelAndView mv=new ModelAndView();

        //调用service,处理业务逻辑,把处理结果返回给前台
        int rows  =service.addStudent(student);

        String msg="注册失败!!!!";

        if(rows>0){
            //注册成功,给用户成功的数据和视图
            msg="注册成功!";
        }
        mv.addObject("msg",student.getName()+","+msg);
        mv.setViewName("result");

        return mv;
    }

    //    浏览学生数据表     
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student>    queryStudents(){

            List<Student>   students=service.queryStudents();

            return students;
    }
}

  到此处,即完成了项目的后端设计,只剩下前端jsp/js页面未写。

二、第二用法(IDEA)

       环境基本:idea空项目,新增modular(maven骨架webapp),结果如下图

       

      1—pom依赖     

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.zteacher</groupId>
  <artifactId>ssm11</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm11 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <!--     省略引用        -->
  </dependencies>

  <build>
    <finalName>ssm11</finalName>

    <resources>
      <resource>
        <!--指定根目录 到源文件夹 一般如下-->
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>

      2—配置文件web.xml      

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">

  <!--      声明sping 监听 器  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/applicationContext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--      前端控制 器      -->
  <servlet>
          <servlet-name>dispatcherServlet</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:conf/DispatcherServlet.xml</param-value>
         </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!--      post 乱码处理     -->
  <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>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

      3—配置文件applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
			http://www.springframework.org/schema/context
			http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/aop
			http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
			http://www.springframework.org/schema/tx
			http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

    <context:property-placeholder   location="classpath:conf/db.properties"     />

    <!--                package search:  dao,service            -->
    <context:component-scan base-package="com.study.dao,com.study.service"      />


    <!--            ali德鲁依                -->
    <bean id="dataSource"   class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init"              destroy-method="close"                                >
        <property name="url"    value="${jdbc.url}"                />
        <property name="username"       value="${jdbc.username}"            />
        <property name="password"               value="${jdbc.password}"           />
    </bean>

    <!--            SessionFactory          -->
    <bean id="sessionFactory"   class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="dataSource"     ref="dataSource"    />
                <!--        整合mybatis,包扫描 mappers       -->
                <property name="configLocation"  value="classpath:conf/sqlMapConfig.xml"    ></property>
                <property name="mapperLocations"    value="classpath:com/study/mappers/*.xml"   ></property>
    </bean>

</beans>

    4—配置文件DispatcherServlet.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

    <!--    scan    controller packages        -->
    <context:component-scan base-package="com.study.controller" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix"     value="/WEB-INF/view/"   />
        <property name="suffix"         value=".jsp"            />
    </bean>

    <mvc:annotation-driven      />

    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/css/**" location="/css/"       />

</beans>

     5—配置文件sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
      <!--  <package name="cn.itcast.mybatis.po"/>
-->
    </typeAliases>

</configuration>

    6—pojo实体

@Alias("stu")
public class student    implements Serializable {

    private   int  Id;
    private   String  Name;
    private   int     Age;

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        Id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }

    @Override
    public String toString() {
        return "student{" +
                "Id=" + Id +
                ", Name='" + Name + '\'' +
                ", Age=" + Age +
                '}';
    }
}

     7—Dao相关

--基接口
public interface BaseDao<T> {

    List<T> find(Map map);
    T  get(Serializable  id);

    List<T>     list();

    int   insert(T  entity);

    int  deleteById(Serializable  id);
}

--实体Dao
public interface studentDao  extends  BaseDao<student>    {
}

 Dao实现

--基实现类
public class BaseDaoImpl<T>  extends SqlSessionDaoSupport    implements BaseDao<T> {
    @Autowired
    public  void   setSqlSessionFactory(SqlSessionFactory  sqlSessionFactory){
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    private   String ns;

    public String getNs() {
        return ns;
    }

    public void setNs(String ns) {
        this.ns = ns;
    }

    @Override
    public List<T> find(Map map) {
        List<T>  oList=this.getSqlSession().selectList(ns+".find",map)      ;

        return oList;
    }

    @Override
    public T get(Serializable id) {
        return this.getSqlSession().selectOne(ns+".get",id);
    }

    @Override
    public List<T> list() {
        List<T> oList=this.getSqlSession().selectList(ns+".list");
        return  oList;
    }

    @Override
    public int insert(T entity) {
            int  i=this.getSqlSession().insert(ns+".insert",entity);
        return i;
    }

    @Override
    public int deleteById(Serializable id) {
        int i =this.getSqlSession().delete(ns+".deleteById",id);
        return i;
    }
}

--student实现
@Repository
public class studentDaoImpl    extends  BaseDaoImpl<student>      implements studentDao {

    public  studentDaoImpl(){
        super.setNs("com.study.mappers.studentMapper");
    }
}

     8—Service相关

public interface studentService  {

    List<student>  Find(Map map);
    student  Get(Serializable id);

    List<student>     List();

    int   Insert(student  entity);

    int  DeleteById(Serializable  id);

}

--实现
@Service
public class studentServiceImpl implements studentService {
    @Autowired
    studentDao dao;


    @Override
    public List<student> Find(Map map) {
        return dao.find(map)    ;
    }

    @Override
    public student Get(Serializable id) {
        return dao.get(id);
    }

    @Override
    public List<student> List() {
        return dao.list();
    }

    @Override
    public int Insert(student entity) {
        return dao.insert(entity);
    }

    @Override
    public int DeleteById(Serializable id) {
        return dao.deleteById(id);
    }
}

      9—Mybatis映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.mappers.studentMapper">

        <insert id="insert"  parameterType="com.study.pojo.student"    >
                insert into student(name,age)
                    values(
                                #{Name,jdbcType=VARCHAR},
                                #{Age,jdbcType=INTEGER}
                    )
        </insert>

        <delete id="deleteById"     parameterType="int" >
                delete from student where id=#{id};
        </delete>

        <select id="get"        parameterType="int" resultType="com.study.pojo.student">
                select * from student where id=#{id};
        </select>

        <select id="find"   parameterType="map" resultType="com.study.pojo.student">
                select * from student  where 1=1
                        <if test="Name!=null">AND  name=#{Name}</if>
                ;
        </select>

        <select id="list"   resultType="com.study.pojo.student">
                select  * from student  ;
        </select>

</mapper>

      10—Controller内容

@Controller
@RequestMapping(value = "student")
public class studentController {

    @Resource
    studentService  studentServ;

    @RequestMapping(value = "/liststudent.do",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public List<student>        listStudents(){
        List<student>  result=null;

        try {
            result=studentServ.List();
        } catch (Exception e) {
            System.out.println("ERR-------------------------------"+e.getMessage());
        }

        return result;
    }
}

      11—测试

使用postman测试如下

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值