Maven,SSM框架搭建(连接ORACLE数据库)

最近自己在网上对着博客搭建了一次SSM框架,说难也不难,因为没遇到什么问题。最重要的是一些不容易犯错的错误如果犯了会很麻烦。不过对着错误报告查找的话,还是能查出来的。现在我把流程一步步写出来,供君参考,也加深自己的印象,但示例代码可能跟其他博客雷同(其实都是大同小异的)。请各位同仁见谅。

1.Oracle数据库的创建

我们搭建SSM首先要把数据的来源设计好,然后拿出需要的数据。我使用的数据库是本地创建的数据库(IP地址127.0.0.1)。数据表是USER_T。

CREATE TABLE USER_T(ID NUMBER(11),USER_NAME VARCHAR2(40) ,PASSWORD VARCHAR2(255),AGE NUMBER(4), constraint pk_id primary key(id));
insert into  User_t values(1,'测试','123456',24);

2.创建Maven项目

2.1 Maven 开发环境的搭建

2.1.1 下载maven安装包
http://mirror.bit.edu.cn/apache/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.zip
2.1.2 配置环境变量
新建变量名:MAVEN_HOME 变量值:C:\apache-maven-3.5.0(这是我的MAVEN路径)

编辑变量名:Path 在最前面加上:%MAVEN_HOME%\bin;(注意,最后要有个”;”作为分隔符)

完成之后,在命令行输入:mvn -version查看是否有以下内容,如果有表示配置成功。
2.1.3 配置Maven数据仓库
在路径C:\apache-maven-3.5.0\conf\settings.xml 下
下面是maven默认的国外仓库配置,下载非常慢(默认的注释的,可以删除),所以要改成国内阿里云的仓库


    -- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    
      mirrorId
      repositoryId
      Human Readable Name for this Mirror.
      http://my.repository.com/repo/path
    
     -->
  

修改后的

<mirror>
        <id>nexus-aliyunid>
        <mirrorOf>*mirrorOf>
        <name>Nexus aliyunname>
        <url>http://maven.aliyun.com/nexus/content/groups/publicurl>
    mirror> 

2.1.4 Eclipse中集成Maven

2.1.4.1 安装Maven
Maven,SSM框架搭建(连接ORACLE数据库)_第1张图片

Maven,SSM框架搭建(连接ORACLE数据库)_第2张图片
如果没有此选择则要选择m2eclipse插件安装
Maven,SSM框架搭建(连接ORACLE数据库)_第3张图片
选择完成即可,我这里已经添加过,只是演示一下过程。

2.1.4.2 自定义用户设置
Maven,SSM框架搭建(连接ORACLE数据库)_第4张图片
我这里为了自己能够理解更清晰,就创建了一个新目录serverMaven用于保存下载的Jar包(多个盘符的话可以省空间,要在Setting.xml中设置,如下图),Setting文件复制出来一份也放在serverMaven(此步骤纯属个人意愿)。
Maven,SSM框架搭建(连接ORACLE数据库)_第5张图片
附:m2eclipse插件的安装
Maven,SSM框架搭建(连接ORACLE数据库)_第6张图片

Maven,SSM框架搭建(连接ORACLE数据库)_第7张图片

2.2 Manen 项目创建

Maven,SSM框架搭建(连接ORACLE数据库)_第8张图片

Maven,SSM框架搭建(连接ORACLE数据库)_第9张图片

Maven,SSM框架搭建(连接ORACLE数据库)_第10张图片

Maven,SSM框架搭建(连接ORACLE数据库)_第11张图片
这里我已经添加过了,所以报错,改个名字就好。
创建完成后目录如下
Maven,SSM框架搭建(连接ORACLE数据库)_第12张图片

2.2 Manen 导入Jar包

2.2.1 使用Manen 导入Jar包

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.xdgroupId>
  <artifactId>ssmartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>ssm Maven Webappname>
  <url>http://maven.apache.orgurl>
  
  <properties>  
          
        <spring.version>4.0.2.RELEASEspring.version>  
          
        <mybatis.version>3.2.6mybatis.version>  
          
        <slf4j.version>1.7.7slf4j.version>  
        <log4j.version>1.2.17log4j.version>  
    properties>  

    <dependencies>  
        <dependency>  
            <groupId>junitgroupId>  
            <artifactId>junitartifactId>  
            <version>4.11version>  
              
            <scope>testscope>  
        dependency>  
          
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-coreartifactId>  
            <version>${spring.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-webartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-oxmartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-txartifactId>  
            <version>${spring.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-jdbcartifactId>  
            <version>${spring.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-webmvcartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-aopartifactId>  
            <version>${spring.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-context-supportartifactId>  
            <version>${spring.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-testartifactId>  
            <version>${spring.version}version>  
        dependency>  
          
        <dependency>  
            <groupId>org.mybatisgroupId>  
            <artifactId>mybatisartifactId>  
            <version>${mybatis.version}version>  
        dependency>  
          
        <dependency>  
            <groupId>org.mybatisgroupId>  
            <artifactId>mybatis-springartifactId>  
            <version>1.2.2version>  
        dependency>  
          
        <dependency>  
            <groupId>javaxgroupId>  
            <artifactId>javaee-apiartifactId>  
            <version>7.0version>  
        dependency>  
          
        <dependency>  
            <groupId>mysqlgroupId>  
            <artifactId>mysql-connector-javaartifactId>  
            <version>5.1.30version>  
        dependency>  
          
        <dependency>  
            <groupId>commons-dbcpgroupId>  
            <artifactId>commons-dbcpartifactId>  
            <version>1.2.2version>  
        dependency>  
          
        <dependency>  
            <groupId>jstlgroupId>  
            <artifactId>jstlartifactId>  
            <version>1.2version>  
        dependency>  
          
          
        <dependency>  
            <groupId>log4jgroupId>  
            <artifactId>log4jartifactId>  
            <version>${log4j.version}version>  
        dependency>  


          
        <dependency>  
            <groupId>com.alibabagroupId>  
            <artifactId>fastjsonartifactId>  
            <version>1.1.41version>  
        dependency>  


        <dependency>  
            <groupId>org.slf4jgroupId>  
            <artifactId>slf4j-apiartifactId>  
            <version>${slf4j.version}version>  
        dependency>  

        <dependency>  
            <groupId>org.slf4jgroupId>  
            <artifactId>slf4j-log4j12artifactId>  
            <version>${slf4j.version}version>  
        dependency>  
          
          
        <dependency>  
            <groupId>org.codehaus.jacksongroupId>  
            <artifactId>jackson-mapper-aslartifactId>  
            <version>1.9.13version>  
        dependency>  
          
        <dependency>  
            <groupId>commons-fileuploadgroupId>  
            <artifactId>commons-fileuploadartifactId>  
            <version>1.3.1version>  
        dependency>  
        <dependency>  
            <groupId>commons-iogroupId>  
            <artifactId>commons-ioartifactId>  
            <version>2.4version>  
        dependency>  
        <dependency>  
            <groupId>commons-codecgroupId>  
            <artifactId>commons-codecartifactId>  
            <version>1.9version>  
        dependency>  
    dependencies>  
  <build>
    <finalName>ssmfinalName>
  build>
project>

这里导入的是MySql的JAR包,OJDBC(Oracle的JAR包我没用MAVEN管理,不知道如何配置,知道的可以告诉我,万分感谢)。

2.2.2 导入OJDBC6 Jar包
我使用的是ORACLE 11G 11.2.0.1
首先在官网下载:
http://www.oracle.com/technetwork/cn/articles/oem/jdbc-112010-094555-zhs.html
完成后导入即可
Maven,SSM框架搭建(连接ORACLE数据库)_第13张图片
这里有一个问题参考我的另一篇博文
http://blog.csdn.net/xudong1107/article/details/77709526

3.SSM整合

3.1 Spring和Mybatis整合

项目结构图如下,需要什么包可以创建
Maven,SSM框架搭建(连接ORACLE数据库)_第14张图片
3.1.1 建立JDBC属性文件
jdbc.properties(文件编码修改为utf-8,操作步骤为打开文件的属性,更改编码)
Maven,SSM框架搭建(连接ORACLE数据库)_第15张图片

oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.username=xd
oracle.password=xudong
oracle.validationQuery=select 1 from dual
#注意一下名称,在Spring-Mybatis整合文件中要对应的
#定义初始连接数  
initialSize=0  
#定义最大连接数  
maxActive=20  
#定义最大空闲  
maxIdle=20  
#定义最小空闲  
minIdle=1  
#定义最长等待时间  
maxWait=60000   

3.1.1 建立spring-mybatis.xml文件

  
<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:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
      
    <context:component-scan base-package="com.xd.ssm">context:component-scan>  
      
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    bean>  

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close" >  
        <property name="driverClassName" value="${oracle.driver}" />  
        <property name="url" value="${oracle.url}" />  
        <property name="username" value="${oracle.username}" />  
        <property name="password" value="${oracle.password}" />  
          
          
        <property name="initialSize" value="${initialSize}">property>  
          
        <property name="maxActive" value="${maxActive}">property>  
          
        <property name="maxIdle" value="${maxIdle}">property>  
          
        <property name="minIdle" value="${minIdle}">property>  
          
        <property name="maxWait" value="${maxWait}">property>  
    bean>  

      
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
          
        <property name="mapperLocations" value="classpath:com/xd/ssm/mapping/*.xml">property>  
    bean>  

      
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.xd.ssm.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>  
    bean>  

      
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    bean>  
beans>

3.2 Log4j的配置

为了方便调试,一般都会使用日志来输出信息,Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
Log4j的配置很简单,而且也是通用的,下面给出一个基本的配置,换到其他项目中也无需做多大的调整,如果想做调整或者想了解Log4j的各种配置,参考下面这篇博文:
http://blog.csdn.net/zhshulin/article/details/37937365

log4j.rootLogger = INFO,Console,File

log4j.appender.Console = org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target = System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern = [%c] - %m%n


log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = All
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

3.3 整合SpringMVC

3.3.1. 配置spring-mvc.xml


<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:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans    
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> 
                         
    <context:component-scan base-package="com.xd.ssm.controller">context:component-scan>
     
    <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
        <property name="supportedMediaTypes">
        <list>
        <value>text/html;charset=UTF-8value>
        list>
        property>     
    bean> 
      
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">  
            <list>  
                <ref bean="mappingJacksonHttpMessageConverter" />   
            list>  
        property>  
    bean>
      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
     <property name="prefix" value="/" />  
     <property name="suffix" value=".jsp" />  
    bean> 
     
    <bean id="multipartResolver"    
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
          
        <property name="defaultEncoding" value="utf-8" />    
          
        <property name="maxUploadSize" value="10485760000" />    
          
        <property name="maxInMemorySize" value="40960" />    
    bean>                     
beans>

3.3.2 配置web.xml文件
这里面对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合


<web-app 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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>SSMdisplay-name>

       
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:spring-mybatis.xmlparam-value>  
    context-param>  
      
    <filter>  
        <filter-name>encodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <async-supported>trueasync-supported>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>encodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  
      
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>  
      
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>  
    listener>  

      
    <servlet>  
        <servlet-name>SpringMVCservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
            <param-value>classpath:spring-mvc.xmlparam-value>  
        init-param>  
        <load-on-startup>1load-on-startup>  
        <async-supported>trueasync-supported>  
    servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVCservlet-name>  
          
        <url-pattern>/url-pattern>  
    servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jspwelcome-file>  
    welcome-file-list>  

web-app>

至此,整合完毕再看下目录结构
Maven,SSM框架搭建(连接ORACLE数据库)_第16张图片

4.测试

4.1 利用MyBatis Generator自动创建代码

4.1.1 下载MyBatis Generator
http://download.csdn.net/detail/u012909091/7206091
4.1.2 导入MyBatis Generator
Maven,SSM框架搭建(连接ORACLE数据库)_第17张图片
即新建JAVA项目保存下来这些文件这样可以保存在工作空间中便于以后整合使用,不设置在工作空间中也可以使用
4.1.3 配置generatorConfig.xml

  
  
<generatorConfiguration>  
  
    <classPathEntry  location="ojdbc6.jar"/>  
    <context id="DB2Tables"  targetRuntime="MyBatis3">  
        <commentGenerator>  
            <property name="suppressDate" value="true"/>  
              
            <property name="suppressAllComments" value="true"/>  
        commentGenerator>  
          
        <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl" userId="xd" password="xudong">  
        jdbcConnection>  
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false"/>  
        javaTypeResolver>  
          
        <javaModelGenerator targetPackage="com.xd.ssm.model" targetProject="C:\Users\Prince\ssm-workspace\ssm\src\main\java">  
            <property name="enableSubPackages" value="true"/>  
            <property name="trimStrings" value="true"/>  
        javaModelGenerator>  
          
        <sqlMapGenerator targetPackage="com.xd.ssm.mapping" targetProject="C:\Users\Prince\ssm-workspace\ssm\src\main\java">  
            <property name="enableSubPackages" value="true"/>  
        sqlMapGenerator>  
          
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.xd.ssm.dao" targetProject="C:\Users\Prince\ssm-workspace\ssm\src\main\java">  
            <property name="enableSubPackages" value="true"/>  
        javaClientGenerator>  
          
        <table tableName="user_t" domainObjectName="userT" enableCountByExample="false" 
               enableUpdateByExample="false" enableDeleteByExample="false" 
               enableSelectByExample="false" selectByExampleQueryId="false">table>
    context>  
generatorConfiguration>

4.1.4 使用MyBatis Generator
进入mybatis-3.4.0.jar所在目录下,执行
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
命令即可。
4.1.5 MyBatis Generator生成的文件

dao接口

package com.xd.ssm.dao;

import com.xd.ssm.model.userT;

public interface userTMapper {
    int deleteByPrimaryKey(Long id);

    int insert(userT record);

    int insertSelective(userT record);

    userT selectByPrimaryKey(Long id);

    int updateByPrimaryKeySelective(userT record);

    int updateByPrimaryKey(userT record);
}

mapping映射文件



<mapper namespace="com.xd.ssm.dao.userTMapper" >
  <resultMap id="BaseResultMap" type="com.xd.ssm.model.userT" >
    <id column="ID" property="id" jdbcType="DECIMAL" />
    <result column="USER_NAME" property="userName" jdbcType="VARCHAR" />
    <result column="PASSWORD" property="password" jdbcType="VARCHAR" />
    <result column="AGE" property="age" jdbcType="DECIMAL" />
  resultMap>
  <sql id="Base_Column_List" >
    ID, USER_NAME, PASSWORD, AGE
  sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from USER_T
    where ID = #{id,jdbcType=DECIMAL}
  select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from USER_T
    where ID = #{id,jdbcType=DECIMAL}
  delete>
  <insert id="insert" parameterType="com.xd.ssm.model.userT" >
    insert into USER_T (ID, USER_NAME, PASSWORD, 
      AGE)
    values (#{id,jdbcType=DECIMAL}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{age,jdbcType=DECIMAL})
  insert>
  <insert id="insertSelective" parameterType="com.xd.ssm.model.userT" >
    insert into USER_T
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      if>
      <if test="userName != null" >
        USER_NAME,
      if>
      <if test="password != null" >
        PASSWORD,
      if>
      <if test="age != null" >
        AGE,
      if>
    trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=DECIMAL},
      if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        #{password,jdbcType=VARCHAR},
      if>
      <if test="age != null" >
        #{age,jdbcType=DECIMAL},
      if>
    trim>
  insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.xd.ssm.model.userT" >
    update USER_T
    <set >
      <if test="userName != null" >
        USER_NAME = #{userName,jdbcType=VARCHAR},
      if>
      <if test="password != null" >
        PASSWORD = #{password,jdbcType=VARCHAR},
      if>
      <if test="age != null" >
        AGE = #{age,jdbcType=DECIMAL},
      if>
    set>
    where ID = #{id,jdbcType=DECIMAL}
  update>
  <update id="updateByPrimaryKey" parameterType="com.xd.ssm.model.userT" >
    update USER_T
    set USER_NAME = #{userName,jdbcType=VARCHAR},
      PASSWORD = #{password,jdbcType=VARCHAR},
      AGE = #{age,jdbcType=DECIMAL}
    where ID = #{id,jdbcType=DECIMAL}
  update>
mapper>

实体类文件

package com.xd.ssm.model;

public class userT {
    private Long id;

    private String userName;

    private String password;

    private Short age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Short getAge() {
        return age;
    }

    public void setAge(Short age) {
        this.age = age;
    }
}

4.2 建立Service接口和实现类

先看下结构图
Maven,SSM框架搭建(连接ORACLE数据库)_第18张图片
bean里放公用组件和类等,
controller是控制器包。

dao放的是Dao接口,
mapping为Mapping映射文件,
model是实体类。 这三者由MyBatis Generator自动生成,请注意在generatorConfig.xml中对应。

service是事务接口,
serviceImpl是事务接口具体实现类。

4.2.1 Service接口

package com.xd.ssm.service;

import com.xd.ssm.model.userT;

public interface UserTService {
    public userT getUserById(Long UserId);

}

4.2.1 Service具体实现类

package com.xd.ssm.serviceImpl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xd.ssm.dao.userTMapper;
import com.xd.ssm.model.userT;
import com.xd.ssm.service.UserTService;

@Service("UserTService")
public class UserTServiceImpl implements UserTService{
    @Resource 
    private userTMapper UserTMapper;
    public userT getUserById(Long UserId) {
        // TODO 自动生成的方法存根
        return this.UserTMapper.selectByPrimaryKey(UserId);
    }

}

4.3 建立Controller控制器

package com.xd.ssm.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xd.ssm.model.userT;
import com.xd.ssm.service.UserTService;

@Controller
@RequestMapping("/user")
public class UserTController {
    @Resource
    private UserTService userTSer;

    @RequestMapping("/showUser")
     public String toIndex(HttpServletRequest request, Model model){  

        Long userId = Long.valueOf(request.getParameter("id"));

        userT user = this.userTSer.getUserById(userId);

        System.out.println(user.getUserName());
        model.addAttribute("user", user);  
        return "WEB-INF/jsp/showUser";
    }  
}

4.4 建立JSP文件

Maven,SSM框架搭建(连接ORACLE数据库)_第19张图片
位置要与控制器中返回的位置相同

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

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>测试title>
head>
<body>
 ${user.userName}  
body>
html>

测试结果

Maven,SSM框架搭建(连接ORACLE数据库)_第20张图片
前台传参依据Controller的要求。

至此搭建结束。
感谢!参考博文http://blog.csdn.net/vchen_hao/article/details/70226422
http://www.cnblogs.com/liumt/p/6215445.html

你可能感兴趣的:(JAVA)