搭建SpringMVC的-->传送门<--
一、环境搭建:
目录结构:
引用的JAR包:
如果是Maven搭建的话,pom.xml的配置如下:
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.yoki.edu</groupId> <artifactId>MyBatisSpringTest</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <version.springframework.boot>1.4.1.RELEASE</version.springframework.boot> <version.springframework>4.3.3.RELEASE</version.springframework> <version.mysql>5.1.35</version.mysql> <version.mybatis-3>3.4.1</version.mybatis-3> <version.mybatis.mapper>3.3.8</version.mybatis.mapper> <version.mybatis.spring>1.3.0</version.mybatis.spring> <version.mybatis.pagehelper>4.1.6</version.mybatis.pagehelper> <version.datasource.durid>1.0.26</version.datasource.durid> </properties> <!--项目依赖 --> <dependencies> <!--日志包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <!--j2ee相关包 servlet、jsp、jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--spring相关包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${version.springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${version.springframework}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${version.springframework}</version> </dependency> <!--mysql驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${version.mysql}</version> </dependency> <!--数据链接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${version.datasource.durid}</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${version.mybatis-3}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${version.mybatis.spring}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${version.mybatis.mapper}</version> </dependency> <!--其他需要的包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> </dependencies> <build> <finalName>MyBatisSpringTest</finalName> </build> </project>
二、数据库的搭建:
/*如果已经存在此数据库,先删除*/ drop database if exists apptest; /*创建并设置编码为UTF-8*/ create database apptestdefault character set utf8 ; /*选择数据库*/ use apptest; /*==============================================================*/ /* Table: uc_customer 会员表 */ /*==============================================================*/ DROP TABLE IF EXISTS uc_customer; CREATE TABLE uc_customer( fd_id INT AUTO_INCREMENT NOT NULL COMMENT'主键id', fd_idCode VARCHAR(64) COMMENT'用户编号', fd_userName VARCHAR(50) COMMENT'登录名', fd_pswd VARCHAR(128) COMMENT'密码', fd_cellphone VARCHAR(20) COMMENT'手机号', fd_email VARCHAR(30) COMMENT'邮箱', PRIMARY KEY(fd_id) )ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT'会员表';
INSERT INTO `apptest`.`uc_customer` (`fd_idCode`,`fd_userName`,`fd_pswd`,`fd_cellphone`,`fd_email`) VALUES ('101', 'ZhangSan', '***101', '07978210768', '101@yoki.com'); INSERT INTO `apptest`.`uc_customer` (`fd_idCode`,`fd_userName`,`fd_pswd`,`fd_cellphone`,`fd_email`) VALUES ('102', 'LiSi', '***102', '07978210102', '102@yoki.com');
三、配置文件的编写:
web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <!--配置首页--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!--配置springmvc DispatcherServlet--> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!--指定SpringMVC的配置文件,如果不配置这一项默认为"[servlet-name]-servlet.xml"--> <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>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--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> </web-app>
jdbc.properties文件的配置:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/AppTest?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
druid.max-wait=6000
druid.max-active=2000
druid.min-idle=1
druid.initial-size=1
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: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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--启用spring的一些annotation --> <context:annotation-config/> <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 --> <mvc:annotation-driven/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="org.yoki.edu"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--HandlerMapping 无需配置,springmvc可以默认启动--> <!--静态资源映射--> <!--本项目把静态资源放在了WEB-INF的statics目录下,资源映射如下--> <!--<mvc:resources mapping="/css/**" location="/WEB-INF/statics/css/"/>--> <!--<mvc:resources mapping="/js/**" location="/WEB-INF/statics/js/"/>--> <!--<mvc:resources mapping="/image/**" location="/WEB-INF/statics/image/"/>--> <!--但是项目部署到linux下发现WEB-INF的静态资源会出现无法解析的情况,但是本地tomcat访问正常,因此建议还是直接把静态资源放在webapp的statics下,映射配置如下--> <mvc:resources mapping="/css/**" location="/statics/css/"/> <mvc:resources mapping="/js/**" location="/statics/js/"/> <mvc:resources mapping="/image/**" location="/statics/image/"/> <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP--> <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- --> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置--> <property name="suffix" value=".jsp"/> </bean> <!-- springmvc文件上传需要配置的节点--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20971500"/> <property name="defaultEncoding" value="UTF-8"/> <property name="resolveLazily" value="true"/> </bean> </beans>
Spring的配置文件Application-context.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:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!--获取properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置数据链接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="${druid.max-active}"/> <property name="maxIdle" value="${druid.min-idle}"/> <property name="maxWait" value="${druid.max-wait}"/> </bean> <!--配置MyBatis的sessionFactory--> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--如果有MyBatis的配置文件--> <!--<property name="configLocation" value="classpath:MyBatis-config.xml"/>--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--配置MyBatis的mapper自动扫描,这个类可以通过.xml文件中的namespace的接口名,通过代理的方式帮我们生成并注册namespace的实现类--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--需要扫描的包路径--> <property name="basePackage" value="org.yoki.edu.main.mapper"/> <property name="sqlSessionFactoryBeanName" value="sessionFactory"/> </bean> <!--配置事物--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!--开启事物--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
四、类的编写:
ApplicationController.java:
package org.yoki.edu.main.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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.yoki.edu.main.service.CustomerService; /** * Created by SKY on 2017/6/4. */ @Controller @RequestMapping("home") public class ApplicationController { @Autowired private CustomerService customerService ; @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } @ResponseBody @RequestMapping("list") private String getList(){ return customerService.getList() ; } @ResponseBody @RequestMapping("getById") private String getById(@RequestParam Integer id){ return customerService.getById(id) ; } @ResponseBody @RequestMapping("listByMapper") private String getListByMapper(){ return customerService.getListByMapper() ; } @ResponseBody @RequestMapping("getByIdByMapper") private String getByIdByMapper(@RequestParam Integer id){ return customerService.getByIdByMapper(id) ; } }
CustomerService.java:
package org.yoki.edu.main.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.yoki.edu.main.dao.CustomerDao; import org.yoki.edu.main.domain.Customer; import java.util.List; /** * Created by SKY on 2017/6/4. */ @Service public class CustomerService { @Autowired private CustomerDao customerDao ; public String getList(){ List<Customer> list =customerDao.getList() ; StringBuffer buf = new StringBuffer() ; for (Customer c : list){ buf.append(buildDOM(c)) ; } return buf.toString(); } public String getById(Integer id){ List<Customer> list =customerDao.getList() ; Customer c = customerDao.getById(id) ; return buildDOM(c); } public String getListByMapper(){ List<Customer> list =customerDao.getListByMapper() ; StringBuffer buf = new StringBuffer() ; for (Customer c : list){ buf.append(buildDOM(c)) ; } return buf.toString(); } public String getByIdByMapper(Integer id){ List<Customer> list =customerDao.getList() ; Customer c = customerDao.getByIdByMapper(id) ; return buildDOM(c); } private String buildDOM(Customer c){ StringBuffer buf = new StringBuffer() ; buf.append("<ul>") ; buf.append("<li>" + c.getUserName() + "</li>") ; buf.append("<li>" + c.getPswd() + "</li>") ; buf.append("<li>" + c.getCellphone() + "</li>") ; buf.append("<li>" + c.getEmail() + "</li>") ; buf.append("</ul>") ; return buf.toString() ; } }
CustomerDao.java:
package org.yoki.edu.main.dao; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.yoki.edu.main.domain.Customer; import org.yoki.edu.main.mapper.CustomerMapper; import javax.annotation.Resource; import java.util.List; /** * Created by SKY on 2017/6/4. */ @Repository public class CustomerDao { @Autowired private SqlSessionFactory sessionFactory ; @Resource private CustomerMapper customerMapper ; //通过XML文件的Mapper的namespace + "." + (select、update、insert、delete)id,进行Mabatis的SQL操作,查看CustomerMapper.xml public List<Customer> getList(){ SqlSession session = sessionFactory.openSession() ; List<Customer> list = session.selectList("this.is.customer.mapper.namespace" + ".selectAll") ; return list ; } //通过XML文件的Mapper的namespace + "." + (select、update、insert、delete)id,进行Mabatis的SQL操作,查看CustomerMapper.xml //通过Mapper类进行Mabatis的SQL操作,查看CustomerMapper.xml public Customer getById(Integer id){ return sessionFactory.openSession().selectOne("this.is.customer.mapper.namespace" + ".selectById" , id) ; } //通过Mapper类进行Mabatis的SQL操作,查看CustomerMapperMapper.xml public List<Customer> getListByMapper(){ SqlSession session = sessionFactory.openSession() ; List<Customer> list = customerMapper.selectAll() ; return list ; } //通过Mapper类进行Mabatis的SQL操作,查看CustomerMapperMapper.xml public Customer getByIdByMapper(Integer id){ return customerMapper.selectById(id) ; } }
BasicMapper.java(只是继承了一下MyBatis的Mapper及MySqlMapper接口):
package org.yoki.edu.main.mapper; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** * Created by SKY on 2017/6/4. */ public interface BasicMapper<T> extends Mapper<T> , MySqlMapper<T>{ }
CustomerMapper.java
package org.yoki.edu.main.mapper; import org.yoki.edu.main.domain.Customer; import java.util.List; /** * Created by SKY on 2017/6/4. */ public interface CustomerMapper extends BasicMapper<Customer>{ //对应CustomerMapperMapper.xml中的selectAll public List<Customer> selectAll() ; //对应CustomerMapperMapper.xml中的selectById public Customer selectById(Integer id) ; }
两个*Mapper.xml配置文件基本一直:
CustomerMapper.xml
<?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"> <!-- namespace随意内容 --> <mapper namespace="this.is.customer.mapper.namespace"> <!-- 方法一 --> <!-- type属性对应与在MyBatis配置文件中typeAliases标签下定义的引用 --> <resultMap id="customerMapper" type="org.yoki.edu.main.domain.Customer"> <!-- 属性名称<>列名 --> <id property="id" column="fd_id"/> <result column="fd_idCode" property="idCode"/> <result column="fd_userName" property="userName"/> <result column="fd_pswd" property="pswd"/> <result column="fd_cellphone" property="cellphone"/> <result column="fd_email" property="email"/> </resultMap> <!-- resultMap属性值对应 --> <select id="selectById" resultMap="customerMapper"> select * from uc_customer where fd_id = #{id} </select> <select id="selectAll" resultMap="customerMapper"> select * from uc_customer </select> </mapper>
CustomerMapperMapper.xml
<?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"> <!-- 这里与CustomerMapper.xml有去吧 --> <!-- namespace对应Mapper类的全名 --> <mapper namespace="org.yoki.edu.main.mapper.CustomerMapper"> <!-- 后面的与CustomerMapper.xml的一致 --> </mapper>
五、输出结果