标签:
一、maven项目的搭建
1.首先建立一个maven项目,本次整合基于eclipse。
2.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>cn.ssm</groupId> <artifactId>ssmDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssmDemo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- spring/mabatis包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- jstl包 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>videoInfo</finalName> </build> </project>
3.maven项目转成web项目
新建的maven项目目录结构和传统的web项目目录结构不一致,还需要做一些改动
(1)右键新建的项目,选择properties选项
先把Dynamic Web Module选项去掉,点击apply->OK。然后再重新进入此页面,把Dynamic Web Module选上对应版本的话我选择3.0,apply->OK。注意,此处Dynamic Web Module的版本对JDK版本是有要求的,具体要求的话,大家另行百度啦。
(2)如果建好的maven项目默认的JDK版本不是你本机装的,那还需要修改maven的setting.xml配置文件,添加下面一段代码,我本机安装的JDK版本为1.8
<profiles> <profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile>
这时候,项目的目录结构就多出了一个WebContent。将src目录下的web.xml文件复制到WebContent->WEB-INF目录下。此时的maven项目还需要在Navigator模式下,添加/src/main/java项目。
直接在main目录下添加java文件夹
(3)选择发布到tomcat的目录
到这里为止,maven项目已经建完成,jar包也通过pom.xml文件关联到项目了。下一步做springMvc + mybatis的整合
二、框架整合
1.新建一个spring-mvc.xml文件,用于配置spring注解和jsp页面的映射
<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启用SPRING MVC注解 --> <mvc:annotation-driven> </mvc:annotation-driven> <!-- 使用基于注解的方式注入java bean --> <context:component-scan base-package="com.xh.info.*"></context:component-scan> <!-- 配置jsp的访问路径 --> <bean id="Resolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
2.新建一个名为jdbc.properties的JDBC的配置文件,添加如下内容
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/db1 username=root password=root initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000
3.新建一个名为spring-mybatis.xml文件,用于整合spring和mybatis,添加如下内容
<?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:mybatis="http://mybatis.org/schema/mybatis-spring" 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://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 关联JDBC文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 数据库源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}"></property> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"/> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"/> </bean> <!-- spring和mybatis整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:com/xh/mappers/*.xml"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
4.新建lo4f.properties文件,用于配置日志信息。
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]
上面四个文件完成了springMvc的配置,spring和mybatis的整合配置,日志信息的配置。最后还需要在web.xml文件将配置 文件和项目关联起来,附上web.xml的代码
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>ssmDemo</display-name> <!-- spring和mybatis整合的文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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> <!-- spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring 内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- springMvc servlet配置 --> <servlet> <servlet-name>SpringMVC</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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
三、demo测试,搭建好的框架是否可用
1.建立controller类,测试springMvc的功能是否搭建成功
DemoController.java文件的内容如下
package com.demo.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/demo") public class DemoController { /** * 定义一个跳转到WEB-INF/page目录下,名为resultPage.jsp的页面 * @param request * @return */ @RequestMapping("test") public ModelAndView resultPage(HttpServletRequest request){ ModelAndView mav = new ModelAndView(); mav.addObject("info", "此信息来自DemoController 的 test方法"); mav.setViewName("resultPage"); return mav; } }
在WEB-INF目录下建一个叫page的文件夹,新建一个名为resultPage的jsp文件,此处新建的名字和方法中setViewName里的要一致。贴上resultPage.jsp文件
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> </head> <body> <div> ${info} </div> </body> </html>
测试结果:
下一步测试往数据库里插入记录
(1)新建一个t_product的表,附上表结构
(2)建立实体类
package com.demo.model; import java.io.Serializable; import java.util.Date; /** * 实体属性和表属性名一致,可以省去在配置文件映射的步骤 * @author Administrator * */ public class Product implements Serializable{ private static final long serialVersionUID = -3560655699428032777L; private Integer id; private String pname; private String pnumber; private String ptype; private Date pdate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getPnumber() { return pnumber; } public void setPnumber(String pnumber) { this.pnumber = pnumber; } public String getPtype() { return ptype; } public void setPtype(String ptype) { this.ptype = ptype; } public Date getPdate() { return pdate; } public void setPdate(Date pdate) { this.pdate = pdate; } }
(3)新建名为ProductMapper.xml的映射文件,用于操作表t_product,配置:
<?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="ProductMapper"> <parameterMap type="com.demo.model.Product" id="ProductMap"></parameterMap> <resultMap type="com.demo.model.Product" id="Product"></resultMap> <sql id="feild">(pname,pnumber,ptype,pdate)</sql> <insert id="insertProductSql" parameterMap="ProductMap"> insert into t_product <include refid="feild"/> values (#{pname},#{pnumber},#{ptype},#{pdate}) </insert> </mapper>
(4)在controller中写一个新方法,用来接收页面的传参。
@RequestMapping("product") public ModelAndView dbPage(HttpServletRequest request){ ModelAndView mav = new ModelAndView(); String name = request.getParameter("name"); String number = request.getParameter("number"); String type = request.getParameter("type"); Product p = new Product(); p.setPname(name); p.setPnumber(number); p.setPtype(type); p.setPdate(new Date()); productService.saveObj(p); mav.addObject("success", "保存成功"); mav.setViewName("success"); return mav; }
(5)开始用于测试的resultPage.jsp页面,修改一下,用来添加记录
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> function product(){ var pro = document.getElementById("productForm"); pro.submit(); } </script> <title>Insert title here</title> </head> <body> <form action="/ssmDemo/demo/product" id="productForm" method="post"> <label>商品名称:</label><input type="text" name="name"><br /> <label>商品编号:</label><input type="text" name="number"><br /> <label>商品类型:</label><input type="text" name="type"><br /> <input type="button" value="添加" onclick="product()"> </form> </body> </html>
(6)构建service和对应的实现类,ProductService和ProductServiceImpl代码
package com.demo.service; import com.demo.model.Product; public interface ProductService { void saveObj(Product p); }
package com.demo.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.demo.base.BaseDao; import com.demo.model.Product; import com.demo.service.ProductService; @Service("productService") public class ProductServiceImpl implements ProductService{ @Resource(name="baseDao") private BaseDao baseDao; @Override public void saveObj(Product p) { if(p != null){ baseDao.saveObject("ProductMapper.insertProductSql", p); } } }
(7)构建Dao层的代码,附上BaseDao和BaseDaoImpl代码
package com.demo.base; public interface BaseDao { /** * 数据保存 * @param sql 保存sql * @param obj 保存对象 */ void saveObject(String sql,Object obj); }
package com.demo.base.impl; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.demo.base.BaseDao; @Repository("baseDao") public class BaseDaoImpl extends SqlSessionDaoSupport implements BaseDao{ /** * 注入sessionFactory */ @Autowired public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } @Override public void saveObject(String sql, Object obj) { getSqlSession().insert(sql, obj); } }
最后通过浏览器测试
数据库记录
THE END!
标签:
原文地址:http://www.cnblogs.com/duck-ifox/p/5904971.html