在spring中有三中實例化bean的方式:
一、使用構造器實例化;
二、使用靜態工廠方法實例化;
三、使用實例化工廠方法實例化。
每種實例化所采用的配置是不一樣的:
一、使用構造器實例化;
這種實例化的方式可能在我們平時的開發中用到的是最多的,因為在xml文件中配置簡單并且也不需要額外的工廠類來實現。
采用這種實例化方式要注意的是:要實例化的類中如果有構造器的話,一定要有一個無參的構造器。
二、使用靜態工廠方法實例化;
根據這個中實例化方法的名稱就可以知道要想通過這種方式進行實例化就要具備兩個條件:(一)、要有工廠類及其工廠方法;(二)、工廠方法是靜態的。OK,知道這兩點就好辦了,首先創建工程類及其靜態方法:
id是實例化的對象的名稱,class是工廠類,也就實現實例化類的靜態方法所屬的類,factory-method是實現實例化類的靜態方法。
然后按照正常的調用方法去調用即可:
三、使用實例化工廠方法實例化。
這個方法和上面的方法不同之處在與使用該實例化方式工廠方法不需要是靜態的,但是在spring的配置文件中需要配置更多的內容,,首先創建工廠類及工廠方法:
這里需要配置兩個bean,第一個bean使用的構造器方法實例化工廠類,第二個bean中的id是實例化對象的名稱,factory-bean對應的被實例化的工廠類的對象名稱,也就是第一個bean的id,factory-method是非靜態工廠方法。
然后按照正常的調用方法去調用即可:
面向切面編程(AOP)通過提供另外一種思考程序結構的途經來彌補面向對象編程(OOP)的不足。在OOP中模塊化的關鍵單元是類(classes),而在AOP中模塊化的單元則是切面。切面能對關注點進行模塊化,例如橫切多個類型和對象的事務管理。(在AOP術語中通常稱作橫切(crosscutting)關注點。)
AOP框架是Spring的一個重要組成部分。但是Spring IoC容器并不依賴于AOP,這意味著你有權利選擇是否使用AOP,AOP做為Spring IoC容器的一個補充,使它成為一個強大的中間件解決方案。
AOP在Spring Framework中的作用
提供聲明式企業服務,特別是為了替代EJB聲明式服務。最重要的服務是聲明性事務管理。
允許用戶實現自定義切面,用AOP來完善OOP的使用。
目前AOP主要有:Spring AOP ,JBOSS AOP ,AspectJ AOP
AOP與OOP:可以理解為OOP是縱向的采用繼承樹形式的。而AOP是橫向的
Spring AOP:
AspectJ AOP:
在這種情況下,你也許會考慮使用AspectJ,其支持編譯期織入且不需要生成代理。
面向切面編程,把散落在程序中的公共部分提取出來,做成切面類,這樣的好處在于,代碼的可重用,一旦涉及到該功能的需求發生變化,只要修改該代碼就行,否則,你要到處修改,如果只要修改1、2處那還可以接受,萬一有1000處呢。
AOP底層的東西就是JDK動態代理和CGLIB代理,說白了就是增強類的功能。
最常用的AOP應用在數據庫連接以及事務處理上。
AOP:面向切面編程。(Aspect-Oriented Programming)
AOP可以說是對OOP的補充和完善。OOP引入封裝、繼承和多態性等概念來建立一種對象層次結構,用以模擬公共行為的一個集合。當我們需要為分散的對象引入公共行為的時候,OOP則顯得無能為力。也就是說,OOP允許你定義從上到下的關系,但并不適合定義從左到右的關系。例如日志功能。日志代碼往往水平地散布在所有對象層次中,而與它所散布到的對象的核心功能毫無關系。在OOP設計中,它導致了大量代碼的重復,而不利于各個模塊的重用。
將程序中的交叉業務邏輯(比如安全,日志,事務等),封裝成一個切面,然后注入到目標對象(具體業務邏輯)中去。
實現AOP的技術,主要分為兩大類:一是采用動態代理技術,利用截取消息的方式,對該消息進行裝飾,以取代原有對象行為的執行;二是采用靜態織入的方式,引入特定的語法創建“方面”,從而使得編譯器可以在編譯期間織入有關“方面”的代碼.
AOP(Aspect Orient Programming),作為面向對象編程的一種補充,廣泛應用于處理一些具有橫切性質的系統級服務,如事務管理、安全檢查、緩存、對象池管理等。 AOP 實現的關鍵就在于 AOP 框架自動創建的 AOP 代理,AOP 代理則可分為靜態代理和動態代理兩大類,其中靜態代理是指使用 AOP 框架提供的命令進行編譯,從而在編譯階段就可生成 AOP 代理類,因此也稱為編譯時增強;而動態代理則在運行時借助于 JDK 動態代理、CGLIB 等在內存中"臨時"生成 AOP 動態代理類,因此也被稱為運行時增強。
使用IoC,對象是被動的接受依賴類,而不是自己主動的去找。容器在實例化的時候主動將它的依賴類注入給它。可以這樣理解:控制反轉將類的主動權轉移到接口上,依賴注入通過xml配置文件在類實例化時將其依賴類注入。
控制反轉即IoC (Inversion of Control),它把傳統上由程序代碼直接操控的對象的調用權交給容器,通過容器來實現對象組件的裝配和管理。所謂的“控制反轉”概念就是對組件對象控制權的轉移,從程序代碼本身轉移到了外部容器。
依賴注入(Dependency Injection)和控制反轉(Inversion of Control)是同一個概念。具體含義是:當某個角色(可能是一個Java實例,調用者)需要另一個角色(另一個Java實例,被調用者)的協助時,在傳統的程序設計過程中,通常由調用者來創建被調用者的實例。但在Spring里,創建被調用者的工作不再由調用者來完成,因此稱為控制反轉;創建被調用者實例的工作通常由Spring容器來完成,然后注入調用者,因此也稱為依賴注入。
IoC核心理念:
1.在類當中不創建對象,在代碼中不直接與對象和服務連接
2.在配置文件中描述創建對象的方式,以及各個組件之間的聯系
3.外部容器通過解析配置文件,通過反射來將這些聯系在一起
The Hollywood principle:Don’t call us,we’ll call you.
即,所有組件都是被動的、不主動聯系(調用)外部代碼,
要等著外部代碼的調用--------所有的組件的初始化和相互調用都由容器負責實現。
簡單的說,就是整個程序之間的關系,都由容器來控制:將程序的控制權反轉給容器,就是所謂的外轉
而在我們傳統代碼中,由程序代碼直接控制
IOC的意思是控件反轉也就是由容器控制程序之間的關系,把控件權交給了外部容器,之前的寫法,由程序代碼直接操控,而現在控制權由應用代碼中轉到了外部容器,控制權的轉移是所謂反轉。
ApplicationContext包括BeanFactory的全部功能,因此建議優先使用ApplicationContext。除非對于某些內存非常關鍵的應用,才考慮使用 BeanFactory。
spring為ApplicationContext提供的3種實現分別為:
1、 ClassPathXmlApplicationContext:利用類路徑的XML文件來載入Bean定義的信息
[1] ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
[2] String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new ClassPathXmlApplication(locations);
2、 FileSystemXmlApplicationContext:利用文件系統中的XMl文件來載入Bean
定義的信息
[1] ApplicationContext ctx = new FileSystemXmlApplicationContext("bean.xml"); //加載單個配置文件
[2] String[] locations = {"bean1.xml", "bean2.xml", "bean3.xml"};
ApplicationContext ctx = new FileSystemXmlApplicationContext(locations );
//加載多個配置文件
[3] ApplicationContext ctx =new FileSystemXmlApplicationContext("D:/project/bean.xml");
//根據具體路徑加載
3、 XmlWebApplicationContext:從Web系統中的XML文件來載入Bean定義的信息。
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
配置WebApplicationContext的兩種方法:
(1) 利用Listener接口來實現
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext</param-value>
</context-param>
(2) 利用Servlet接口來實現
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext</param-value>
</context-param>
<Servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
</servlet>
1. 實例化;
2. 設置屬性值;
3. 如果實現了BeanNameAware接口,調用setBeanName設置Bean的ID或者Name;
4. 如果實現BeanFactoryAware接口,調用setBeanFactory 設置BeanFactory;
5. 如果實現ApplicationContextAware,調用setApplicationContext設置ApplicationContext
6. 調用BeanPostProcessor的預先初始化方法;
7. 調用InitializingBean的afterPropertiesSet()方法;
8. 調用定制init-method方法;
9. 調用BeanPostProcessor的后初始化方法;
1. 調用DisposableBean的destroy();
2. 調用定制的destroy-method方法;
二,多個Bean的先后順序
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:context=" xmlns:mvc="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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util <!-- 指定系統尋找controller路徑 -->
<!-- json 數據格式轉換
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="jsonConverter" class="com.abin.lee.ssh.util.json.fastjson.FastjsonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="serializerFeature">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
-->
<!-- 搜索的包路徑 -->
<context:component-scan base-package="com.abin.lee.ssh"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- jsp視圖解釋器 -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
package com.abin.lee.ssh.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.abin.lee.ssh.entity.UniversalBean;
@Scope("prototype")
@Controller
@RequestMapping("/sky/")
public class UniversalController {
@RequestMapping("/activity")
public String activity(ModelMap map){
List<UniversalBean> list=new ArrayList<UniversalBean>();
UniversalBean bean=null;
for(int i=0;i<=5;i++){
bean=new UniversalBean();
bean.setId(i);
bean.setName("abin"+i);
bean.setImageUrl("http://localhost:7700/front/"+i+".jpg");
list.add(bean);
}
map.put("list", list);
return "mobile/show";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%@ taglib prefix="c" uri="<%@ taglib uri="</head>
<script language="javascript" type="text/javascript" src="../script/js/share.js" ></script>
<script type="text/javascript">
</script>
<body>
<div id="content">
<c:forEach items="${list}" var="obj">
<div id="" class="lb">
<c:choose>
<c:when test="${empty obj.name}">
I am Empty
</c:when>
<c:when test="${obj.name=='abin1'}">
${obj.name} is a boy
</c:when>
<c:otherwise>
${obj.name } is normally
</c:otherwise>
</c:choose>
<img alt="顯示不出來" src="${obj.imageUrl }"></img>
</div>
</c:forEach>
</div>
</body>
</html>
Spring AOP使用了兩種代理機制,一種是基于JDK的動態代理,另一種是基于CGLib的動態代理,之所以需要兩種代理機制,很大程度上是因為JDK本身只提供基于接口的代理,不支持類的代理。
什么是AOP?
面向切面編程(AOP)完善spring的依賴注入(DI),面向切面編程在spring中主要表現為兩個方面
1.面向切面編程提供聲明式事務管理
2.spring支持用戶自定義的切面
面向切面編程(aop)是對面向對象編程(oop)的補充,
面向對象編程將程序分解成各個層次的對象,面向切面編程將程序運行過程分解成各個切面。
AOP從程序運行角度考慮程序的結構,提取業務處理過程的切面,oop是靜態的抽象,aop是動態的抽象,
是對應用執行過程中的步驟進行抽象,,從而獲得步驟之間的邏輯劃分。
aop框架具有的兩個特征:
1.各個步驟之間的良好隔離性
2.源代碼無關性
什么是DI機制?
依賴注入(Dependecy Injection)和控制反轉(Inversion of Control)是同一個概念,具體的講:當某個角色
需要另外一個角色協助的時候,在傳統的程序設計過程中,通常由調用者來創建被調用者的實例。但在spring中
創建被調用者的工作不再由調用者來完成,因此稱為控制反轉。創建被調用者的工作由spring來完成,然后注入調用者
因此也稱為依賴注入。
spring以動態靈活的方式來管理對象 , 注入的兩種方式,設置注入和構造注入。
設置注入的優點:直觀,自然
構造注入的優點:可以在構造器中決定依賴關系的順序。
spring 的優點都有哪些?
1.降低了組件之間的耦合性 ,實現了軟件各層之間的解耦
2.可以使用容易提供的眾多服務,如事務管理,消息服務等
3.容器提供單例模式支持
4.容器提供了AOP技術,利用它很容易實現如權限攔截,運行期監控等功能
5.容器提供了眾多的輔助類,能加快應用的開發
6.spring對于主流的應用框架提供了集成支持,如hibernate,JPA,Struts等
7.spring屬于低侵入式設計,代碼的污染極低
8.獨立于各種應用服務器
9.spring的DI機制降低了業務對象替換的復雜性
10.Spring的高度開放性,并不強制應用完全依賴于Spring,開發者可以自由選擇spring的部分或全部
一、spring工作原理:
1.spring mvc請所有的請求都提交給DispatcherServlet,它會委托應用系統的其他模塊負責負責對請求進行真正的處理工作。
2.DispatcherServlet查詢一個或多個HandlerMapping,找到處理請求的Controller.
3.DispatcherServlet請請求提交到目標Controller
4.Controller進行業務邏輯處理后,會返回一個ModelAndView
5.Dispathcher查詢一個或多個ViewResolver視圖解析器,找到ModelAndView對象指定的視圖對象
6.視圖對象負責渲染返回給客戶端。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=" xmlns="http://java.sun.com/xml/ns/javaee id="WebApp_ID" version="3.0">
<display-name>universal</display-name>
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:com/abin/lee/ssh/spring-service.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring MVC -->
<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*:com/abin/lee/ssh/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/mvc/*</url-pattern>
</servlet-mapping>
<!-- spring encoding -->
<filter>
<filter-name>utf8-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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>utf8-encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:context=" xmlns:mvc="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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util <!-- 指定系統尋找controller路徑 -->
<mvc:annotation-driven>
<!-- json 數據格式轉換-->
<mvc:message-converters>
<bean class="com.abin.lee.ssh.function.FastJsonAbstractHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="serializerFeature">
<list>
<value>WriteMapNullValue</value>
<value>QuoteFieldNames</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 搜索的包路徑 -->
<context:component-scan base-package="com.abin.lee.ssh"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>
package com.abin.lee.ssh.function;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.FileCopyUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
//來對requestbody 或responsebody中的數據進行解析
public class FastJsonAbstractHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
// fastjson特性參數
private SerializerFeature[] serializerFeature;
public SerializerFeature[] getSerializerFeature() {
return serializerFeature;
}
public void setSerializerFeature(SerializerFeature[] serializerFeature) {
this.serializerFeature = serializerFeature;
}
//限定頁面文本傳送類型 只有數據是改類型 的 才會進行攔截
//application/json
public FastJsonAbstractHttpMessageConverter(){
// super(new MediaType("text","plain"));
super(new MediaType("application","json"));
}
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputmessage) throws IOException,
HttpMessageNotReadableException {
Charset charset;
MediaType mediaType=inputmessage.getHeaders().getContentType();
if(mediaType!=null&&mediaType.getCharSet()!=null){
charset=mediaType.getCharSet();
}else{
charset=Charset.forName("UTF-8");
}
String input=FileCopyUtils.copyToString(new InputStreamReader(inputmessage.getBody(),charset));
String result=URLDecoder.decode(input, "UTF-8");
System.out.println(result);
/*OrgnizationPO po=new OrgnizationPO();
po.setId(1);
po.setName("11");
po.setOrgdesc("1");*/
/*ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputmessage.getBody().read()) != -1) {
baos.write(i);
} */
return JSON.parseObject(result, clazz);
// return JSON.parseArray(baos.toString(), clazz);
// return po;
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
//throw new UnsupportedOperationException();
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
String jsonString = JSON.toJSONString(o, serializerFeature);
// System.out.println(jsonString);
OutputStream out = outputMessage.getBody();
out.write(jsonString.getBytes(DEFAULT_CHARSET));
out.flush();
}
}
package com.abin.lee.ssh.hibernate;
import com.abin.lee.ssh.entity.ModeBean;
public interface ModeDao {
public boolean insert(ModeBean mode);
}
package com.abin.lee.ssh.hibernate.impl;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.hibernate.ModeDao;
@Repository
public class ModeDaoImpl extends HibernateDaoSupport implements ModeDao{
@Resource(name = "sessionFactory")
public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
public boolean insert(ModeBean mode) {
boolean flag=false;
try {
this.getHibernateTemplate().saveOrUpdate(mode);
flag=true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
package com.abin.lee.ssh.spring;
import com.abin.lee.ssh.entity.ModeBean;
public interface ModeService {
public boolean insert(ModeBean mode);
}
package com.abin.lee.ssh.spring.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.hibernate.ModeDao;
import com.abin.lee.ssh.spring.ModeService;
@Service
@Transactional(readOnly = true, timeout = 2, propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class ModeServiceImpl implements ModeService {
@Resource
private ModeDao modeDao;
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public boolean insert(ModeBean mode) {
boolean flag = false;
try {
flag = this.modeDao.insert(mode);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
package com.abin.lee.ssh.springmvc;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abin.lee.ssh.dto.request.ModeRequest;
import com.abin.lee.ssh.dto.response.ModeResponse;
import com.abin.lee.ssh.entity.ModeBean;
import com.abin.lee.ssh.spring.ModeService;
@Controller
@RequestMapping("/stevenjohn/")
public class ModeController {
@Resource
private ModeService modeService;
@RequestMapping(value = "getMode", method = RequestMethod.POST)
public @ResponseBody
ModeResponse getMode(
@ModelAttribute ModeRequest modeRequest) {
ModeResponse response = new ModeResponse();
String id=modeRequest.getId();
String username=modeRequest.getUsername();
String password=modeRequest.getPassword();
int age=modeRequest.getAge();
String address=modeRequest.getAddress();
String email=modeRequest.getEmail();
ModeBean mode=new ModeBean(id, username, password, age, address, email);
boolean flag=modeService.insert(mode);
System.out.println("flag="+flag);
if(flag==true){
response.setStatus("success");
}else{
response.setStatus("failure");
}
return response;
}
}
package com.abin.lee.ssh.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="MODEBEAN")
public class ModeBean implements Serializable{
@Id
@Column(name="ID")
private String id;
@Column(name="USERNAME",length=100,nullable=true)
private String username;
@Column(name="PASSWORD",length=100,nullable=true)
private String password;
@Column(name="AGE",length=10,nullable=true)
private int age;
@Column(name="ADDRESS",length=100,nullable=true)
private String address;
@Column(name="EMAIL",length=100,nullable=true)
private String email;
public ModeBean() {
}
public ModeBean(String id, String username, String password, int age,
String address, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.address = address;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.abin.lee.ssh.dto.request;
import java.io.Serializable;
public class ModeRequest implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1886596479119297989L;
private String id;
private String username;
private String password;
private int age;
private String address;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.abin.lee.ssh.dto.response;
import java.io.Serializable;
public class ModeResponse implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7725619232731203410L;
private String status;
private String message;
public ModeResponse() {
}
public ModeResponse(String status, String message) {
super();
this.status = status;
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
log4j.rootCategory=info,log,console
log4j.logger.org.apache.axis2.enterprise=FATAL
log4j.logger.de.hunsicker.jalopy.io=FATAL
log4j.logger.httpclient.wire.header=FATAL
log4j.logger.org.apache.commons.httpclient=FATAL
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
log4j.appender.log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File=../logs/mms.log
log4j.appender.log.layout=org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern=%d [%t] %-5p %c %x - %m%n
package com.abin.lee.ssm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.junit.Test;
public class HttpsClient extends TestCase {
private String httpUrl = "http://localhost:7000/universal/mvc/stevenjohn/getMode";
@Test
public void testHttpsClient() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(httpUrl);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("id", UUID.randomUUID().toString()));
nvps.add(new BasicNameValuePair("username", "abin"));
nvps.add(new BasicNameValuePair("password", "abing"));
nvps.add(new BasicNameValuePair("age", "28"));
nvps.add(new BasicNameValuePair("address", "beijing of china"));
nvps.add(new BasicNameValuePair("email", "varyall@tom.com"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
BufferedReader buffer = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
StringBuffer stb=new StringBuffer();
String line=null;
while((line=buffer.readLine())!=null){
stb.append(line);
}
buffer.close();
String result=stb.toString();
System.out.println("result="+result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
首先,CXF和spring整合需要準備如下jar包文件:
這邊我是用Spring的jar包是Spring官方提供的,并沒有使用CXF中的Spring的jar文件。
添加這么多文件后,首先在web.xml中添加如下配置:
<!-- 加載Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 設置Spring容器加載配置文件路徑 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-server.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<servlet>
<servlet-name>CXFService</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFService</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
然后在src目錄中,新建一個applicationContext-server.xml文件,文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd"
注意上面的帶下劃線加粗部分,這個很重要的哦!不能寫錯或是遺漏了。
添加完這個文件后,還需要在這個文件中導入這么幾個文件。文件內容如下:
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
下面開始寫服務器端代碼,首先定制服務器端的接口,代碼如下:
package com.hoo.service;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import com.hoo.entity.User;
import com.hoo.entity.Users;
/**
* <b>function:</b>定制客戶端請求WebService所需要的接口
* @author hoojo
* @createDate 2011-3-18 上午08:22:55
* @file ComplexUserService.java
* @package com.hoo.service
* @project CXFWebService
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
@WebService
@SOAPBinding(style = Style.RPC)
public interface IComplexUserService {
public User getUserByName(@WebParam(name = "name") String name);
public void setUser(User user);
}
下面編寫WebService的實現類,服務器端實現代碼如下:
package com.hoo.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import com.hoo.entity.User;
import com.hoo.entity.Users;
/**
* <b>function:</b> WebService傳遞復雜對象,如JavaBean、Array、List、Map等
* @author hoojo
* @createDate 2011-3-18 上午08:22:55
* @file ComplexUserService.java
* @package com.hoo.service
* @project CXFWebService
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
@WebService
@SOAPBinding(style = Style.RPC)
@SuppressWarnings("deprecation")
public class ComplexUserService implements IComplexUserService {
public User getUserByName(@WebParam(name = "name") String name) {
User user = new User();
user.setId(new Date().getSeconds());
user.setName(name);
user.setAddress("china");
user.setEmail(name + "@hoo.com");
return user;
}
public void setUser(User user) {
System.out.println("############Server setUser###########");
System.out.println("setUser:" + user);
}
}
注意的是和Spring集成,這里一定要完成接口實現,如果沒有接口的話會有錯誤的。
下面要在applicationContext-server.xml文件中添加如下配置:
<bean id="userServiceBean" class="com.hoo.service.ComplexUserService"/>
<bean id="inMessageInterceptor" class="com.hoo.interceptor.MessageInterceptor">
<constructor-arg value="receive"/>
</bean>
<bean id="outLoggingInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
<!-- 注意下面的address,這里的address的名稱就是訪問的WebService的name -->
<jaxws:server id="userService" serviceClass="com.hoo.service.IComplexUserService" address="/Users">
<jaxws:serviceBean>
<!-- 要暴露的 bean 的引用 -->
<ref bean="userServiceBean"/>
</jaxws:serviceBean>
<jaxws:inInterceptors>
<ref bean="inMessageInterceptor"/>
</jaxws:inInterceptors>
<jaxws:outInterceptors>
<ref bean="outLoggingInterceptor"/>
</jaxws:outInterceptors>
</jaxws:server>
下面啟動tomcat服務器后,在WebBrowser中請求:
http://localhost:8080/CXFWebService/Users?wsdl
如果你能看到wsdl的xml文件的內容,就說明你成功了,注意的是上面地址的Users就是上面xml配置中的address的名稱,是一一對應的。
下面編寫客戶端請求的代碼,代碼如下:
package com.hoo.client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.hoo.entity.User;
import com.hoo.service.IComplexUserService;
/**
* <b>function:</b>請求Spring整合CXF的WebService客戶端
* @author hoojo
* @createDate 2011-3-28 下午03:20:35
* @file SpringUsersWsClient.java
* @package com.hoo.client
* @project CXFWebService
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class SpringUsersWsClient {
public static void main(String[] args) {
//調用WebService
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(IComplexUserService.class);
factory.setAddress("http://localhost:8080/CXFWebService/Users");
IComplexUserService service = (IComplexUserService) factory.create();
System.out.println("#############Client getUserByName##############");
User user = service.getUserByName("hoojo");
System.out.println(user);
user.setAddress("China-Guangzhou");
service.setUser(user);
}
}
運行后,可以在控制臺中看到
log4j:WARN No appenders could be found for logger (org.apache.cxf.bus.spring.BusApplicationContext). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 2011-3-28 18:12:26 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass 信息: Creating Service {http://service.hoo.com/}IComplexUserServiceService from class com.hoo.service.IComplexUserService #############Client getUserByName############## 27#hoojo#hoojo@hoo.com#china Tomcat控制臺![]()
這個server端是通過Spring整合配置的,下面我們將Client端也通過Spring配置完成整合。
首先增加applicationContext-client.xml配置文件,文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd"
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<jaxws:client id="userWsClient" serviceClass="com.hoo.service.IComplexUserService"
address="http://localhost:8080/CXFWebService/Users"/>
</beans>
客戶端請求代碼如下:
package com.hoo.client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hoo.entity.User;
import com.hoo.service.IComplexUserService;
/**
* <b>function:</b>請求Spring整合CXF的WebService客戶端
* @author hoojo
* @createDate 2011-3-28 下午03:20:35
* @file SpringUsersWsClient.java
* @package com.hoo.client
* @project CXFWebService
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@126.com
* @version 1.0
*/
public class SpringUsersWsClient {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-client.xml");
IComplexUserService service = ctx.getBean("userWsClient", IComplexUserService.class);
System.out.println("#############Client getUserByName##############");
User user = service.getUserByName("hoojo");
System.out.println(user);
user.setAddress("China-Guangzhou");
service.setUser(user);
}
}
運行后結果如下:
#############Client getUserByName############## 45#hoojo#hoojo@hoo.com#china ############Server setUser########### setUser:45#hoojo#hoojo@hoo.com#China-Guangzhou
作者:hoojo
出處:
import javax.jws.WebService;
/**
* @author abin
*
*/
@WebService(targetNamespace="cxf.lee.abin.com")
public interface IUserService {
public String getMessage(String message);
}
package com.abin.lee.cxf;
import javax.jws.WebService;
@WebService(endpointInterface="com.abin.lee.cxf.IUserService")
public class UserService implements IUserService{
public String getMessage(String message) {
return message+" welcome to beijing";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" xmlns:xsi=" xmlns:tx=" xmlns:jaxws=" xmlns:cxf=" xmlns:wsa=" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-beans-3.0.xsd
http://cxf.apache.org/core
http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<cxf:bus>
<cxf:features>
<!--日志攔截功能,用于監控soap內容,開發后可以刪除 -->
<cxf:logging/>
<wsa:addressing/>
</cxf:features>
</cxf:bus>
<bean id="userService" class="com.abin.lee.cxf.UserService"></bean>
<jaxws:endpoint id="userWebservice" implementor="#userService" address="/UserService" publish="true" />
</beans>
package com.abin.lee.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* 獲取spring容器,以訪問容器中定義的其他bean
*
* @author lyltiger
* @since MOSTsView 3.0 2009-11-16
*/
public class SpringContextUtil implements ApplicationContextAware {
// Spring應用上下文環境
private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"com/abin/lee/cxf/applicationContext-cxf.xml");
/**
* 實現ApplicationContextAware接口的回調方法,設置上下文環境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 獲取對象 這里重寫了bean方法,起主要作用
*
* @param name
* @return Object 一個以所給名字注冊的bean的實例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
package com.abin.lee.cxf.test;
import com.abin.lee.cxf.UserService;
import com.abin.lee.spring.SpringContextUtil;
import junit.framework.TestCase;
public class TestUserService extends TestCase{
public void testcxf(){
UserService userService=(UserService)SpringContextUtil.getBean("userService");
String response=userService.getMessage("abin");
System.out.println("response="+response);
System.exit(0);
}
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* 獲取spring容器,以訪問容器中定義的其他bean
*
* @author lyltiger
* @since MOSTsView 3.0 2009-11-16
*/
public class SpringContextUtil implements ApplicationContextAware {
// Spring應用上下文環境
private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"com/abin/lee/spring/applicationContext-queue.xml");
/**
* 實現ApplicationContextAware接口的回調方法,設置上下文環境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 獲取對象 這里重寫了bean方法,起主要作用
*
* @param name
* @return Object 一個以所給名字注冊的bean的實例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
package com.abin.lee.queue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class BeanFactoryUtil {
private static BeanFactory factory = new XmlBeanFactory(
new ClassPathResource(
"com/abin/lee/spring/applicationContext-queue.xml"));
public static BeanFactory getFactory() {
return factory;
}
public static void setFactory(BeanFactory factory) {
BeanFactoryUtil.factory = factory;
}
public static Object getBean(String name){
return factory.getBean(name);
}
}
package com.abin.lee.queue;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueueServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map map=request.getParameterMap();
String name1=(String)((Object[])map.get("name1"))[0];
String name2=(String)((Object[])map.get("name2"))[0];
MakeQueue makeQueue = (MakeQueue)BeanFactoryUtil.getBean("makeQueue");//bean的名稱
System.out.println(makeQueue.queueSize());
makeQueue.addQueue(name1);
makeQueue.addQueue(name2);
System.out.println(makeQueue.queueSize());
ServletOutputStream out=response.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));
writer.write("success");
writer.flush();
writer.close();
}
}