spring2.5+spring MVC + ibatis2.3.4 + FreeMarker2.3

步骤:


1、 导入jar 包
Spring2.5.jar  commons-logging.jar ,ibatis-2.3.4.726.jar ,mysql-connecotr.jar , freemarker.jar
2、 写实体bean ,dao
3、 配置 该实体bean 的ibatis.xml 文档
      1) 配置结果集
      2) 写相应的sql 语句
4、 配置spring + ibatis 的集成
       1) 配置数据源
       2) 配置sqlMapClient
       3) 事务管理器
       4) 注入sqlMapClient 及其它对象
5、 配置spring + freeMarker 的集成
       1) 控制器的映射
       2) 方法解析
       3) 视图解析
       4) FreeMarker 解析
       5) 当前控制器的注入
6、 写spring MVC 的controll 类
7、 页面开发
8、 Web.xm 配置
      1)、读取spring 配置文件
      2) spring 编码过滤

      3)spring MVC 的DispatcherServlet

 

实例:

javaBean:
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	private Integer id;
	
	private String name;
	
	private String sex;
	
	private Integer age;
	
	private String phone;
              
               get .... 
               set ...... 方法
}

 

实体bean的ibatis 文件 userModel.xml

<sqlMap namespace="User">

  <!-- Use type aliases to avoid typing the full classname every time. -->
  <typeAlias alias="User" type="com.figure.entry.User"/>

  <!--定义了一个结果集 -->
  <resultMap id="userResult" class="User">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="age" column="age"/>
    <result property="sex" column="sex"/>
    <result property="phone" column="phone"/>
  </resultMap>

  <!-- Select with no parameters using the result map for Account class. -->
  <select id="selectAllUser" resultMap="userResult">
    select * from user
  </select>

  <!-- A simpler select example without the result map.  Note the 
       aliases to match the properties of the target result class. -->
  <select id="selectUserById" parameterClass="Integer"  resultClass="User">
    select
      id ,
      name,
      sex,
      age,
      phone
    from user
    where id = #id#
  </select>
   
  <!-- Insert example, using the Account parameter class -->
  <insert id="insertUser" parameterClass="User">
    insert into user (
      id,
      name,
      sex,
      age,
      phone )
    values ( #id#, #name#, #sex#, #age#,#phone# )
  </insert>

  <!-- Update example, using the Account parameter class -->
  <update id="updateUser" parameterClass="User">
    update user set
      name = #name#,
      sex = #sex#,
      age = #age#,
      phone=#phone#
    where
      id = #id#
  </update>

  <!-- Delete example, using an integer as the parameter class -->
  <delete id="deleteUserById" parameterClass="integer">
    delete from user where id = #id#
  </delete>

</sqlMap>

 

userDaoImpl 类

public class UserDaoImpl implements UserDao {
	
	private SqlMapClient sqlMapClient;

	public void setSqlMapClient(SqlMapClient sqlMapClient) {
		this.sqlMapClient = sqlMapClient;
	}

	public void del(Integer id) throws Exception {
		this.sqlMapClient.delete("deleteUserById",id);

	}

	public void save(User user)throws Exception {
		this.sqlMapClient.insert("insertUser",user);
	}

	public void update(User user)throws Exception {
		this.sqlMapClient.update("updateUser",user);
	}

	public List<User> users()throws Exception {
		return this.sqlMapClient.queryForList("selectAllUser");
	}

	public User getUser(Integer id) throws Exception {
		return (User) this.sqlMapClient.queryForObject("selectUserById",id);
	}

}

 

   springCommon.xml配置

 <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">      
             <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>      
             <property name="url" value="jdbc:mysql://localhost/first_test"></property>      
             <property name="username" value="root"></property>      
             <property name="password" value="root"></property>      
           </bean>     

	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
  <!-- 事务管理器 -->      
 <bean id="ibatisManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">      
  <property name="dataSource" ref="dataSource"></property>      
 </bean>      
   <!-- 事务拦截器 -->      
 <bean id="trInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">      
  <property name="transactionManager" ref="ibatisManager"></property>      
  <property name="transactionAttributes">      
   <props>      
   <prop key="*">PROPAGATION_REQUIRED</prop>      
   </props>      
  </property>      
 </bean>      
 <!-- 自动代理 -->      
 <bean id="autoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">      
     <property name="beanNames">      
     <list>      
      <value>*DAO</value>      
      </list>      
     </property>      
     <property name="interceptorNames">      
        <list>      
            <value>trInterceptor</value>      
         </list>      
     </property>      
    </bean>
	
	<bean id="userDao" class="com.figure.dao.impl.UserDaoImpl">
		<property name="sqlMapClient" ref="sqlMapClient"></property>	
	</bean>
	
	<bean id="userService" class="com.figure.service.impl.UserServiceImpl">
		<property name="userDao" ref="userDao"></property>
	</bean>

 

   UserFtl.java类

public class UserFtl extends MultiActionController {
	
		private UserService userService;
		public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public ModelAndView addUser(HttpServletRequest request,
			HttpServletResponse response,User user) throws Exception{
		System.out.println(user);
		userService.save(user);
		return userList(request,response);
	}
	
	public ModelAndView userList(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		List<User> list =userService.users();
		Map map = new HashMap();
		map.put("userList", list);
		return new ModelAndView("test",map);
	}

 spring  exampleServlet.xml

 <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">
        </bean>


        <!--配置控制器的映射-->

        <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

                <property name="mappings">
                    <props>
                        <!--  <prop key="*.do">userAction</prop>-->
                        <prop key="*.do">userFtl</prop>
                    </props>
                </property>

        </bean>
        
        <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
 <property name="paramName">
   <value>method</value>
  </property>
  <property name="defaultMethodName">
   <value>htmlFile</value>
  </property>
      </bean>  
        
        <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
  <property name="freemarkerSettings" >
     <props>
       <prop key="template_update_delay">0</prop>
       <prop key="default_encoding">gbk</prop>
       <prop key="locale">zh_CN</prop>
     </props>
  </property>
 <!--   <property name="exposeSpringMacroHelpers" value="true"/>-->
</bean>

<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
 <!-- 是否需要缓存 -->
 <property name="cache">
   <value>true</value>
 </property>
 
 <property name="suffix">
  <value>.ftl</value>
 </property>
 
 <property name="prefix">
  <value></value>
 </property>
 
 <!-- 解决中文乱码问题 -->
 <property name="contentType" value="text/html;charset=gbk"></property>
 <property name="viewClass">
  <value>org.springframework.web.servlet.view.freemarker.FreeMarkerView</value>
 </property>
</bean>
        

             <bean id="userFtl" class="com.figure.action.UserFtl">
        <property name="userService" ref="userService"></property>
         <property name="methodNameResolver">
           <ref bean="methodNameResolver"/>
     </property>
        
        </bean>
</beans>

 
web.xml配置文件

<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>
  
  <filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>gbk</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	
	<servlet>
        <servlet-name>exampleServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>         
         <param-name>contextConfigLocation</param-name>         
         <param-value>/WEB-INF/exampleServlet.xml</param-value>
        </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>exampleServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

 三、常遇到的问题

 
1、 乱码问题:

在freemarker 中 显示乱码:

配置 FreeMarker 的解析中

<prop key="default_encoding">gbk</prop> 换成gbk

  

   插入到数据库时出现乱码:

      在web.xml 中 配置的过滤器中,编码换成gbk

 

2、 找不到freemarker 页面

在配置 FreeMarker 的解析,有一个参数

<property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>

所以在

new ModelAndView("test",map) 跳转页面时,该text.ftl 必须位于当前目录下

 

2)在 new ModelAndView("test",map) 不需要 加上后缀名 ,因为在视图解析时,已经配置了

<property name="suffix"> //所有显示视图的时候,都会+ 上.ftl 的后缀

  <value>.ftl</value>

 </property> , 所以始终会找寻test.ftl 这个文件

 

 

3、 如何知道MultiActionController 中调用了哪个方法

 

通过两个配置,及 在地址栏中输入地址时所带的参数决定 的

1)通过这种配置

<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">

   …  两个属性

 

2) 通过地址栏访问 (method 所传递的参数就是 要调用的方法名

   http://localhost:8080/firstTest/addUser.do?method=addUser

 

4、 MultiActionController 是如何把页面上的form 封装到实体bean的

该方法应如此写:

  public ModelAndView addUser(HttpServletRequest request,

          HttpServletResponse response,User user)

 

在调用该方法时:

  页面上的名称会通过 反射自动映射到 user 对象 中

 

 

5、 freemarker 中不能这样写

 <#if userList !=null> </#if>

应换成: <#if userList??> </#if>

 

6、 Spring MVC 是如何把查询所得到的结果集带到页面上的

通过map 集合 再 new ModelAndView("test",map)带过去

 

7、 页面上如何获得map 中的值

${key}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值