ssm整合

来源:互联网 发布:推女郎吧最新域名 编辑:程序博客网 时间:2024/05/01 10:48

 

ssm整合

10.4.1创建项目

新建项目后规划好各层的包。

10.4.2导入包

 

10.4.3整合spring与mybatis

调整spring与mybatis配置文件

10.4.4创建、编写配置文件:

 

 

myBatis-config.xml文件

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<!-- 通过别名简化对类的使用

<typeAliases>

      <typeAliastype="cn.itcast.entity.Dept" alias="Dept" />

</typeAliases>

 

   <mappers>

      <mapperresource="cn/itcast/entity/DeptMapper.xml" />

   </mappers>

      -->

</configuration>

 

applicationContext.xml

 

<?xmlversion="1.0"encoding="UTF-8"?>

<beans

   xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:tx="http://www.springframework.org/schema/tx"

   xmlns:aop="http://www.springframework.org/schema/aop"

   xmlns:context="http://www.springframework.org/schema/context"

   xmlns:p="http://www.springframework.org/schema/p"

   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/tx

   http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

   http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

 

  

   <!-- 配置数据源,记得去掉myBatis-config.xml的数据源相关配置 -->

   <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource">        

      <propertyname="driverClass"value="com.mysql.jdbc.Driver"/>

      <propertyname="jdbcUrl"value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>

      <propertyname="user"value="root"/>

      <propertyname="password"value="root"/>     

   </bean>

   <!-- 配置session工厂 -->

   <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">

      <propertyname="dataSource"ref="dataSource"/>

      <propertyname="configLocation"value="classpath:myBatis-config.xml"/>

   </bean>

  

   <!-- 配置事务管理器,管理数据源事务处理-->

   <beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

      <propertyname="dataSource"ref="dataSource"/>

   </bean>

   <!-- 配置事务通知 -->

   <tx:adviceid="advice" transaction-manager="transactionManager">

      <tx:attributes>

<!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 -->

         <tx:methodname="insert*" propagation="REQUIRED" rollback-for="Exception"/>

         <tx:methodname="update*" propagation="REQUIRED" rollback-for="Exception"/>

         <tx:methodname="delete*" propagation="REQUIRED" rollback-for="Exception"/>

         <tx:methodname="*"propagation="SUPPORTS"/>

      </tx:attributes>

   </tx:advice>

   <!-- 配置切面织入的范围,后边要把事务边界定在service -->

   <aop:config>

      <aop:advisoradvice-ref="advice"pointcut="execution(* cn.itcast.scm.dao.impl.*.*(..))"/>

   </aop:config>

   <!-- 配置SessionTemplate,已封装了繁琐的数据操作-->

   <beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">

      <constructor-argname="sqlSessionFactory"ref="sqlSessionFactory"/>    

   </bean>

  

   <context:component-scanbase-package="*"/>

     

</beans>

 

10.4.5编写实体及sql映射文件

l  如没有建库表,先建库表,可参考如下sql:

drop databaseifexists mybatis;

create databasemybatisCHARACTERSET UTF8;

use mybatis;

 

create table dept(

   dept_id int primary key auto_increment,

   dept_name varchar(50),

   dept_address varchar(50)

);

 

 

insert into dept(dept_name,dept_address)values('1','1');

insert into dept(dept_name,dept_address)values('2','2');

insert into dept(dept_name,dept_address)values('3','3');

select * from dept;

l  编写实体类

 

public class Dept implementsSerializable {

   private IntegerdeptId;

   private StringdeptName;

   private StringdeptAddress;

   public Integer getDeptId() {

      return deptId;

   }

   public void setDeptId(IntegerdeptId) {

      this.deptId = deptId;

   }

   public String getDeptName() {

      return deptName;

   }

   public void setDeptName(String deptName) {

      this.deptName = deptName;

   }

   public String getDeptAddress() {

      return deptAddress;

   }

   public void setDeptAddress(String deptAddress) {

      this.deptAddress = deptAddress;

   }

   @Override

   public String toString() {

      return "Dept [deptId=" + deptId + ",deptName=" + deptName

            +",deptAddress=" +deptAddress +"]";

   }

  

}

 

 

l  sql映射文件,并将相关信息映射到mybatis-config.xml文件。

 

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEmapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

<mappernamespace="cn.itcast.entity.DeptMapper">

   <resultMaptype="Dept"id="deptResultMap">

      <idproperty="deptId"column="dept_id"/>

      <resultproperty="deptName"column="dept_name"/>

      <resultproperty="deptAddress"column="dept_address"/>

   </resultMap>

   <!-- id和命名空间用来定位SQL语句,parameterType表示参数的类型,resultMap返回类型 -->

   <selectid="selectDept"parameterType="Integer"resultMap="deptResultMap">

      <!--参数的写法#{deptID} -->

      select* from dept where dept_id=#{deptID}

   </select>

 

   <insertid="insertDept"parameterType="Dept">

      insertinto dept(dept_name,dept_address) values(#{deptName},#{deptAddress});

   </insert>

 

</mapper>

 

myBatis-config.xml文件修改后为如下内容

 

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<!-- 通过别名简化对类的使用 -->

<typeAliases>

      <typeAliastype="cn.itcast.entity.Dept" alias="Dept"/>

</typeAliases>

   <mappers>

      <mapperresource="cn/itcast/entity/DeptMapper.xml" />

   </mappers>     

</configuration>

 

 

10.4.6编写Dao接口及实现

DeptDaoImpl.java

 

@Repository("deptDao")

public class DeptDaoImpl{

  

   @Resource

   private SqlSessionTemplatesqlSessionTemplate;

  

   /**

    * 根据部门编号查询部门信息

    * @param deptId部门编号

    * @return部门信息

    */

   public Dept selectDept(Integer deptId){

      Deptdept=   sqlSessionTemplate.selectOne("cn.itcast.entity.DeptMapper.selectDept", deptId);       

      return dept;

   }

   /**

    * 添加部门信息

    * @param dept部门信息

    * @return添加成功的记录数

    */

   public int insertDept(Dept dept){

         System.out.println("------dao.dept:"+dept);

         returnsqlSessionTemplate.insert("cn.itcast.entity.DeptMapper.insertDept", dept);      

   }

}

 

10.4.7测试spring与mybatis整合

 

public class TestDeptDao {

 

   //@Resource //这里没法使用,后继版本有其它方式可以注入

   static private DeptDaoImpl deptDao;

   @BeforeClass

   public static void setUpBeforeClass()throws Exception {

      ApplicationContextcontext =new ClassPathXmlApplicationContext("applicationContext.xml");

      deptDao=(DeptDaoImpl) context.getBean("deptDao");

   }

 

   @AfterClass

   public static void tearDownAfterClass()throws Exception {

   }

 

   @Test

   public void testSelectDept() {

      System.out.println(deptDao.selectDept(1));

   }

 

   @Test

   public void testInsertDept() {

      Deptdept=new Dept();

      //dept.setDeptId(117);

      dept.setDeptName("name117");

      dept.setDeptAddress("address117");

      System.out.println("受影响行数:"+deptDao.insertDept(dept));

   }

}

 

10.4.8整合springmvc

修改web.xml文件,加入springmvc相关信息,编写 控制器类及相关jsp 文件

l  spring-mvc.xml

 

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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:p="http://www.springframework.org/schema/p"

   xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd

   http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsd

   http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd

   ">

        

   <mvc:annotation-driven></mvc:annotation-driven>

   <context:component-scanbase-package="*"/>

</beans>

 

l  web.xml文件配置

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="3.0"

   xmlns="http://java.sun.com/xml/ns/javaee"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name></display-name>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

 

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

  <servlet>

      <servlet-name>mvc</servlet-name>

      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

      <init-param>

         <param-name>contextConfigLocation</param-name>

         <param-value>classpath:spring-mvc.xml</param-value>

      </init-param>

      <load-on-startup>1</load-on-startup>

   </servlet>

   <servlet-mapping>

      <servlet-name>mvc</servlet-name>

      <url-pattern>*.action</url-pattern>

   </servlet-mapping>

   <filter>

      <filter-name>encodingFilter</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>encodingFilter</filter-name>

      <url-pattern>/*</url-pattern>

   </filter-mapping>

  

</web-app>

 

l  编写控制器类

@Controller

@RequestMapping(value="/dept")

public class DeptAction {

   @Resource

   private DeptDaoImpldeptDao;

  

   @RequestMapping(value="/insert")

   public String insert(Dept dept){

      System.out.println("---action.dept:"+dept);

      deptDao.insertDept(dept);

      return "forward:/jsp/main.jsp";

   }

}

 

l  缩写跳转页面

/jsp/main.jsp

 

<%@ page language="java"import="java.util.*"pageEncoding="utf-8"%>

<html>

<head>

</head>

<body>

 thisis main jsp

</body>

</html>

 

10.4.9测试ssi整合

 

缩写测试页面

index.jsp

 

<%@ page language="java"import="java.util.*"pageEncoding="utf-8"%>

<html>

<head>

</head>

<body>

   <formaction="dept/insert.action"method="post">

      名称:<inputtype="text" name="deptName"><br>

      地址:<inputtype="text"name="deptAddress"><br>

      <inputtype="submit"value="ok">

   </form>

</body>

</html>

 

10.3优化

10.3.1中文乱码

中文乱码处理,在web.xml中配置拦截器(参考前面)

 

<filter>

      <filter-name>encodingFilter</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>encodingFilter</filter-name>

      <url-pattern>/*</url-pattern>

   </filter-mapping>

 

10.3.2添加业务层

1).添加业务层相关包、接口及实现

接口包:cn.itcast.service

实现类包:cn.itcast.service.impl

编写接口与实现类(实现类用@Service进行注解,dao接口结合下边的配置,通过@Autowired方式注入代理实例),略。

 

 

10.3.3添加dao层接口

10.3.4修改applicationContext.xml与spring-mvc.xml文件

添加如下内容:

 

<!-- 把事务边界定在service -->

   <aop:config>

      <aop:advisoradvice-ref="advice"pointcut="execution(* cn.itcast.scm.service.impl.*.*(..))"/>

   </aop:config>

<!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。  -->

      <context:component-scanbase-package="cn.itcast">

      <context:exclude-filtertype="annotation"        expression="org.springframework.stereotype.Controller"/>

   </context:component-scan>  

  

      <!-- 配置转换器,对于在basePackage设置的包(包括子包)下的接口类,如果在Mapper.xml文件中定义过,

   将被转换成springBEAN,在调用的地方通过@Autowired方式将可以注入接口实例-->

  

   <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">

      <propertyname="sqlSessionFactory"ref="sqlSessionFactory"/>

      <propertyname="basePackage"value="cn.itcast.scm.dao"/>

   </bean>

 

spring-mvc.xml

 

<!-- 扫描所有的controller但是不扫描service -->

   <context:component-scanbase-package="cn.itcast">

      <context:include-filtertype="annotation"

         expression="org.springframework.stereotype.Controller"/>

      <context:exclude-filtertype="annotation"

         expression="org.springframework.stereotype.Service"/>

   </context:component-scan>

 

10.3.4修改sql映射文件中命名空间

 

10.3.5修改各层的调用

控制器类通过业务层接口调用业务层,业务层再通过dao接口(可删除dao实现类,及测试类)获取代理对象执行相关SQL,进行数据的操作

 

0 0
原创粉丝点击