前面说完怎么样创建maven web项目,这篇继续向web项目中整合进ssm(spring+springmvc+mybatis)的框架。
先发个目录图片,让萌新们知道下面提到的文件是创建在什么地方。
1、web.xml文件
修改如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="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>study</display-name> <!-- 加载Spring容器配置 --> <!-- 监听器无法为spring框架设置其需要处理的请求格式 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置Spring容器加载配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置DispatchcerServlet --> <!-- 注册spring mvc ,就需要为其设置处理的请求格式 就需要使用另外一个类代替监听器 --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring mvc下的配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 1)load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法)。 2)它的值必须是一个整数,表示servlet应该被载入的顺序 2)当值为0或者大于0时,表示容器在应用启动时就加载并初始化这个servlet; 3)当值小于0或者没有指定时,则表示容器在该servlet被选择时才会去加载。 4)正数的值越小,该servlet的优先级越高,应用启动时就越先加载。 5)当值相同时,容器就会自己选择顺序来加载。 <load-on-startup>x</load-on-startup>,中x的取值1,2,3,4,5代表的是优先级,而非启动延迟时间。 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 注册的同时为这个框架设置其需要处理的请求格式 --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</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>index.jsp</welcome-file> </welcome-file-list> </web-app>
web.xml
2、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" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 引入db.properties属性文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 引入多个以properties结尾的配置文件 --> <!-- <context:property-placeholder location="classpath:*.properties"/> --> <!-- 扫描除了 controller 之外的bean --> <context:component-scan base-package="com.su.study.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 数据源的配置 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close" p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:maxActive="${ds.maxActive}" p:username="${jdbc.username}" p:password="${jdbc.password}" p:initialSize="${ds.initialSize}"/> <!--===================== mybatis ========================--> <!-- SqlSessionFactory(mybatis) --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:mapperLocations="classpath:com/su/study/mapping/*.xml" p:dataSource-ref="dataSource"/> <!-- 配置mybatis 的扫描器扫描接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.su.study.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- ===============事务相关===================--> <!-- 事务管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 开启事务的注解模式 --> <tx:annotation-driven transaction-manager="txManager" /> </beans>
applicationContext.xml
说明:p:basePackage="com.su.study.dao" 其实就是<property name="basePackage" value="com.su.study.dao" />
3、db.properties保存了applicationContext.xml用到的数据库信息
db.properties文件:
#mysql数据库连接 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root [email protected] ds.initialSize=5 ds.maxActive=30
db.properties
4、springmvc.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解的包,包括子集,只扫描 controller注解 --> <context:component-scan base-package="com.su.study.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 该标签可以扩展其中的一些东西,比如:responseBody的返回值编码转换。可以不 配置任何东西,但是是需要的,为了使@Controller这样的注解生效 --> <mvc:annotation-driven/> </beans>
springmvc.xml
5、在pom.xml文件中引入依赖jar包
举个例子:web.xml中的监听器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
它用到了spring-web的jar包中的类,所以需要在项目中导入spring-web的jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.2.RELEASE</version> </dependency>
pom.xml:
<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.0</modelVersion> <groupId>com.su</groupId> <artifactId>study</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>study Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.3.2.RELEASE</spring.version> <mybatis.version>3.4.1</mybatis.version> <mybatis-spring.version>1.3.0</mybatis-spring.version> <druid.version>1.0.27</druid.version> <mybatis-generator-core.version>1.3.2</mybatis-generator-core.version> <servlet-api.version>2.5</servlet-api.version> <jackson.version>2.8.5</jackson.version> <slf4j.version>1.7.7</slf4j.version> <fastjson.version>1.2.31</fastjson.version> </properties> <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!-- spring扩展包,在基础IoC功能上的扩展服务 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- spring web开发应用包,提供controller层的核心封装 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- spring对JDBC数据访问的封装 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis 包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis与spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- mybatis-generator自动生成工具 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>${mybatis-generator-core.version}</version> </dependency> <!-- mybatis 使用 durid 数据源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!-- mysql JDBC驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <!-- JSON和Java对象转换--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- servlet jar包,包含HttpServletRequest --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <!-- 日志打印 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> </dependencies> <build> <finalName>study</finalName> <plugins> <!-- Config: Maven Tomcat Plugin --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> <resources> <!-- 打包 mybatis 的XXXMapper.xml文件--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!-- 打包 配置文件--> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> </build> </project>
pom.xml
6、mybatis的generator自动生成工具
搭建Mysql数据库:http://www.cnblogs.com/sucb/p/8968860.html
需要添加的文件如下:
1)、generatorConfig.xml
<?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> <!--导入配置文件--> <properties resource="mybatis/generator.properties"></properties> <classPathEntry location="${jdbc.driverLocation}"/><!-- 绝对路径 --> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.user}" password="${jdbc.password}"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名 targetProject 指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="${target.model.path}" targetProject="${target.project.path}"> <!-- enableSubPackages:在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false --> <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置(xml) --> <sqlMapGenerator targetPackage="${target.mapping.path}" targetProject="${target.project.path}"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置(dao 层的 xxxMapper) --> <javaClientGenerator type="XMLMAPPER" targetPackage="${target.dao.path}" targetProject="${target.project.path}"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定数据库表 ,可以有多个table标签 schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample是否生成 example类 ,false表示不生成 --> <table schema="${jdbc.user}" tableName="${database.table.name}" domainObjectName="${table.model.name}" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> </table> </context> </generatorConfiguration>
generatorConfig.xml
2)、generator.properties
#==================mysql 驱动及用户密码设置=============== jdbc.driverLocation=C:/Users/wifi/.m2/repository/mysql/mysql-connector-java/5.1.37/mysql-connector-java-5.1.37.jar jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/test jdbc.user=root [email protected] #==================生成的文件的路径设置==================== #生成的 model文件路径 target.model.path=com.su.study.model #生成的 mapper接口路径 target.dao.path=com.su.study.dao #生成xml文件路径 target.mapping.path=com.su.study.mapping #生成文件的包所在的路径 target.project.path=src/main/java #对应的数据库表名 database.table.name=user #要生成的实体类名 table.model.name=User
generator.properties
3)、MybatisGeneratorMain.java
package mybatis; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; public class MybatisGeneratorMain { public static void main(String[] args) { System.out.println("开始。。。。。"); List<String> warnings = new ArrayList<String>(); boolean overwrite = true; String genCfg = "../mybatis/generatorConfig.xml"; File configFile = new File(MybatisGeneratorMain.class.getResource(genCfg).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = null; try { config = cp.parseConfiguration(configFile); System.out.println("进行中1。。。。"); } catch (IOException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } System.out.println("进行中2。。。。。"); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = null; try { myBatisGenerator = new MyBatisGenerator(config, callback, warnings); System.out.println("结束、、、、、、"); } catch (InvalidConfigurationException e) { e.printStackTrace(); } try { myBatisGenerator.generate(null); } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
MybatisGeneratorMain.java
4)、运行MybatisGeneratorMain.java中的main方法,控制台输出如下
刷新项目,发现会生成数据库(test)下表(user)的相关文件
User.java :user表对应的实体类; UserMapper.java :user表基本的增删改查操作的接口; UserMapper.xml : UserMapper.java中增删改查对应的sql实现。
这几个文件能自动生成,具体代码就不贴了。
7、写一个测试类UserController.java,只做测试,所以没有加api、service等
package com.su.study.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.su.study.dao.UserMapper; import com.su.study.model.User; @Controller @RequestMapping("/user") public class UserController { /** * 用户表相关 */ @Autowired private UserMapper userMapper; /** * 查询 */ @RequestMapping(value = "/select", method=RequestMethod.POST, produces="application/json;charset=UTF-8") @ResponseBody public User test( @RequestBody(required=true) User user) { System.out.println("入参:" + JSON.toJSONString(user)); User u = userMapper.selectByPrimaryKey(user.getId()); System.out.println("查询结果 :" + JSON.toJSONString(u)); return u; } }
UserController.java
8、 启动项目
1)、编译并打包项目: 点击项目,右键Run As ----> Maven install
2)、启动项目:Run As ----> Maven build ----> Goals中配置tomcat的端口:tomcat7:run -Dmaven.tomcat.port=8080
3)、点击Apply ----> Run,启动项目。
9、使用Postman测试。
1)、先看下数据库记录,user表为空,插入一条数据
2)、Postman请求
这里说明一下,state的值在数据库中和查询出来不一样的原因:创建user表的sql中, `state` tinyint(1) NOT NULL DEFAULT ‘0‘ ,mybatis自动生成的文件中,state的jdbcType为BIT,对应的是java type中的boolean,数据库state的值为0时,Postman查询出来是false,为1时,查询出来就是true。
------------END-----------
原文地址:https://www.cnblogs.com/sucb/p/8968862.html