天天看點

spring2.5學習筆記之一:IOC和MVC

       1spring2.5的使用在配置上已經有了很大的改進。特别在自動裝配上面的改進最為明顯。我的項目裡用spring2.5和ibatis2.3來開發的,其中spring2.5就是用ioc,mvc,還有就是資料持久ibatis。現在貼一部分代碼出來,分析分析。

       頁面index.jsp

jsp頁面 寫道 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<form name="form1" action="<c:url value='/userdao/checklogin.do '/>" method="post" >

<input type="text" name="username" id="usernaem" value=""/>

<input type="password" name="password" id="password" value=""/>

<br>

<input type=" submit " name="submit" id="submit" value="submit"/>

</form>

</body>

</html>

   上面的頁面是一個測試的jsp頁面,其中action送出請求到背景控制器,代碼如下。

LoginController 寫道 package com.spring.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

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

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.spring.manageri.UserDaoManager;

@Controller

public class LoginController {

@Autowired

private UserDaoManager userDaoManager;

@SuppressWarnings("unchecked")

@RequestMapping(value="/userdao/checklogin.do ")

public ModelAndView checkLogin (HttpServletRequest request,HttpServletResponse response){

return new ModelAndView("/welcome");

}

}

 在控制器裡面的RequestMapping(value="/userdao/checklogin.do ")這個值和頁面上的action 相對應。在頁面送出的時候spring2.5容器便可以找到這個連結來處理請求(注意這個value="/userdao/checklogin.do "必須是全局唯一的。) 

 另外還有就是注解

 @Autowired

 private UserDaoManager userDaoManager;

UserDaoManager是一個接口,并且有它自己的實作類UserDaoManagerImpl,這個類用來處理業務邏輯。代碼如下。

UserDaoManager 寫道 package com.spring.manageri;

import java.util.List;

public interface UserDaoManager {

public abstract List getUserList();

}   UserDaoManagerImpl 寫道 package com.spring.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.spring.common.IbatisDaoSupport;

import com.spring.manageri.UserDaoManager;

@Service

@Transactional

public class UserDaoManagerImpl extends IbatisDaoSupport implements UserDaoManager {

@Override

public List getUserLists() {

// TODO Auto-generated method stub

return null;

}

}

 其中IbatisDaoSupport是一個自定類,代碼如下。

IbatisDaoSupport 寫道 package com.spring.common;

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

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;

public class IbatisDaoSupport extends SqlMapClientDaoSupport {

@Autowired

public void setSqlMapClientForAutowire(SqlMapClient sqlMapClient) {

super.setSqlMapClient(sqlMapClient);

}

}

這裡采用這個類主要是為了避免每一次去操縱資料庫都要去配置檔案裡注入sqlMapClient的問題,采用繼承,業務邏輯的實作類隻需要繼承它即可。ibatis的配置檔案。sqlmapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig

    PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"

    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

    <settings cacheModelsEnabled="true" lazyLoadingEnabled="true"

        enhancementEnabled="true" errorTracingEnabled="true"

        useStatementNamespaces="false" maxRequests="30" maxSessions="20"

        maxTransactions="10" />

     <sqlMap

        resource="com/spring/domain/user.xml" />

</sqlMapConfig>

 com.spring.domain.user.xml這個檔案就是ibatis的業務邏輯的實作檔案,裡面是對資料庫的操作代碼(sql).還有就是user.xml對應的pojo,user.java:

User.java 寫道   User.java 寫道 package com.spring.domain;

import java.io.Serializable;

import java.util.Date;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

private Integer id;

private String username;

private String password;

private String picture;

private String address;

private Integer trustlevel;

private String tel;

private String qq;

private String email;

private String ip;

private Date jointime;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

..........................

}

 配置檔案是這樣的。

 首先是 applicationcontext-web.xml

applicationcontext-web.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:context="http://www.springframework.org/schema/context"

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">

<import resource="applicationContext-propertyConfigurer.xml"/>

<context:component-scan base-package="com.spring.web"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

<property name="prefix" value="/jsp"/>

<property name="suffix" value=".jsp"/>

</bean>

<bean id="urlFilenameViewController"

class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:order="1"/>

</beans>

 <context:component-scan base-package="com.spring.web"/>明确要掃描的控制包。

1<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

2<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

其中1和2用來處理通過方法名稱的映射。是頁面請求送出到背景的路徑的解釋器。

Autowired 寫道 <?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:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<context:annotation-config/>

<context:component-scan base-package="com.spring.impl" />

</beans>

 這個配置檔案指明了處理業務邏輯的包,這樣Spring容器可以制動裝配類對象。下面的配置檔案用來連接配接資料庫:并且把資料源注入到ibatis中

applicationContext-propertyConfigurer.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:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<!-- c3p0 datasource -->

<!-- bean id="dataSource"

class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close" p:driverClass="${jdbc.driverClass}"

p:jdbcUrl="${jdbc.jdbcUrl}" p:user="${jdbc.user}"

p:password="${jdbc.password}">

<property name="initialPoolSize"

value="5" />

<property name="maxPoolSize" value="10" />

</bean-->

<bean id="dataSource"

class="com.mchange.v2.c3p0.ComboPooledDataSource"

destroy-method="close" p:driverClass="oracle.jdbc.driver.OracleDriver"

p:jdbcUrl="jdbc:oracle:thin:@127.0.0.1:1521:oracle9" p:user="dgdr"

p:password="dgdr">

<property name="initialPoolSize"

value="5" />

<property name="maxPoolSize" value="10" />

</bean>

<!-- Transaction manager for a single JDBC DataSource (alternative to JTA) -->

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSourceTransactionManager"

p:dataSource-ref="dataSource" />

    <tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="lobHandler"

class="org.springframework.jdbc.support.lob.DefaultLobHandler" />

<bean id="sqlMapClient"

class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

<property name="configLocation"

value="/WEB-INF/config/ibatis/sqlmap-config.xml">

</property>

<property name="dataSource" ref="dataSource"></property>

<property name="lobHandler" ref="lobHandler"/>

</bean>

</beans>  

  <bean id="sqlMapClient"

   class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

    <property name="configLocation"

    value="/WEB-INF/config/ibatis/sqlmap-config.xml">

   </property>

   <property name="dataSource" ref="dataSource"></property>

   <property name="lobHandler" ref="lobHandler"/>

</bean>

把資料源注入到ibatis中。下面是web.xml的綜合配置。

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">

<display-name>spring</display-name>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/config/applicationContext-propertyConfigurer.xml

/WEB-INF/config/applicationContext-business.xml

</param-value>

</context-param>

<context-param>

<param-name>log4jConfigLocation</param-name>

<param-value>/WEB-INF/config/log4j.properties</param-value>

</context-param>

<filter>

<filter-name>Encoding</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>

</filter>

<filter-mapping>

<filter-name>Encoding</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<listener>

<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

</listener>

<listener>

<listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>

</listener>

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/config/applicationContext-web.xml

</param-value>

</init-param>

   <load-on-startup>1</load-on-startup>

</servlet>

  <servlet-mapping>

     <servlet-name>spring</servlet-name>

     <url-pattern>*.do</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

     <welcome-file>jsp/index.jsp</welcome-file>

   </welcome-file-list>

</web-app>  

繼續閱讀