本文在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)文件目录大体如下:
(8)将工程变成web工程
此时,我们的工程还不是标准的web工程,可以在eclipse中增加web工程的特性,选择工程的Properties,选Project Facets,点击Convert to faceted form... 如下图:
这里,我们选择Dynamic Web Module,版本选择2.4,这个版本比较通用,我本机为默认版本。 如下图:
这样,我们的工程就完全是一个web工程了。
三、文件配置
(1)配置pom.xml,让jar包飞一会。如果pom.xml保存后,有错误提示,很可能是jar包重复,可注释掉重复的引用
文件pom.xml
文件web.xml 路径:WEB-INF下
>
< web-app >
< display-name > Archetype Created Web Applicationdisplay-name >
< context-param >
< param-name > contextConfigLocationparam-name >
< param-value > /WEB-INF/config/app-context.xmlparam-value >
context-param >
< filter >
< filter-name > characterEncodingFilterfilter-name >
< filter-class > org.springframework.web.filter.CharacterEncodingFilterfilter-class >
< init-param >
< param-name > encodingparam-name >
< param-value > UTF-8param-value >
init-param >
< init-param >
< param-name > forceEncodingparam-name >
< param-value > trueparam-value >
init-param >
filter >
< filter-mapping >
< filter-name > characterEncodingFilterfilter-name >
< url-pattern > /*url-pattern >
filter-mapping >
< listener >
< listener-class > org.springframework.web.context.ContextLoaderListenerlistener-class >
listener >
< servlet >
< servlet-name > examservlet-name >
< servlet-class > org.springframework.web.servlet.DispatcherServletservlet-class >
< init-param >
< param-name > contextConfigLocationparam-name >
< param-value > /WEB-INF/config/spring-servlet.xmlparam-value >
init-param >
servlet >
< servlet-mapping >
< servlet-name > examservlet-name >
< url-pattern > /url-pattern >
servlet-mapping >
< welcome-file-list >
< welcome-file > index.jspwelcome-file >
welcome-file-list >
web-app >
文件app-context.xml 路径:WEB-INF/config下
"1.0" encoding="UTF-8" ?>
"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:
http:
http:
http:
http:
class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
"locations" value="/WEB-INF/config/jdbc.properties" />
"dataSource" class ="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" >
"driverClassName" value="${jdbc.driver}" />
"url" value="${jdbc.url}" />
"username" value="${jdbc.user}" />
"password" value="${jdbc.password}" />
"initialSize" value="60" />
"maxActive" value="100" />
"maxIdle" value="50" />
"minIdle" value="10" />
"sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
"dataSource" ref="dataSource" />
class ="org.mybatis.spring.mapper.MapperScannerConfigurer" >
"basePackage" value="com.mxy.mapper" />
文件spring-servlet.xml 路径:WEB-INF/config下
"1.0" encoding="UTF-8" ?>
"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:
http:
http:
http:
package ="com.mxy" />
class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
"viewResolver" class ="org.springframework.web.servlet.view.InternalResourceViewResolver" >
"prefix" >
/jsp/
"suffix" >
.jsp
文件jdbc.properties 路径:WEB-INF/config下
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:
jdbc.user=test
jdbc.password=123456
文件test.sql,这个文件直接在数据库下执行即可
SET FOREIGN_KEY_CHECKS=0;
drop database if exists test;
create database test;
use test;
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 resultMap = new HashMap();
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
"1.0" encoding="UTF-8" ?>
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
"com.mxy.mapper.TestMapper" >
"account_Result" type="com.mxy.model.User" >
"id" column="id" jdbcType="DECIMAL" />
"username" column="userName" jdbcType="VARCHAR" />
"password" column="password" jdbcType="VARCHAR" />
"email" column="email" jdbcType="DECIMAL" />
"insert" parameterType="com.mxy.model.User" >
insert into account(userName,password,email) values(#{userName},#{password},#{email})
"select" parameterType="com.mxy.model.User" resultType="com.mxy.model.User" >
select * from account where userName=#{userName}
文件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) {
return accountMapper.insert(entity);
}
public User select(User entity) {
return accountMapper.select(entity);
}
}
文件index.jsp 路径:webapp下
<%
request.getRequestDispatcher("/jsp/add.jsp" ).forward(request,response);
%>
文件error.jsp 路径:webapp/jsp下
<%@ page isELIgnored="false" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
"Content-Type" content="text/html; charset=utf-8" >
Insert title here
用户已经存在,"/spring_test" >返回
文件add.jsp 路径:webapp/jsp下
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
"Content-Type" content="text/html; charset=utf-8" >
Insert title here
文件success.jsp 路径:webapp/jsp下
<%@ page isELIgnored="false" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
"Content-Type" content="text/html; charset=utf-8" >
Insert title here
恭喜,添加成功!
用户名:${user.userName}
密码:${user.password}
邮箱:${user.email}
邮箱:${userName}
"/spring_test" >返回
发布后访问本地地址 http://localhost:8080/spring_test 如
KO。。。。
上面我们提到插入到数据库是乱码,我们可以根据这篇文章解决:http://blog.csdn.net/zht666/article/details/8955952