手機號碼:Request.ServerVariables("HTTP_X_UP_CALLING_LINE_ID")
手機型號:request.ServerVariables("HTTP_User-Agent")
補充:
手機號碼,要看當地的運營商了
有三種方法獲得(聯通的)
1.加密的手機號碼:被加密的手機號碼,與手機號碼一一對應。
中國聯通WAP平臺向CP Server(主域或IP地址)傳送加密手機號碼,CP Server獲取該加密手機號碼的方法為:在每次用戶發送的請求http header中取“deviceid”。
2.公開的手機號碼:中國聯通WAP平臺向CP Server(主域或IP地址)傳送公開的手機號碼,CP Server獲取該公開手機號碼的方法為:在每次用戶發送的請求http header中取“x-up-calling-line-id”。
以上要和聯通進行申請
3、你可以試這樣的方法獲得手機號碼: Mobile = request.ServerVariables("HTTP_X_UP_subno")
Mobile =mid(FromMobile,3,11) ??
asp?lp=27&id=1782582>http://www.blueidea.com/bbs/NewsDetail.asp?lp=27&id=1782582
聲明:第三種方法不保險
頭文件參考:
答7:
POST /default.asp HTTP/1.0
Host: 211.94.121.3:81
content-type: text/plain
accept-language: zh
accept-charset: ISO-8859-1, UTF-8; Q=0.8, ISO-10646-UCS-2; Q=0.6
profile: http://nds.nokia.com/uaprof/N7210r100.xml
user-agent: Nokia7210/1.0 (3.09) Profile/MIDP-1.0 Configuration/CLDC-1.0
x-wap.tod-coded: Thu, 01 Jan 1970 00:00:00 GMT
accept: */*
content-length: 1
Cookie: ASPSESSIONIDGGGQGAPU=KFHHMHPCHJFPKPEPBEDFHCJL
via: WTP/1.1 wapgw2 (Nokia WAP Gateway 3.1/CD1/3.1.43), HTTP/1.1 httpproxy2[0A0000C3] (Traffic-Server/4.0.9 [uSc ])
X-Network-info: GPRS,10.15.96.127,13810027XXX,211.139.172.70,unsecured
X-Forwarded-For: 10.15.96.127
X-Up-Calling-Line-ID: 13810027XXX
X-Source-ID: 211.139.172.70
X-Nokia-CONNECTION_MODE: CLESS
X-Nokia-BEARER: GPRS
X-Nokia-gateway-id: NAWG/3.1/Build43
Client-ip: 192.168.0.6
Connection: keep-alive
package cn.itcast.bean;
public class Person {
private Integer id;
private String name;
public Person(){
}
public Person(String name) {
this.name=name;
}
getter&&setter方法
}
Person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.itcast.bean">
<class name="Person" table="person">
<id name="id" type="integer">
<generator class="native"></generator>
</id>
<property name="name" length="10" not-null="true">
</property>
</class>
</hibernate-mapping>
定義業務接口package cn.itcast.service;
import java.util.List;
import cn.itcast.bean.Person;
public interface IPersonService {
/**
* 保存人員信息
* @param person
*/
public abstract void save(Person person);
/**
* 更新信息
* @param person
*/
public abstract void update(Person person);
/**
* 獲取人員
* @param personId
* @return
*/
public abstract Person getPerson(Integer personId);
/**
* 刪除人員信息
* @param personId
*/
public abstract void delete(Integer personId);
/**
* 獲取人員列表
* @return
*/
public abstract List<Person> getPersons();
}
package cn.itcast.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
/**
* 業務層,采用注解聲明事務
*
* @author Administrator
*
*/
@Transactional
public class PersonServiceBean implements IPersonService {
@Resource
private SessionFactory sessionFactory;
public void save(Person person) {
// 從spring 容器中得到正在管理的sessionFactory,persist方法用于保存實體
sessionFactory.getCurrentSession().persist(person);
}
public void update(Person person) {
sessionFactory.getCurrentSession().merge(person);
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
public Person getPerson(Integer personId) {
return (Person) sessionFactory.getCurrentSession().get(Person.class,
personId);
}
public void delete(Integer personId) {
sessionFactory.getCurrentSession()
.delete(
sessionFactory.getCurrentSession().load(Person.class,
personId));
}
@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
@SuppressWarnings("unchecked")
public List<Person> getPersons() {
return sessionFactory.getCurrentSession().createQuery("from Person")
.list();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<!-- 配置數據源 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="org.gjt.mm.mysql.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="" />
<!-- 連接池啟動時的初始值 -->
<property name="initialSize" value="1" />
<!-- 連接池的最大值 -->
<property name="maxActive" value="500" />
<!-- 最大空閑值.當經過一個高峰時間后,連接池可以慢慢將已經用不到的連接慢慢釋放一部分,一直減少到maxIdle為止 -->
<property name="maxIdle" value="2" />
<!-- 最小空閑值.當空閑的連接數少于閥值時,連接池就會預申請去一些連接,以免洪峰來時來不及申請 -->
<property name="minIdle" value="1" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" /><!-- 將datasource注入到sessionFactory -->
<property name="mappingResources">
<list>
<value>cn/itcast/bean/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update hibernate.show_sql=false
hibernate.format_sql=false
</value>
</property>
</bean>
<!-- 通過事務管理 管理sessionFactory -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="personServiceBean"
class="cn.itcast.service.impl.PersonServiceBean">
</bean>
</beans>
package junit;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
public class IPersonServiceTest {
private static IPersonService ipersonservice;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
ipersonservice=(IPersonService)ctx.getBean("personServiceBean");
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void TestSave(){
ipersonservice.save(new Person("小張"));
System.out.println("保存成功");
}
@Test public void testGetPerson(){
Person person=ipersonservice.getPerson(1);
System.out.println(person.getName());
}
@Test public void testUpdate(){
Person person=ipersonservice.getPerson(1);
person.setName("小麗");
ipersonservice.update(person);
}
@Test public void testGetPersons(){
List<Person> persons=ipersonservice.getPersons();
for(Person person : persons){
System.out.println(person.getId()+" :" +person.getName());
}
}
@Test public void testDelete(){
ipersonservice.delete(1);
}
}
table :person
id int
name varchar
package cn.itcast.service;
import java.util.List;
import cn.itcast.bean.Person;
public interface IPersonService {
public void save(Person person);
public void update(Person person);
public void delete(int personId);
public Person getPerson(int personId);
public List<Person> getPersons();
}
package cn.itcast.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
@Transactional
public class PersonServiceImpl implements IPersonService {
private JdbcTemplate jdbcTemplete;
// private DataSource datasource;
@Resource
public void setDatasource(DataSource datasource) {
this.jdbcTemplete = new JdbcTemplate(datasource);
}
public void delete(int personId) {
this.jdbcTemplete
.update("delete from person where id=?",
new Object[] { personId },
new int[] { java.sql.Types.INTEGER });
}
public Person getPerson(int personId) {
return (Person) this.jdbcTemplete.queryForObject(
"select * from person where id=?", new Object[] { personId },
new int[] { java.sql.Types.INTEGER }, new PersonRowMapper());
}
@SuppressWarnings("unchecked")
public List<Person> getPersons() {
return (List<Person>) this.jdbcTemplete.query("select * from person",
new PersonRowMapper());
}
public void save(Person person) {
System.out.println(person.getName());
this.jdbcTemplete.update("insert into person(name) values(?)",
new Object[] { person.getName() },
new int[] { java.sql.Types.VARCHAR });
}
public void update(Person person) {
this.jdbcTemplete.update("update person set name=? where id=?",
new Object[] { person.getName(), person.getId() }, new int[] {
java.sql.Types.VARCHAR, java.sql.Types.INTEGER });
}
}
package cn.itcast.bean;
public class Person {
private int id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package cn.itcast.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import cn.itcast.bean.Person;
public class PersonRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int index) throws SQLException {
cn.itcast.bean.Person person=new Person(rs.getString("name"));
person.setId(rs.getInt("id"));
return person;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<!-- 連接池啟動時的初始值 -->
<property name="initialSize" value="1"/>
<!-- 連接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空閑值.當經過一個高峰時間后,連接池可以慢慢將已經用不到的連接慢慢釋放一部分,一直減少到maxIdle為止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空閑值.當空閑的連接數少于閥值時,連接池就會預申請去一些連接,以免洪峰來時來不及申請 -->
<property name="minIdle" value="1"/>
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="personServiceImpl"
class="cn.itcast.service.impl.PersonServiceImpl">
<property name="datasource" ref="dataSource" />
</bean>
</beans>
package junit.test;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.bean.Person;
import cn.itcast.service.IPersonService;
public class TestSpringAndJdbc {
public static IPersonService iPersonService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
iPersonService=(IPersonService)ctx.getBean("personServiceImpl");
}
@Test
public void TestSave(){
for(int i=1;i<5;i++){
iPersonService.save(new Person("傳智博客"+i));
}
}
@Test
public void TestFindPerson(){
iPersonService.getPerson(1);
System.out.println(iPersonService.getPerson(1).getName());
}
@Test
public void TestUpdate(){
Person person=iPersonService.getPerson(1);//通過id取得person對象
person.setName("張三");//設置名字
iPersonService.update(person);//更新
}
@Test
public void TestDelete(){
Person person=iPersonService.getPerson(2);
iPersonService.delete(person.getId());
}
@Test
public void testFindAllPeron(){
List<Person> list=iPersonService.getPersons();
for(Person person:list){
System.out.println(person.getId()+" "+person.getName());
}
}
}
@Aspect
public class LogPrint {
@Pointcut("execution(* cn.itcast.service..*.*(..))")
private void anyMethod() {}//聲明一個切入點
@Before("anyMethod() && args(userName)")//定義前置通知
public void doAccessCheck(String userName) {
}
@AfterReturning(pointcut="anyMethod()",returning="revalue")//定義后置通知
public void doReturnCheck(String revalue) {
}
@AfterThrowing(pointcut="anyMethod()", throwing="ex")//定義例外通知
public void doExceptionAction(Exception ex) {
}
@After("anyMethod()")//定義最終通知
public void doReleaseAction() {
}
@Around("anyMethod()")//環繞通知
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();
}
}
基于基于XML配置方式聲明切面
public class LogPrint {
public void doAccessCheck() {}定義前置通知
public void doReturnCheck() {}定義后置通知
public void doExceptionAction() {}定義例外通知
public void doReleaseAction() {}定義最終通知
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();環繞通知
}
}
<bean id="orderservice" class="cn.itcast.service.OrderServiceBean"/>
<bean id="log" class="cn.itcast.service.LogPrint"/>
<aop:config>
<aop:aspect id="myaop" ref="log">
<aop:pointcut id="mycut" expression="execution(* cn.itcast.service..*.*(..))"/>
<aop:before pointcut-ref="mycut" method="doAccessCheck"/>
<aop:after-returning pointcut-ref="mycut" method="doReturnCheck "/>
<aop:after-throwing pointcut-ref="mycut" method="doExceptionAction"/>
<aop:after pointcut-ref="mycut" method=“doReleaseAction"/>
<aop:around pointcut-ref="mycut" method="doBasicProfiling"/>
</aop:aspect>
</aop:config>
組成 Spring 框架的每個模塊(或組件)都可以單獨存在,或者與其他一個或多個模塊聯合實現。每個模塊的功能如下:
BeanFactory
,它是工廠模式的實現。BeanFactory
使用控制反轉 (IOC) 模式將應用程序的配置和依賴性規范與實際的應用程序代碼分開。
Spring 框架的功能可以用在任何 J2EE 服務器中,大多數功能也適用于不受管理的環境。Spring 的核心要點是:支持不綁定到特定 J2EE 服務的可重用業務和數據訪問對象。毫無疑問,這樣的對象可以在不同 J2EE 環境 (Web 或 EJB)、獨立應用程序、測試環境之間重用。
public interface IPersonService {
public abstract void Save();
public Set<String> getSets() ;
public List<String> getLists() ;
public Properties getProperties() ;
public Map<String, String> getMaps() ;
}
public class PersonServiceBean implements IPersonService {
private IPersonDao iPersonDao;
private Set<String> sets=new HashSet<String>();
private List<String> lists=new ArrayList<String>();
private Properties properties=new Properties();
private Map<String,String> maps=new HashMap<String,String>();
public PersonServiceBean(IPersonDao personDao, String name) {
iPersonDao = personDao;
this.name = name;
}
public void Save(){
System.out.println(name);//輸出name
iPersonDao.add();
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getMaps() {
return maps;
}
public void setMaps(Map<String, String> maps) {
this.maps = maps;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public Set<String> getSets() {
return sets;
}
public void setSets(Set<String> sets) {
this.sets = sets;
}
public IPersonDao getIPersonDao() {
return iPersonDao;
}
public void setIPersonDao(IPersonDao personDao) {
iPersonDao = personDao;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
}
測試類:
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
// ItcastClassPathXMLApplicationContext ctx=new
// ItcastClassPathXMLApplicationContext("beans.xml");
//
IPersonService ipersonService = (IPersonService) ctx
.getBean("personService");
//集合對象的遍歷
System.out.println("===========set==================");
for (String value : ipersonService.getSets()) {
System.out.println(value);
}
// ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
System.out.println("===========List=================");
for(String value:ipersonService.getLists()){
System.out.println(value);
}
System.out.println("=========properties===============");
for(Object value:ipersonService.getProperties().keySet()){
System.out.println(value);
}
System.out.println("================maps==================");
for(Object value:ipersonService.getMaps().keySet()){
System.out.println(value);
}
//調用PersonServiceBean的sava方法,輸出結果
ipersonService.Save();
}
}
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="personService"
class="cn.itcast.service.impl.PersonServiceBean">
<property name="IPersonDao" ref="personDaoBean"></property>
<constructor-arg index="0" ref="personDaoBean"
type="cn.itcast.dao.IPersonDao" />
<constructor-arg index="1" type="java.lang.String"
value="傳智博客">
</constructor-arg>
<property name="sets">
<set>
<value>set1</value>
<value>set2</value>
<value>set3</value>
</set>
</property>
<property name="lists">
<list>
<value>list1</value>
<value>list2</value>
<value>list3</value>
</list>
</property>
<property name="properties">
<props>
<prop key="properties1">property1</prop>
<prop key="properties2">property2</prop>
<prop key="properties3">property3</prop>
</props>
</property>
<property name="maps">
<map>
<entry key="key1" value="keyFirst"></entry>
<entry key="key2" value="keySecond"></entry>
<entry key="key3" value="keyThird"></entry>
</map>
</property>
</bean>
<bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
<!--
<bean id="anotherPersonServiceBean"
class="cn.itcast.service.impl.AnotherPersonServiceBean" >
</bean>
-->
</beans>
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("這是personDaoBean的Add()方法");
}
}
/**
* 實現的spring容器
*
* @author Administrator
*
*/
public class ItcastClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public ItcastClassPathXMLApplicationContext() {
}
public ItcastClassPathXMLApplicationContext(String filename) {
// System.out.println("構造方法 ");
this.readXml(filename);// 調用 讀取配置文件 的方法
this.instanceBeans();// 調用bean的實例化
this.injectObject();// 注入對象
}
/**
* 為bean對象的屬性注入值
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 取得屬性描述 ,是一個數組
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
bean.getClass()).getPropertyDescriptors();
for (PropertyDefinition propertyDefinition : beanDefinition
.getPropertys()) {// 取所有屬性
for (PropertyDescriptor properdesc : ps) {
if (propertyDefinition.getName().equals(
properdesc.getName())) {
Method setter = properdesc.getWriteMethod();// 獲取屬性的setter方法.
// private
if (setter != null) {
Object value=null;
if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
value = sigletons
.get(propertyDefinition
.getRef());
}else{
//將配置文件里字符串類型轉換為屬性類型的值
value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
}
setter.setAccessible(true);// 設置為可訪問
setter.invoke(bean, value);// 把引用對象注入到屬性
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 完成bean的實例化
*/
private void instanceBeans() {
// System.out.println("bean實例化方法被調用");
// 利用反射機制把bean實例化
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 判斷BeanDefinition的實例獲得的類名不為null和空串
if (beanDefinition.getClassName() != null
&& !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 讀取配置文件信息
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("讀取xml文件的方法被調用了");
SAXReader saxReader = new SAXReader();// 創建讀取器
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//取得當前xml文件在本地的位置
document = saxReader.read(xmlpath);// 讀取路徑
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空間
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 創建beans/bean查詢路徑
xsub.setNamespaceURIs(nsMap);// 設置命名空間
List<Element> beans = xsub.selectNodes(document);// 獲取文檔下所有bean節點
for (Element element : beans) {
String id = element.attributeValue("id");// 獲取id屬性值
String clazz = element.attributeValue("class");// 獲取class屬性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
XPath propertysub = element.createXPath("ns:property");// 船艦查詢路徑
propertysub.setNamespaceURIs(nsMap);// 設置命名空間
List<Element> propertys = propertysub.selectNodes(element);// 查找節點
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 取得property的name值
String propertyref = property.attributeValue("ref");// 取得property的ref值
String propertyValue = property.attributeValue("value");// 取得property的value值
PropertyDefinition propertyDefinition = new PropertyDefinition(
propertyName, propertyref,propertyValue);
beanDefine.getPropertys().add(propertyDefinition);// 將屬性對象加入到bean中
}
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取bean 實例
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
// "beans.xml");
ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
//
IPersonService ipersonService = (IPersonService)ctx
.getBean("personService");
ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
}
}
public class PropertyDefinition {
private String name;
private String ref;
private String value;
public PropertyDefinition(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value=value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
其他略。
out:
Itcast
15
這是personDaoBean的Add()方法
/**
* 實現的spring容器
*
* @author Administrator
*
*/
public class ItcastClassPathXMLApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String, Object> sigletons = new HashMap<String, Object>();
public ItcastClassPathXMLApplicationContext() {
}
public ItcastClassPathXMLApplicationContext(String filename) {
// System.out.println("構造方法 ");
this.readXml(filename);// 調用 讀取配置文件 的方法
this.instanceBeans();// 調用bean的實例化
this.injectObject();// 注入對象
}
/**
* 為bean對象的屬性注入值
*/
private void injectObject() {
for (BeanDefinition beanDefinition : beanDefines) {
Object bean = sigletons.get(beanDefinition.getId());
if (bean != null) {
// 取得屬性描述 ,是一個數組
try {
PropertyDescriptor[] ps = Introspector.getBeanInfo(
bean.getClass()).getPropertyDescriptors();
for (PropertyDefinition propertyDefinition : beanDefinition
.getPropertys()) {// 取所有屬性
for (PropertyDescriptor properdesc : ps) {
if (propertyDefinition.getName().equals(
properdesc.getName())) {
Method setter = properdesc.getWriteMethod();// 獲取屬性的setter方法.
// private
if (setter != null) {
Object value = sigletons
.get(propertyDefinition.getRef());
setter.setAccessible(true);// 設置為可訪問
setter.invoke(bean, value);// 把引用對象注入到屬性
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 完成bean的實例化
*/
private void instanceBeans() {
// System.out.println("bean實例化方法被調用");
// 利用反射機制把bean實例化
for (BeanDefinition beanDefinition : beanDefines) {
try {
// 判斷BeanDefinition的實例獲得的類名不為null和空串
if (beanDefinition.getClassName() != null
&& !"".equals(beanDefinition.getClassName().trim()))
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 讀取配置文件信息
*
* @param filename
*/
private void readXml(String filename) {
// System.out.println("讀取xml文件的方法被調用了");
SAXReader saxReader = new SAXReader();// 創建讀取器
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);//取得當前xml文件在本地的位置
document = saxReader.read(xmlpath);// 讀取路徑
System.out.println(document);
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空間
XPath xsub = document.createXPath("http://ns:beans/ns:bean");// 創建beans/bean查詢路徑
xsub.setNamespaceURIs(nsMap);// 設置命名空間
List<Element> beans = xsub.selectNodes(document);// 獲取文檔下所有bean節點
System.out.println(beans.size());
for (Element element : beans) {
String id = element.attributeValue("id");// 獲取id屬性值
String clazz = element.attributeValue("class");// 獲取class屬性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
System.out.println("id=" + id);
System.out.println("clazz=" + clazz);
XPath propertysub = element.createXPath("ns:property");// 船艦查詢路徑
propertysub.setNamespaceURIs(nsMap);// 設置命名空間
List<Element> propertys = propertysub.selectNodes(element);// 查找節點
for (Element property : propertys) {
String propertyName = property.attributeValue("name");// 取得property的name值
String propertyref = property.attributeValue("ref");// 取得property的ref值
System.out.println(propertyName + "= " + propertyref);
PropertyDefinition propertyDefinition = new PropertyDefinition(
propertyName, propertyref);
beanDefine.getPropertys().add(propertyDefinition);// 將屬性對象加入到bean中
}
beanDefines.add(beanDefine);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取bean 實例
*
* @param beanName
* @return
*/
public Object getBean(String beanName) {
return this.sigletons.get(beanName);
}
}
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
>
<bean id="personService"
class="cn.itcast.service.impl.PersonServiceBean">
<property name="IPersonDao" ref="personDaoBean"></property>
</bean>
<bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>
</beans>
package junit.test;
public class PropertyDefinition {
private String name;
private String ref;
public PropertyDefinition(String name, String ref) {
this.name = name;
this.ref = ref;
}
getter&setter method
}
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import cn.itcast.service.IPersonService;
import cn.itcast.service.impl.PersonServiceBean;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
// "beans.xml");
ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
IPersonService ipersonService = (IPersonService)ctx
.getBean("personService");//調用自定義容器的getBean方法
ipersonService.Save();
// ctx.close();
// ctx.registerShutdownHook();
}
}
package junit.test;
import java.util.ArrayList;
import java.util.List;
public class BeanDefinition {
private String id;
private String className;
private List<PropertyDefinition> propertys=new ArrayList<PropertyDefinition>();
生成getter,setter方法
}
package cn.itcast.dao.impl;
import cn.itcast.dao.IPersonDao;
public class PersonDaoBean implements IPersonDao {
public void add(){
System.out.println("這是personDaoBean的Add()方法");
}
}
package cn.itcast.service;
public interface IPersonService {
public abstract void Save();
}
package cn.itcast.service.impl;
import cn.itcast.dao.IPersonDao;
import cn.itcast.service.IPersonService;
/**
* 業務bean
* @author Administrator
*
*/
public class PersonServiceBean implements IPersonService {
private IPersonDao iPersonDao;
public IPersonDao getIPersonDao() {
return iPersonDao;
}
public void setIPersonDao(IPersonDao personDao) {
iPersonDao = personDao;
}
public void Save(){
iPersonDao.add();
}
}