手把手搭建一个SpringMVC+ibatis 工程

很早以前就想写一篇关于SpringMVC+ibatis的初级入门日志了,最近不那么忙了就自己动手搭了搭框架,写了这篇初级入门教程,希望可以帮到刚入门的萌新,哈哈,废话不多说,直接开撸。

先创建一个工程,如下图:


一 、 编辑web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<!-- 应用名称 -->
  	<display-name>XueShenWeb</display-name>	
	<!-- 应用程序上下文参数,指定log4j日志框架使用的配置参数文件位置 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<!-- 加载所有的spring配置文件 --> 
	<context-param> 
		<param-name>contextConfigLocation</param-name> 
		<param-value> 
			classpath:applicationContext.xml
		</param-value> 
	</context-param> 
	<!-- 采用监听器加载 --> 
	<listener> 
	  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
	</listener>
	
 	<!-- Spring配置 -->
 	<servlet>  
	    <servlet-name>spring-mvc</servlet-name>  
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
	    <init-param>  
	        <param-name>contextConfigLocation</param-name>  
	        <param-value>classpath:springMVC-servlet.xml</param-value>  
	    </init-param>  
	    <load-on-startup>1</load-on-startup>  
	 </servlet>  
    
	 <servlet-mapping>  
	    <servlet-name>spring-mvc</servlet-name>  
	    <url-pattern>/</url-pattern>  <!-- 拦截所有URL -->
	 </servlet-mapping>  
	 
 	<!-- 中文编码filter -->
	<filter> 
		<filter-name>encodingFilter</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>encodingFilter</filter-name>  
	  	<url-pattern>/*</url-pattern>  
	 </filter-mapping> 
	 <!-- 以下配置的作用是 强行指定浏览器以gb2312编码格式打开HTM和HTML  -->
	 <mime-mapping>
		<extension>htm</extension>
		<mime-type>text/html;charset=gb2312</mime-type>
	 </mime-mapping> 
	 <mime-mapping>
		<extension>html</extension>
		<mime-type>text/html;charset=gb2312</mime-type>
	 </mime-mapping> 
	 
</web-app>

二、 在src 下 添加  

applicationContext-common.xml,
applicationContext-dao.xml, 
applicationContext-service.xml,
applicationContext.xml 这4个文件

 

怎么写这四个文件,还有大致的作用:

applicationContext-common.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:aop="http://www.springframework.org/schema/aop"    
    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/tx     
          	http://www.springframework.org/schema/tx/spring-tx.xsd
          	http://www.springframework.org/schema/context     
          	http://www.springframework.org/schema/context/spring-context.xsd  
          	http://www.springframework.org/schema/aop     
         	http://www.springframework.org/schema/aop/spring-aop.xsd"
			default-autowire="byName" >
		
	<!-- 数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
        <!--  
        <property name="url" value="jdbc:mysql://xxxx" />  
        <property name="username" value="xxxx" />  
        <property name="password" value="xxxx" />  
        -->
        
        <property name="url" value="jdbc:mysql://xxx.28.140.xx:3306/xueshen" />  
        <property name="username" value="xxx" />  
        <property name="password" value="xxx" />  
        
        <property name="maxActive" value="5" />  
        <property name="maxIdle" value="2" /> 
       
        <property name="validationQuery" value="SELECT 1" />  
        <property name="testWhileIdle" value="true" />  
        <property name="testOnReturn" value="true" />  
        <property name="testOnBorrow" value="true" />
        
    </bean>  
	<!-- 事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
    <!-- 工厂bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="configLocation" value="classpath:sql-map-config.xml" />  
        <property name="dataSource" ref="dataSource" />  
    </bean>
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="sqlSessionFactory"/>  
    </bean>  
    <!-- 对service层进行事务管理 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<tx:attributes>
    		<tx:method name="insert*" propagation="REQUIRED"/>
    		<tx:method name="update*" propagation="REQUIRED"/>
    		<tx:method name="delete*" propagation="REQUIRED"/>
    		<tx:method name="get*" propagation="REQUIRED"/>
    		<tx:method name="check*" propagation="REQUIRED"/>
    		<tx:method name="regist*" propagation="REQUIRED"/>
    		<tx:method name="login*" propagation="REQUIRED"/>
    		<tx:method name="logout*" propagation="REQUIRED"/>
    		<tx:method name="validate*" propagation="REQUIRED"/>
    		<tx:method name="*" read-only="false" rollback-for="xxx.dao.DAOException"/>
    	</tx:attributes>
    </tx:advice>
  	<aop:config>
    	<aop:advisor advice-ref="txAdvice" pointcut="execution(* xxxx.service.impl..*ServiceImpl.*(..))"/>
    </aop:config>
    
    <!-- 自动扫描组件,需要把controller去掉,否则影响事务管理  
     <context:component-scan base-package="com.aokunsang">  
        <context:exclude-filter type="regex" expression="com.yunhulu.web.*"/>  
     </context:component-scan>  --> 
     
</beans>

applicationContext-dao.xml

配置dao层

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans.xsd"
			default-autowire="byName" >		
	<bean  class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>		
  	<bean id="userDAO" class="cn.maple.xueshen.dao.impl.IbatisUserDAO"/>
</beans>

applicationContext-service.xml

配置Service 层

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans.xsd"
			default-autowire="byName" >
    
  	 <span style="white-space:pre">	</span><bean id="userService" class="cn.maple.xueshen.service.impl.UserServiceImpl"/>

</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"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans.xsd"
			default-autowire="byName" >
	<import resource="applicationContext-common.xml"/>		
	<import resource="applicationContext-dao.xml"/>
	<import resource="applicationContext-service.xml"/>
</beans>

三、在src 下建springMVC-servlet.xml和sql-map-config.xml两个文件

下面分别说明这两个文件写的是什么,还有大致的作用


springMVC-servlet.xml

<pre name="code" class="html"><?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: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"
			default-autowire="byName" >
		
	<!-- 扫描指定的包中的类上的注解 -->  
    <context:component-scan base-package="cn.maple.xueshen.*"/>  
    <!-- 启用默认注解映射 -->  
	<mvc:annotation-driven/>
	<!-- 视图解释类 -->  
    <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean> -->
    
    <!-- ===================================================== -->
    <!-- ViewResolver For FreeMarker -->
    <!-- ===================================================== -->
    <bean id="freemarkerResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="order" value="1" />
        <!-- 这里是定义视图层文件的后缀名,我下面测试项目中后缀名是html 所以这里后缀名应该把ftl改为html -->
<span style="white-space:pre">	</span><property name="suffix" value=".ftl" />
        <property name="contentType" value="text/html;charset=utf-8" />
        <property name="requestContextAttribute" value="rc"></property>
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value>
        </property>
    </bean>
    <!-- ===================================================== -->
    <!-- ViewResolver For FreeMarkerConfigurer -->
    <!-- ===================================================== -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath">
            <value>/views/</value>
        </property>
        <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性 -->
            <props>
                <prop key="template_update_delay">5</prop><!--刷新模板的周期,单位为秒 -->
                <prop key="default_encoding">UTF-8</prop><!--模板的编码格式 -->
                <prop key="locale">UTF-8</prop><!-- 本地化设置 -->
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="number_format">0.####</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="whitespace_stripping">true</prop>
                <prop key="tag_syntax">auto_detect</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
            </props>
        </property>
    </bean>
    
    <!-- JSON支持 -->
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <bean  
                    class="org.springframework.http.converter.StringHttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>text/html;charset=UTF-8</value>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>  
    </bean>  
    <!-- <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >  
    	<property name="supportedMediaTypes" value="text/plain;charset=UTF-8" />
	</bean> -->
	 <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>text/json;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    	
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   	<property name="messageConverters">
      <list>
         <!-- <ref bean="mappingJacksonHttpMessageConverter" /> -->
         <ref bean="mappingJackson2HttpMessageConverter" />
      </list>
   	</property>
	</bean>
    <!-- 支持上传文件 设置文件大小-->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	    <property name="maxInMemorySize">
			<value>5400000</value>
		</property>
	</bean>  

    <!-- 静态资源的访问方案一   -->
    <mvc:default-servlet-handler/>
    <!-- 静态资源的访问方案二 
    <mvc:resources location="/resources/**" mapping="/WEB-INF/resources/"/>  -->
   
</beans>


 
 
 
 

sql-map-config.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>

    <!-- 基础配置 -->
    <!--
    <settings>  
        这个配置使全局的映射器启用或禁用缓存  
        <setting name="cacheEnabled" value="true"/>  
        全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载  
        <setting name="lazyLoadingEnabled" value="true"/>  
        当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载  
        <setting name="aggressiveLazyLoading" value="true"/>  
        允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)  
        <setting name="multipleResultSetsEnabled" value="true"/>  
        使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动  
        <setting name="useColumnLabel" value="true"/>  
        允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby)  
        <setting name="useGeneratedKeys" value="true"/>  
        指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况)  
        <setting name="autoMappingBehavior" value="PARTIAL"/>  
        配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新  
        <setting name="defaultExecutorType" value="SIMPLE"/>  
        设置超时时间,它决定驱动等待一个数据库响应的时间  
        <setting name="defaultStatementTimeout" value="25000"/>  
    </settings>


    -->


    <!-- 别名定义 -->

    <typeAliases>
        <typeAlias alias="user" type="cn.maple.xueshen.entity.User"/>
    </typeAliases>  
      
  
    <!-- 映射文件,存放sql语句的配置文件 -->  
    <mappers>  
          <mapper resource="cn/maple/xueshen/dao/mapper/user.xml"/>
    </mappers>  
  
</configuration> 

4、接下来加入jar包(jar包我的下载分享里有)然后开始建Controller

在src 下建一个包名为 cn.maple.xueshen.controller( xueshen 就是学生的意思 哈哈  = = )

package cn.maple.xueshen.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.maple.xueshen.entity.User;
import cn.maple.xueshen.service.intf.UserService;

@Controller
@RequestMapping("/go")
public class UserController {
	@Autowired
	private UserService userService;
	
	@InitBinder("userDO")
	public void initBinder1(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("userDO.");
	}
	
	@RequestMapping(value = { "/index",""})
	public String  index(){
	
		return "xueshen/index";
		
	} 
	
	@RequestMapping(value = { "/register"})
	public String  register(ModelMap model , User user ){
		userService.register(user);
		return "xueshen/registerOk";
		
	} 
	@RequestMapping(value = { "/load"})
	public String  load(ModelMap model , User user ){
		String psw =user.getPsw();
		String psw2 =userService.getOne(user.getName()).getPsw();
		System.out.println("xxxxx"+psw2);
	    if(psw.equals(psw2)) {
	    	return "xueshen/loadOk";
	    }else {
	    	return "xueshen/loadFail";
		}
	}
}

5、建service接口和实现类

package cn.maple.xueshen.service.intf;

import cn.maple.xueshen.entity.User;


public interface UserService {
	// 查询列表集合
		public int register(User user) ;
		public User getOne(String name);
}

package cn.maple.xueshen.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import cn.maple.xueshen.dao.intf.UserDAO;
import cn.maple.xueshen.entity.User;
import cn.maple.xueshen.service.intf.UserService;

public class UserServiceImpl  implements UserService{
	@Autowired
	private UserDAO userDao;
	
	public int register(User user) {
	
		return userDao.insert(user);
	}

	@Override
	public User getOne(String name) {
		System.out.println("YYY");
		return userDao.getOne(name);
	
	}
	
}

6、建DAO接口 和实现类


package cn.maple.xueshen.dao.intf;

import cn.maple.xueshen.entity.User;

public interface UserDAO {
	public int insert(User user);
	public User getOne(String name);

}
package cn.maple.xueshen.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.ibatis.session.SqlSession;

import cn.maple.xueshen.dao.intf.UserDAO;
import cn.maple.xueshen.entity.User;

public class IbatisUserDAO implements UserDAO {
	
	protected SqlSession sqlSession;
	
	/**
	 * 注入sqlSession
	 * 
	 * @param sqlSession
	 */
	public void setSqlSession(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}



	@Override
	public int insert(User user) {
		return sqlSession.insert("cn.maple.xueshen.entity.User" + "."
				+ "insert", user);
	}

	@Override
	public User getOne(String name) {
		return sqlSession.selectOne("cn.maple.xueshen.entity.User" + "."
				+ "getOne", name);
	}

	

}

7、建一个entity 

package cn.maple.xueshen.entity;

public class User {
	private int userId ;
	private String name ;
	private int age ;
	private String address ;
	private String phoneNumber ;
	private String psw ;
	public String getPsw() {
		return psw;
	}
	public void setPsw(String psw) {
		this.psw = psw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	
 
}

8、建一个放sql文的 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">
<!-- 命名空间路径采用实体类完整路径 -->
<mapper namespace="cn.maple.xueshen.entity.User" >

 
    
    <select
        id="getOne"
        resultType="user"  parameterType="String" >
		SELECT   user_id as userId ,name,age,address,phone_number as phoneNumber,psw
		FROM userxueshen where name=#{name} 

    </select>

    <insert
        id="insert"
        parameterType="user" >
		insert into userxueshen (name,age,address,phone_number,psw) 
		values(#{name},#{age},#{address},123,#{psw})

    </insert>
    

   

</mapper>

到现在为止我的工程目录:




9、创建测试的基本页面吧 

index.html 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<span>注册</span>

<form action="http://localhost:8080/XueShenWeb/go/register" method="post" class="form-x">
<input type="text" name="name"   value="yan"><br/>
<input type="text" name="psw"  value="yan" ><br/>
<input type="text" name="age"   value="66">
<button type="submit">注册</button>
</form>
<br/><br/>
<span>登入</span>
<form action="http://localhost:8080/XueShenWeb/go/load" method="post" class="form-x">
<input type="text" name="name" value="chen" ><br/>
<input type="text" name="psw"   value="123"     >
<button type="submit">登入</button>

</form>
</body>
</html>

loadFail.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
密码错误,登录失败!
</body>
</html>

registerOk.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
恭喜! 注册成功。 欢迎你加入小学生队伍!
</body>
</html>

10:测试





到这里基本结束了,有问题可以私信我,评论里问也行,希望大家一起讨论交流,一起进步。


















  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值