jar包 引入 ibatis jack 以及spring用到的jar包
其中 ibatis的包括有
jack的包括
spring 的包括
由于时间紧急 没有来得及对jar包进行详细的分类 所以有存在位置错误的情况
接下来 配置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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!--
字符过滤转码(防止添加到数据库中的数据为乱码)
-->
<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>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在这个中间有个springmvc的配置 这个在spring内部的处理 就是去寻找springmvc-servlet.xml默认在web-inf下面进行查询
所以我们在web-inf下面创建springmvc-servlet.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.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">
<context:annotation-config
/>
<context:component-scan
base-package="com.cn"/>
<mvc:interceptors>
<bean class="com.cn.interceptor.MyInterceptor"
>
</bean>
</mvc:interceptors>
<bean
id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property
name="viewClass"
value="org.springframework.web.servlet.view.JstlView"
/>
<property name="prefix" value="/"
/>
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<bean
class
="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
>
<property
name="messageConverters">
<list>
<ref
bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
</beans>
然后配置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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx"
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://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<!-- 需要扫描带注解类的包 -->
<context:component-scan
base-package="com.cn" />
<!-- AOP的注解支持
-->
<aop:aspectj-autoproxy />
<!-- 引入数据库连接
-->
<context:property-placeholder
location="classpath:conf/db.properties" />
<!--
配置数据源,使用BasicDataSource (另外一个比较好的数据源c3p0)-->
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
>
<property name="driverClassName"
value="${mysql.driverClassName}"></property>
<property
name="url"
value="${mysql.url}"></property>
<property
name="username"
value="${mysql.username}"></property>
<property
name="password"
value="${mysql.password}"></property>
<property
name="initialSize"
value="${mysql.initialSize}"></property>
<property
name="maxActive"
value="${mysql.maxActive}"></property>
<property
name="maxIdle"
value="${mysql.maxIdle}"></property>
</bean>
<!--
配置Ibatis的sqlMapClient -->
<bean
id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<property name="dataSource"
ref="dataSource"
/>
<!--configLocation属性指定mybatis的核心配置文件-->
<property
name="configLocation"
value="classpath:conf/SqlMapConfig.xml"
/>
</bean>
<!--MapperScannerConfigurer配置-->
<bean
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--basePackage指定要扫描的包,在此包之下的映射器都会被
搜索到。可指定多个包,包与包之间用逗号或分号分隔-->
<property
name="annotationClass"
value="org.springframework.stereotype.Repository"/>
<property
name="basePackage" value="com.cn"
/>
</bean>
</beans>
db.properties
mysql.driverClassName=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/traveler?useUnicode=true&characterEncoding=UTF-8
mysql.username=root
mysql.password=
mysql.initialSize=5
mysql.maxActive=100
mysql.maxIdle=10
log4j.properties
# For JBoss: Avoid to setup Log4J outside
$JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment
out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=info,
stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d
%p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${ibatis_spring.root}/WEB-INF/ibatis_spring.log
log4j.appender.logfile.MaxFileSize=512KB
#
Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern
to output: date priority [category] -
message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d
%p [%c] - %m%n
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--表明重用预编译的SQL语句-->
<!-- 加载常量 -->
<!-- <properties
resource="globalContants.properties" />
-->
<settings>
<setting
name="defaultExecutorType" value="REUSE"
/>
</settings>
<typeAliases>
<typeAlias
alias="user" type="com.cn.userCenter.pojo.User"
/>
</typeAliases>
</configuration>
这样基本的springMVC+Ibatis配置就已经完成
然后就是基本操作的一些代码
package com.cn.action;
import java.io.IOException;
import java.text.DateFormat;
import
java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.beans.propertyeditors.CustomDateEditor;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.ServletRequestDataBinder;
import
org.springframework.web.bind.annotation.InitBinder;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestMethod;
import
org.springframework.web.bind.annotation.ResponseBody;
import
org.springframework.web.servlet.mvc.SimpleFormController;
import com.cn.annotation.RequestAttribute;
import
com.cn.common.DemoException;
import com.cn.common.GlobalContext;
import
com.cn.service.UserService;
import com.cn.userCenter.pojo.User;
import
com.cn.utils.MD5;
@Controller
@RequestMapping(value="user")
public class UserController
extends SimpleFormController {
private static final Logger log =
Logger.getLogger(UserController.class);
@Autowired
private
UserService userService;
/**
* 登录
*
@param request
* @param response
*/
@RequestMapping(value="/login.do",method=RequestMethod.POST)
public
void login(HttpServletRequest request,HttpServletResponse response)
{
userService.getUserById(1);
}
/**
*
注册
* @param request
* @param response
* @throws
IOException
*/
@RequestMapping(value="/addUser.do",method=RequestMethod.POST)
@ResponseBody
@RequestAttribute(value="user",name="name")
public
void logon( User user,HttpServletRequest request,HttpServletResponse response)
throws IOException {
try {
/**
*
添加数据
*/
user.setPassword(MD5.getMD5(user.getPassword()));
userService.saveUser(user);
response.getWriter().print(GlobalContext.SAVE_SUCCESS);
}
catch (IOException e) {
DemoException d=new
DemoException(e.getMessage());
log.error(d.getMessage());
response.getWriter().print(GlobalContext.SAVE_FAILD);
}
}
@RequestMapping(value
= "/hello")
public String hello(HttpServletRequest
request, HttpServletResponse response)
{
userService.getUserById(1);
return "hello";
}
@RequestMapping(value="/queryCountByUserName.do",method=RequestMethod.POST)
@RequestAttribute(value="user",name="name")
public
void queryCountByName( User user,HttpServletRequest request,HttpServletResponse
response) throws IOException {
try {
int
count=userService.queryCountByName(user.getUserName());
response.getWriter().print(count);
}
catch (RuntimeException e) {
DemoException d=new
DemoException(e.getMessage());
log.error(d.getMessage());
response.getWriter().print(GlobalContext.EXCEPTION);
}
}
@InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
DateFormat fmt = new
SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor dateEditor = new
CustomDateEditor(fmt, true);
binder.registerCustomEditor(Date.class,
dateEditor);
super.initBinder(request, binder);
}
}
package com.cn.service.impl;
import org.apache.commons.lang3.StringUtils;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Service;
import com.cn.dao.UserDao;
import com.cn.service.UserService;
import
com.cn.userCenter.pojo.User;
@Service
public class UserServiceImpl
implements UserService {
@Autowired
private UserDao userDao;
public boolean
checkUser(String userName, String password)
{
if(StringUtils.isNotEmpty(userName) &&
StringUtils.isNotEmpty(password)){
return
false;
}
return false;
}
public User getUserById(Integer id)
{
System.out.println("Success");
if(StringUtils.isNotEmpty(id+"")){
return
userDao.getUserById(id);
}
return
null;
}
@Override
public void saveUser(User user)
{
userDao.saveUser(user);
}
@Override
public int queryCountByName(String userName)
{
return
userDao.queryCountByName(userName);
}
}
package com.cn.dao;
import org.springframework.stereotype.Repository;
import com.cn.userCenter.pojo.User;
@Repository
public interface
UserDao {
User getUserById (int id);
void saveUser(User user);
int queryCountByName(String userName);
}
<?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.cn.dao.UserDao">
<sql id="selectHead"> select
userid,username,password,birthday,age,cardno,description,photo from db_user
u</sql>
<select id="getUserById" parameterType="int"
resultType="user">
<include refid="selectHead"/>
where u.userid=#{id}
</select>
<insert id="saveUser"
parameterType="user">
insert into
db_user(userid,username,password,age,birthday,cardno,description,photo,sex,telephone,phone,hobbies,grade)
values(#{userId},
#{userName,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},#{age,jdbcType=VARCHAR},#{birthday,jdbcType=VARCHAR},
#{cardNo,jdbcType=VARCHAR},#{description,jdbcType=VARCHAR},#{photo,jdbcType=VARCHAR},#{sex,jdbcType=VARCHAR},
#{telephone,jdbcType=VARCHAR},#{phone,jdbcType=VARCHAR},#{hobbies,jdbcType=VARCHAR},#{grade,jdbcType=VARCHAR})
</insert>
<select
id="queryCountByName" parameterType="string" resultType="int">
select
count(1) from db_user where
username=#{userName}
</select>
</mapper>
就这样
一个简单的基于springMVC以及Ibatis的配置就已经完成了
然后启动tomcat进行访问
http://pan.baidu.com/s/1dDABNrz