前言,第一次自己搭建环境。也是在网上查资料,自己摸索着搞的
写此文章时,又重新搭建了一次。代码亲测可跑,没有问题,欢迎反馈
本文在maven环境下整合Spring-Mybatis,其中Spring支持当下比较流行的注解注入方式,简化配置
本文存在问题,不支持数据库事务回滚,数据库存入汉字为乱码。
一、准备工作
eclipse 4.2
maven 3.1.0
maven安装就不介绍了,eclipse的maven插件版本为3.0.4,本地版本为3.1.0。用哪个版本的差别不大
二、创建Maven项目
(1)选择安装maven项目。搜索关键字maven,如下图:
(2)这里默认就行了,直接下一步
(3)搜索关键字webapp,选择maven-archetype-webapp点击下一步
(4)填写工程的Group Id,Artifact Id。
Group Id就是大项目的id,Arifact Id就是该项目的Id,点击完成。如下图:
(5)首先,完善目录,增加重要的source Folder,这个不是简单的Floder,这些文件夹是会参与编译的。增加src/main/java目录。如果创建目录时提示目录已经存在,请参考http://yudey.iteye.com/blog/1985181如下图:
(6)在webapp下创建文件夹jsp,在WEB-INF下创建文件夹config
(7)文件目录大体如下:
此时,我们的工程还不是标准的web工程,可以在eclipse中增加web工程的特性,选择工程的Properties,选Project Facets,点击Convert to faceted form... 如下图:
这里,我们选择Dynamic Web Module,版本选择2.4,这个版本比较通用,我本机为默认版本。 如下图:
三、文件配置
(1)配置pom.xml,让jar包飞一会。如果pom.xml保存后,有错误提示,很可能是jar包重复,可注释掉重复的引用
文件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>test</groupId> <artifactId>spring_test</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring_test Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <org.springframework.version>3.0.6.RELEASE</org.springframework.version> </properties> <dependencies> <!-- Spring jar --> <!-- Core utilities used by other modules. Define this if you use Spring Utility APIs (org.springframework.core.*/org.springframework.util.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Expression Language (depends on spring-core) Define this if you use Spring Expression APIs (org.springframework.expression.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define this if you use Spring Bean APIs (org.springframework.beans.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans) Define this if you use Spring AOP APIs --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Application Context (depends on spring-core, spring-expression, spring- spring-beans) This is the central artifact for Spring's Dependency Injec Container and is generally always defined --> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> <type>pom.tmp.sha1.tmp</type> </dependency> --> <!-- Various Application Context utilities, including EhCache, JavaMail, Quartz, and Freemarker integration Define this if you need any of these --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Transaction Management Abstraction (depends on spring-core, spring-bean spring-aop, spring-context) Define this if you use Spring Transactions o DAO Exception Hierarchy (org.springframework.transaction.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- JDBC Data Access Library (depends on spring-core, spring-beans, spring- spring-tx) Define this if you use Spring's JdbcTemplate API --> <!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> --> <!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, and iBatis. (depends on spring-core, spring-beans, spring-context, sprin Define this if you need ORM (org.springframework.orm.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, Castor, XStream, and XML Beans. (depends on spring-core, spring-be spring-context) Define this if you need OXM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Web application development utilities applicable to both Servlet and Portlet Environments (depends on spring-core, spring-beans, spring-conte Define this if you use Spring MVC, or wish to use Struts, JSF, or anothe web framework with Spring (org.springframework.web.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Spring MVC for Servlet Environments (depends on spring-core, spring-bea spring-context, spring-web) Define this if you use Spring MVC with a Ser Container such as Apache Tomcat --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Spring MVC for Portlet Environments (depends on spring-core, spring-bea spring-context, spring-web) Define this if you use Spring MVC with a Por Container (org.springframework.web.portlet.*) --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${org.springframework.version}</version> </dependency> <!-- Support for testing Spring applications with tools such as JUnit and TestNG This artifact is generally always defined with a 'test' scope for the integration testing framework and unit testing stubs --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <!-- Mybatis develop jar --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!-- Mybatis and Spring jar, from mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <!-- tomcat servlet develop jar --> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> <type>pom.lastUpdated</type> </dependency> --> <!-- JSTL tag library --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- mysql database driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <!--commons-dbcp and commons-pool , Configure Data Source --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.6</version> </dependency> <!-- Logging depend on the jar, like log4j,json-lib... --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency> <!-- spring upload files --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <!-- log log4g --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- dom4j analysis XML files --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- Configuration of the transaction --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.3</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2</version> </dependency> <!-- json lib --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <type>pom</type> </dependency> <!-- <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.4-SNAPSHOT</version> <type>pom</type> </dependency> --> <!-- <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>4.0-SNAPSHOT</version> <type>pom</type> </dependency> --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> <type>pom</type> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.6</version> </dependency> <!-- junit test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- others --> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>spring_test</finalName> </build> </project>
文件web.xml 路径:WEB-INF下
<!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> <display-name>Archetype Created Web Application</display-name> <!-- 配置Mybatis数据库配置文件的位置 如果不指定位置,默认找WEB-INF下applicationContext.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/app-context.xml</param-value> </context-param> <!-- 配置spring转发器 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 添加启动spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>exam</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 配置spring-servlet.xml位置 如果不指定位置,默认找WEB-INF下 项目名-servlet.xml --> <param-value>/WEB-INF/config/spring-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>exam</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 首页位置 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
文件app-context.xml 路径:WEB-INF/config下
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!-- 先引用jdbc.properties文件,待用 --> <property name="locations" value="/WEB-INF/config/jdbc.properties" /> </bean> <!-- 配置数据库 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> <!-- data source configuration --> <property name="initialSize" value="60" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="50" /> <property name="minIdle" value="10" /> </bean> <!-- 指定sqlSessionFactory。官方描述:要创建工厂 bean,放置下面的代码在 Spring 的 XML 配置文件中 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注入映射器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mxy.mapper" /> </bean> </beans>
文件spring-servlet.xml 路径:WEB-INF/config下
<?xml version="1.0" encoding="UTF-8"?> <!-- Bean头部 --> <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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- 激活@Controller模式 即声明 --> <mvc:annotation-driven /> <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改,要写到代码的外层 --> <context:component-scan base-package="com.mxy" /> <!-- 注解式声明 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 配置jsp文件前缀后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
文件jdbc.properties 路径:WEB-INF/config下
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/shop jdbc.user=test jdbc.password=123456
文件test.sql,这个文件直接在数据库下执行即可
SET FOREIGN_KEY_CHECKS=0; drop database if exists test; create database test; use test; -- ---------------------------- -- Table structure for `account` -- ---------------------------- DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=56 DEFAULT CHARSET=utf8;
文件TestController.java 路径:com.mxy.controller
package com.mxy.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.mxy.model.User; import com.mxy.service.TestService; @Controller @RequestMapping("/testc") public class TestController { @Resource private TestService accountService; @RequestMapping("/test") public ModelAndView test(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> resultMap = new HashMap<String, Object>(); String userName = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); User entity = new User(); entity.setUserName(userName); entity.setPassword(password); entity.setEmail(email); User user = accountService.select(entity); if (user != null) { return new ModelAndView("error", resultMap); } accountService.insert(entity); resultMap.put("user", entity); return new ModelAndView("success", resultMap); } }
文件TestMapper.java 路径:com.mxy.mapper
package com.mxy.mapper; import org.springframework.transaction.annotation.Transactional; import com.mxy.model.User; @Transactional public interface TestMapper { public Integer insert(User entity); public User select(User entity); }
文件TestMapper.xml 路径:com.mxy.mapper
<?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="com.mxy.mapper.TestMapper"> <resultMap id="account_Result" type="com.mxy.model.User"> <result property="id" column="id" jdbcType="DECIMAL"/> <result property="username" column="userName" jdbcType="VARCHAR"/> <result property="password" column="password" jdbcType="VARCHAR"/> <result property="email" column="email" jdbcType="DECIMAL"/> </resultMap> <insert id="insert" parameterType="com.mxy.model.User"> insert into account(userName,password,email) values(#{userName},#{password},#{email}) </insert> <select id="select" parameterType="com.mxy.model.User" resultType="com.mxy.model.User"> select * from account where userName=#{userName} </select> </mapper>
文件User.java 路径:com.mxy.model
package com.mxy.model; public class User { private int id; private String userName; private String password; private String email; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
文件TestService.java 路径:com.mxy.service
package com.mxy.service; import com.mxy.model.User; public interface TestService{ public Integer insert(User entity); public User select(User entity); }
文件TestServiceImpl.java 路径:com.mxy.service.impl
package com.mxy.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.mxy.mapper.TestMapper; import com.mxy.model.User; import com.mxy.service.TestService; @Service public class TestServiceImpl implements TestService { @Resource private TestMapper accountMapper; public Integer insert(User entity) { // TODO Auto-generated method stub return accountMapper.insert(entity); } public User select(User entity) { // TODO Auto-generated method stub return accountMapper.select(entity); } }
文件index.jsp 路径:webapp下
<html> <body> <% request.getRequestDispatcher("/jsp/add.jsp").forward(request,response); %> </body> </html>
文件error.jsp 路径:webapp/jsp下
<%@ page isELIgnored="false"%> <%@ 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"> <title>Insert title here</title> </head> <body> 用户已经存在,<a href="/spring_test">返回</a> </body> </html>
文件add.jsp 路径:webapp/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"> <title>Insert title here</title> </head> <body> <div> <form action="testc/test" method="post"> <p>用户名:<input type="text" name="username"></p> <p>密码:<input type="password" name="password"></p> <p>邮箱:<input type="text" name="email"></p> <p><input type="submit" value="添加用户"></p> </form> </div> </body> </html>
文件success.jsp 路径:webapp/jsp下
<%@ page isELIgnored="false"%> <%@ 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"> <title>Insert title here</title> </head> <body> 恭喜,添加成功!<br /> 用户名:${user.userName}<br /> 密码:${user.password}<br /> 邮箱:${user.email}<br /> 邮箱:${userName}<br /> <a href="/spring_test">返回</a><br /> </body> </html>
发布后访问本地地址 http://localhost:8080/spring_test 如
KO。。。。
上面我们提到插入到数据库是乱码,我们可以根据这篇文章解决:http://blog.csdn.net/zht666/article/details/8955952