基于maven和SSM(spring+springMVC+mybatis)的实例

1、环境搭建

搭建maven环境,DOC下输入mvn -v查看是否配置成功maven环境。新建mvn工程选择webapp,双击进入

这里写图片描述

工程结构:
这里写图片描述

2、自动生成代码

文件结构:
这里写图片描述
生成方法:
本地路径 D:\generator下新建如下文件,导入图中包(前提是本地搭建好了maven环境,DOC下输入mvn -v查看是否配置成功),在路径D:\generator>下,DOC执行命令:

java -jar mybatis-generator-core-1.3.5.jar -configfile generator.xm
l -overwrite
![这里写图片描述](https://img-blog.csdn.net/20170808115632628?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjM0ODkzMDM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

图中文件数据:

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
<generatorConfiguration>  
    <!-- 数据库驱动包位置 -->  
    <classPathEntry location="D:\generator\mysql-connector-java-5.1.30.jar" />   
    <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />-->  
    <context id="DB2Tables" targetRuntime="MyBatis3">  
        <commentGenerator>  
            <property name="suppressAllComments" value="true" />  
        </commentGenerator>  
        <!-- 数据库链接URL、用户名、密码 -->  
         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test02?characterEncoding=utf8" userId="root" password="root">   
        <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->  
        </jdbcConnection>  
        <javaTypeResolver>  
            <property name="forceBigDecimals" value="false" />  
        </javaTypeResolver>  
        <!-- 生成模型的包名和位置 -->  
        <javaModelGenerator targetPackage="andy.model" targetProject="D:\generator\src">  
            <property name="enableSubPackages" value="true" />  
            <property name="trimStrings" value="true" />  
        </javaModelGenerator>  
        <!-- 生成的映射文件包名和位置 -->  
        <sqlMapGenerator targetPackage="andy.mapping" targetProject="D:\generator\src">  
            <property name="enableSubPackages" value="true" />  
        </sqlMapGenerator>  
        <!-- 生成DAO的包名和位置 -->  
        <javaClientGenerator type="XMLMAPPER" targetPackage="andy.dao" targetProject="D:\generator\src">  
            <property name="enableSubPackages" value="true" />  
        </javaClientGenerator>  
        <!-- 要生成那些表(表是已经存在的)(更改tableName和domainObjectName就可以) -->  
        <table tableName="emps" domainObjectName="Emps" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />  -->
        <!--<table tableName="course_user_info" domainObjectName="CourseUserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> -->  
    </context>  
</generatorConfiguration>

注意文件路径必须正确
将生成问加你copy到项目文件中

需要创建表格及模拟导入数据:

DROP TABLE IF EXISTS  emps;  
CREATE TABLE emps 
(id int(10) NOT NULL, 
name varchar(30) NOT NULL, 
age int(10) NOT NULL, 
salary float NOT NULL, 
PRIMARY KEY (id)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into emps(id,name,age,salary) values (1,'zjx',21,100);
insert into emps(id,name,age,salary) values (2,'zht',22,110);
insert into emps(id,name,age,salary) values (3,'qqq',23,120);
insert into emps(id,name,age,salary) values (4,'www',24,130);
insert into emps(id,name,age,salary) values (5,'aaa',25,140);
insert into emps(id,name,age,salary) values (6,'qzzzqq',26,150)

3、配置文件

工程配置文件结构:
这里写图片描述

文件说明:
1>jdbc.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test02?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
username=root
password=root
#定义初始连接数  
initialSize=0
#定义最大连接数 
maxActive=20
#定义最大空闲  
maxIdle=20
#定义最小空闲  
minIdle=1
#定义最长等待时间  
maxWait=60000  

2>log4j.properties:

#定义LOG输出级别  
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  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
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>applicationContext-dao.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 引入配置文件 -->
    <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="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        <!-- 连接池最大数量 -->
        <property name="maxActive" value="30"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="5"></property>

    </bean>

    <!--spring与mybatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <!-- <property name="mapperLocations" value="classpath:com/ssm/mapping/*.xml"></property> -->
        <!-- 全局配置 -->
        <!-- 若不保留mybatis配置文件用上面那条替换这一条 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml" />
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,需要扫描多个包中间用逗号隔开 -->
        <property name="basePackage" value="andy.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

4>applicationContext-services.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="andy.service.impl" />
</beans>

5>applicationContext-transaction.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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源dataSource在applicationContext-dao.xml中配置了 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 启用事务 -->
    <tx:annotation-driven transaction-manager="transactionmanager" />
</beans>

6>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>
    <mappers>
        <!-- 注册empsMapper.xml文件 -->
        <mapper resource="andy/mapping/EmpsMapper.xml" />
    </mappers>
</configuration>  

7>spring-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns: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-4.0.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="andy.controller" />
    <!-- 处理静态资源 和解放MVC的原有功能-->  
    <mvc:default-servlet-handler/>  
    <mvc:annotation-driven>   </mvc:annotation-driven> 
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <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>  

4、service接口及类

文件结构:
这里写图片描述
1>接口IEmpsService

package andy.service;

import andy.model.Emps;

public interface IEmpsService {  
    public Emps getEmpsById(int id);  
}  

2>实现类EmpsServiceImpl

package andy.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import andy.dao.EmpsMapper;
import andy.model.Emps;
import andy.service.IEmpsService;

@Service("empsService")  
public class EmpsServiceImpl implements IEmpsService {  
    @Resource  
    private EmpsMapper empsDao;  
    @Override
    public Emps getEmpsById(int id) {  
        // TODO Auto-generated method stub  
        return this.empsDao.selectByPrimaryKey(id);  
    }    
}  

5、controller类

文件结构:
这里写图片描述

类EmpsController:

package andy.controller;

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

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller; 

import andy.model.Emps;
import andy.service.IEmpsService;  

@Controller  
@RequestMapping("/emps")  // url路径
public class EmpsController {  
    @Resource  
    private IEmpsService empsService;  

    @RequestMapping("/getById")  //url路径
    public ModelAndView  getById(HttpServletRequest request,ModelAndView model){  
        int id = Integer.parseInt(request.getParameter("id"));  
        Emps emps = this.empsService.getEmpsById(id);  
        model.addObject("emps", emps); //视图模型,向页面传递对象
        model.setViewName("empsList");  //指定视图文件,路径在spring-mvc下指定
        return model;  
    }  
} 

DEMO下载路径:
https://github.com/duangYiXia/SSM-DEMO/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值