Solo  当前访客:3 登录 注册

喧哗博客-http://blog.xuahua.com

繁华过后的沉寂--技术经验分享
浏览次数: 95,037    文章总数: 91    评论总数: 3
标签:

最简单的RPC框架实现

1,接口定义

public interface EchoService{
    String echo(String ping);
}

 

2,接口实现

public Class EchoServiceImpl implements EchoService{

   @Override
   public String echo(String ping){
        return ping != null?ping + " -- > I am OK .":"I am Ok";
   }
}

 

3,RPC服务端服务发布者代码实现

public class RpcExporter{
   static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

   public static void exporter(String hostname,int port) throws Exception {
      ServerSocket server = new ServerSocket();
      server.bind(new InetSocketAddress(hostName,port));
      try{
         while(true){
           executor.execute(new ExporterTask(server.accept()));
         }
      }finally{
         server.close();
       }
   }
}


private static class ExporterTask implements Runnable{

   Socket client = null;
   public ExporterTask(Socket client){
     this.client = client;
   }
  @Override
  public ExporterTask(Socket client){
     this.client = client;
  }

  @Override
   public void run(){
     
			ObjectInputStream input = null;
			ObjectOutputStream output = null;
			
			try{
				input = new ObjectInputStream(client.getInputStream());
				String interfaceName = input.readUTF();
				Class<?> service = Class.forName(interfaceName);
				String methodName = input.readUTF();
				Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
				Object[] argments = (Object[]) input.readObject();
				Method method = service.getMethod(methodName, parameterTypes);
				Object result = method.invoke(service.newInstance(),argments);
				output = new ObjectOutputStream(client.getOutputStream());
				output.writeObject(result);
				
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(output !=null){
					try {
						output.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if(input !=null){
					try {
						input.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				if(client!=null){
					try {
						client.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		
  }
}

 

4,本地代理服务 RpcImporter

public class RpcImporter<S> {

	public S importer(final Class<?> serviceClass,final InetSocketAddress addr){
		return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class<?>[] {serviceClass.getInterfaces()[0]}, new InvocationHandler(){

			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				
				Socket socket = null;
				ObjectOutputStream output = null;
				ObjectInputStream input = null;
				try{
					socket = new Socket();
					socket.connect(addr);
					output = new ObjectOutputStream(socket.getOutputStream());
					output.writeUTF(serviceClass.getName());
					output.writeUTF(method.getName());
					output.writeObject(method.getParameterTypes());
					output.writeObject(args);
					input = new ObjectInputStream(socket.getInputStream());
					return input.readObject();
				}finally{
					if(socket != null){
						socket.close();
					}
					
					if(output != null){
						output.close();
					}
					
					if(input != null ){
						input.close();
					}
				}
			}
			
		});
	}
}

 

5, 测试代码 RpcTest

 

public class RpcTest {

	public static void main(String[] args) {
		new Thread(new Runnable(){

			@Override
			public void run() {
				try{
					RpcExporter.exporter("localhost",8080);
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					
				}
			}
			
		}).start();
		
		RpcImporter<EchoService> importer = new RpcImporter<EchoService>();
		EchoService echo = importer.importer(EchoServiceImpl.class,new InetSocketAddress("localhost",8080));
		System.out.println(echo.echo("Are you ok? "));
	}
}

 

运行结果.

Are you ok?  -- > I am Ok !

dubbox框架实例

1,dubbox-service端

 接口与实现一起在service端。使用maven单独打成独立的interface.jar即可。

包名规则如下:

   com.xuahua --根包

   ---------------interfaces --接口包

----------------service --接口实现包

-----------------model --接口使用类对外的Pojo

创建接口类名 com.xuahua.interfaces.DemoService.java

/**
* @author wyong
* 定义测试例子
*/
public interface DemoService {

/**
* @param name
* @return
* 定义方法,与某人打招呼
*/
String sayHello(String name); 


}

 

接口实现类com.xuahua.service.DemoServiceImpl.java

package com.xuahua.service;

import org.springframework.stereotype.Service;

import com.xuahua.interfaces.DemoService;

@Service("demoService")
public class DemoServiceImpl implements DemoService {

	public String sayHello(String name) {
		return "Hello " + name;  
	}


}

 

加载独立的spring_dubbox.xml文件,可以在spring-mvc.xml中最下面增加

<!-- **************************** 导入其他XML文件 **************************** -->
<import resource="spring_dubbo.xml"/>
<!-- **************************** /导入其他XML文件 **************************** -->

spring_dubbo.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:dubbo="http://code.alibabatech.com/schema/dubbo"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://code.alibabatech.com/schema/dubbo  
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">  
    <!-- 提供方应用信息,用于计算依赖关系 -->  
    <dubbo:application name="demoService_provider" owner="programmer" organization="dubbox" />  
    <dubbo:monitor protocol= "registry" />
    <!-- 使用zookeeper注册中心暴露服务地址  192.168.0.101 为zookeeper的ip地址及开放端口-->  
    <dubbo:registry protocol="zookeeper" address="192.168.0.101:2181"  />   
    
    <!-- 用dubbo协议在20880端口暴露服务 -->  
    <dubbo:protocol name="dubbo" port="20880" />  
   
    <!-- 声明需要暴露的服务接口 -->  
    <dubbo:service interface="com.xuahua.interfaces.DemoService" ref="demoService"  timeout="6000"/>  
      
    <!-- 具体的实现bean -->  
    <bean id="demoService" class="com.xuahua.service.DemoServiceImpl" />  
</beans>  

 

最后pom.xml文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.xuahua</groupId>
	<artifactId>dubbo-model-service</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>com.xuahua Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<!-- 定义本pom.xml引用版本属性, org.springframework-version,org.hibernate-version,project.build.sourceEncodeing 
		此名可随便取,必须与下面引用相匹配。 -->
	<properties>
		<org.springframework-version>4.0.0.RELEASE</org.springframework-version>
		<org.hibernate-version>4.3.1.Final</org.hibernate-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.parent.version>2.8.4</project.parent.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- 此处可以添加相关联的,使用的jar包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>${project.parent.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>spring</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.2</version>
</dependency>
		<!-- 下面是springframwork 4.xx 引用的包 -->
		<!-- spring 4 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- Apache Commons 基础组件 -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.8</version>
		</dependency>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.10</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>

		<!-- 下面是返回json串时,使用到的处理相关包 Jackson -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<!-- slf4j 日志文件框架使用的jar包 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>

		<!-- mysql driver 数据库驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>

		<!-- c3p0 datasource 数据库联接池使用的,此处是c3p0 -->
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<!-- druid 联接池,同时也提供内部默认的监控,个人推荐 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.23</version>
		</dependency>
		<!-- dbcp使用的默认联接池 配合 commons-pool 使用 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.5.4</version>
		</dependency>


		<!-- 中间件 ibatis -->
		<dependency>
			<groupId>org.apache.ibatis</groupId>
			<artifactId>ibatis-core</artifactId>
			<version>3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<!-- hiberante 4 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.1-GA</version>
		</dependency>
		<!-- http-client -->
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.3</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.4</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>
		<!-- json-lib -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.7</version>
		</dependency>
		<!-- memcached -->
		<dependency>
			<groupId>com.whalin</groupId>
			<artifactId>Memcached-Java-Client</artifactId>
			<version>3.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.maven-play-plugin.spy</groupId>
			<artifactId>spymemcached</artifactId>
			<version>2.6</version>
		</dependency>

		<!-- servlet3 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.8</version>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
	</dependencies>
	<build>
		<finalName>dubbo-service</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>3.0.2</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
						<configuration>
							<classifier>interface</classifier>
							<includes>
								<include>**/interfaces/*</include>
								<include>**/model/*</include>
							</includes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

####################################以上为dubbox-service的配置,########################

2,dubbox-client配置如下

包名规则如下

com.xuahua --------根包名

---------------controller --对外调用的服务,可以在内部使用上面暴露的接口。

 

com.xuahua.controller.DemoController.java 

内容如下

package com.xuahua.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xuahua.interfaces.DemoService;



/**
 * @author wyong
 * @version 1.0
 * @link QQ343886028
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

	@Autowired
	DemoService demoService;
//	
	@RequestMapping("/index")
	public String index(Model model){
		String result =demoService.sayHello("xuahua");
		System.out.println("======="+result);
		
		//此处是模拟调用请求,本人测试,服务端默认参数,超过5000个必定会抛出异常。
//		for(int i=0;i<1000;i++){
//			new Thread(new DemoController.process(demoService,String.valueOf(i))).start();
//		}
		return "index";
	}
	 
	/**
	 * @author wyong
	 * 此处只是做了一个多线程请求,模拟压力测试。。
	 
	class process implements Runnable {
		DemoService demoService;
		String name;
		public process(DemoService demoService,String name){
			this.demoService = demoService;
			this.name = name;
			Thread.currentThread().setName(name);
		}
		public void run() {
			 long s = System.currentTimeMillis();
			 String result =demoService.sayHello(name);
			 long b = System.currentTimeMillis();
			System.out.println(Thread.currentThread().getName()+"=>"+result+",cost=>"+(b-s)+"ms");
		}
		
	}*/
}

 

spring_dubbox.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:dubbo="http://code.alibabatech.com/schema/dubbo"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://code.alibabatech.com/schema/dubbo  
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd">  
   
   <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 -->
  <dubbo:application name="consumer-of-helloworld-web"  />
  <dubbo:monitor protocol= "registry" />
  
    <!-- 使用zookeeper注册中心暴露服务地址  192.168.0.101 为zookeeper的ip地址及开放端口--> 
 <dubbo:registry protocol = "zookeeper" address="192.168.0.101:2181" /> 
 <dubbo:protocol name="dubbo"  port="20880" />
 
 <!-- 对于初始化,强制使用 demoService 参数init="true" -->
	<dubbo:reference id="demoService" interface="com.xuahua.interfaces.DemoService" check="false" timeout="5000" /> 
</beans>  

 

同样在spring-mvc.xml配置最后面引入

<!-- **************************** 导入其他XML文件 **************************** -->
<import resource="spring_dubbo.xml" />
<!-- **************************** /导入其他XML文件 **************************** -->

 

dubbx-client工程pom.xml配置如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.xuahua</groupId>
	<artifactId>dubbo-module-client</artifactId>
	<packaging>war</packaging>
	<version>1.0</version>
	<name>com.xuahua Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<!-- 定义本pom.xml引用版本属性, org.springframework-version,org.hibernate-version,project.build.sourceEncodeing 
		此名可随便取,必须与下面引用相匹配。 -->
	<properties>
		<org.springframework-version>4.0.0.RELEASE</org.springframework-version>
		<org.hibernate-version>4.3.1.Final</org.hibernate-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.parent.version>2.8.4</project.parent.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- 从provider工程打包放到nexus上面后,再引用 -->
		<dependency>
			<groupId>com.xuahua.interfaces</groupId>
			<artifactId>demoService</artifactId>
			<version>1.0</version>
		</dependency>
		<!-- 此处可以添加相关联的,使用的jar包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>dubbo</artifactId>
			<version>${project.parent.version}</version>
			<exclusions>
				<exclusion>
					<artifactId>spring</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>com.101tec</groupId>
			<artifactId>zkclient</artifactId>
			<version>0.2</version>
		</dependency>

		<!-- 下面是springframwork 4.xx 引用的包 -->
		<!-- spring 4 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- Apache Commons 基础组件 -->
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.8</version>
		</dependency>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.10</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>

		<!-- 下面是返回json串时,使用到的处理相关包 Jackson -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<!-- slf4j 日志文件框架使用的jar包 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>

		<!-- mysql driver 数据库驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>

		<!-- c3p0 datasource 数据库联接池使用的,此处是c3p0 -->
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<!-- druid 联接池,同时也提供内部默认的监控,个人推荐 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.23</version>
		</dependency>
		<!-- dbcp使用的默认联接池 配合 commons-pool 使用 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.5.4</version>
		</dependency>


		<!-- 中间件 ibatis -->
		<dependency>
			<groupId>org.apache.ibatis</groupId>
			<artifactId>ibatis-core</artifactId>
			<version>3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<!-- hiberante 4 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.1-GA</version>
		</dependency>
		<!-- http-client -->
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.3</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.4</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>
		<!-- json-lib -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.7</version>
		</dependency>
		<!-- memcached -->
		<dependency>
			<groupId>com.whalin</groupId>
			<artifactId>Memcached-Java-Client</artifactId>
			<version>3.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.maven-play-plugin.spy</groupId>
			<artifactId>spymemcached</artifactId>
			<version>2.6</version>
		</dependency>

		<!-- servlet3 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.3</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

</project>

 

特别要注意pom.xml中标红的,那是我使用dubbox-server工程打出来的接口jar包,我上传到了本地仓库中。如果你直接放到了lib中,就不需要此引用。

完整源码包下载

dubbox-service

dubbox-client

 

 

 

 

spring实战汇总

1,
    spring实战系列一MAVEN工程建立
2,
    spring实战之二maven文件配置


3,

    spring实战之三web配置

4,



    spring实战之四run



完整工程源码下载

如果你也需要jar包,此处也有lib打包下载



spring实战之四run 有更新!

前面讲了这么多,到了最关键的时候了,让他跑起来吧。

1,生成文件路径,java ,source,webapp各目录下的文件。




文件目录路径必须与applicationContext.xml ,spring-webmvc.xml中配置的一致。



至此,已经编译成功。可以在工程target目录下的 把war复制到运行容器中即可运行。

效果图如下

spring实战之三web配置 有更新!

1,除了需要配置pom.xml需要引用的jar包以外,还需要配置其他的配置文件;如web.xml,spring-mvc.xml,applicationContext.xml等。

现在一一详细解说

web.xml



<!-- spring初始化时,容器调用监听 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 <!--  spring初始化时,引用文件工程目录下所有以applicationContext_开头的.xml,包括jar包中也会搜索进来。
    	classpath:applicationContext.xml 仅指工程classes目录下的applicationContext.xml;
    	classpath:applicationContext_*.xml 仅指工程classes目录下的applicationContext_开头的.xml文件;
    	classpath*:applicationContext_.xml 指工程classes目录下包括lib包中,包含有application_开头的.xml文件。	
    	 文件以及全局参数,此处默认了一个参数product来控制是否使用生产联接串或开发联接串-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.default</param-name>
        <param-value>product</param-value>
    </context-param>
  <!-- 不多说了,编码过滤器 -->
    <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>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 <!-- spring mvc的初始化,文件为classes目录下的 spring-webmvc.xml web请求处理参数,以及 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-webmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  <!--MySQL数据库JNDI数据  可在程序手动lookup 到数据源-->
    <resource-ref>
       <description>xuahua</description>
       <res-ref-name>jdbc/xuahua</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
   </resource-ref>
 <!-- druid web监控使用,如果不需要监控,可不用 -->
   <servlet>  
        <servlet-name>DruidStatView</servlet-name>  
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
    </servlet>    
    <servlet-mapping>  
        <servlet-name>DruidStatView</servlet-name>  
        <url-pattern>/druid/*</url-pattern>  
    </servlet-mapping> 
        
以上为一般工程所需要的基本文件.


其中文件提到了  applicationContext.xml  spring-webmvc.xml

applicationContext.xml 内容如下

<!-- 加载属性文件,如果没有,可不使用 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>classpath:parameter.properties</value>
		</property>
	</bean>


<!-- Hibernate 联接配置 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		
		<!-- 指定数据源 -->
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		
		<!-- 指定实体映射文件 -->
		<property name="packagesToScan">
			<list>
				<value>com.xuahua.model</value>
			</list>
		</property>
		
		<!-- 属性文件 -->
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.show_sql=true
				hibernate.format_sql=true
				hibernate.cache.use_second_level_cache=false
				hibernate.use_sql_comments=false
				hibernate.jdbc.batch_size=30
				hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
			</value>
		</property>
	</bean>
 <!-- hibernate事务管理 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
<!-- 事务切入点 -->
	<aop:config>
		<aop:pointcut id="crudMethodsCoreMaster"
			expression="execution(* com.xuahua.service..*.*(..))" />
		<aop:advisor advice-ref="txAdviceCoreMaster" pointcut-ref="crudMethodsCoreMaster" />
	</aop:config>
	
<!-- hibernate 代理事务,定义哪些service 开头的应该需要事务。哪些只需要只读事务 -->
	<tx:advice id="txAdviceCoreMaster" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="mng*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="create*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="save*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="update*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="insert*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="delete*" propagation="REQUIRED"
				rollback-for="Exception" />
			<tx:method name="do*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="load*" read-only="true" />
			<tx:method name="get*" read-only="true" />
			<tx:method name="list*" read-only="true" />
			<tx:method name="find*" read-only="true" />
			<tx:method name="view*" read-only="true" />
			<tx:method name="show*" read-only="true" />
			<tx:method name="valid*" read-only="true" />
			<tx:method name="query*" read-only="true" />
		</tx:attributes>
	</tx:advice>

		<!-- 生产数据源(JNDI)(生产环境、UAT环境、测试环境用) -->
	<beans profile="product">
		<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
			<property name="jndiName">
				<value>${jndiName}</value>
			</property>
		</bean>
	</beans>
<!-- druid web监控使用。 -->
	<beans>
		<bean id="druid-stat-interceptor"
			class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
		</bean>
	
	
		<bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut"
			scope="prototype">
			<property name="patterns">
				<list>
					<value>com.xuahua.service.*</value>
				</list>
			</property>
		</bean>
	
		<aop:config>
			<aop:advisor advice-ref="druid-stat-interceptor"
				pointcut-ref="druid-stat-pointcut" />
		</aop:config>
 	</beans>


spring-mvc.xml文件内容如下

<!-- 定义自动代理 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
	
	<!-- spring 定义扫描的包,对应工程路径.com.xuahua.controller;dao;service,意味着这三个包下面的所有类,spring会把注解的类名,方法名都会扫描进来 -->
	<context:component-scan base-package="com.xuahua">
		<context:include-filter type="regex"
			expression=".controller..*" />
		<context:include-filter type="regex"
			expression=".dao..*" />
		<context:include-filter type="regex"
			expression=".service..*" />
	</context:component-scan>
    
	<!-- 启动注解的方式 -->
	<context:annotation-config />  
	
 <!-- spring mvc 请求映射处理默认-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    
    <!-- spring mvc Adapter 请求适配 转换json使用-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <!-- 处理JSON数据转换的-->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

	<!-- 使用默认的Servlet来响应静态文件-->
	<mvc:default-servlet-handler />
<!-- 视图解释类,定义文件路径,以及文件后缀。 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 上传文件支持 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

完整文件下载地址  web.xml http://file.xuahua.com/images/blog/2016/0728/web.xml

                          applicationContext.xml  http://file.xuahua.com/images/blog/2016/0728/applicationContext.xml

                         spring-webmvc.xml   http://file.xuahua.com/images/blog/2016/0728/spring-webmvc.xml


spring实战之二maven文件配置

1,建立工程以后,就可以先运行pom.xml可以看到成功,并产生一个空的war包。 如何建工程?请见 spring实战之一maven工程建立

2, 打开编辑pom.xml

在根节点project下,dependencies 节点前添加以下内容

<modelVersion>4.0.0</modelVersion>
  <groupId>blog</groupId>
  <artifactId>com.xuahua</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>com.xuahua Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!-- 定义本pom.xml引用版本属性, org.springframework-version,org.hibernate-version,project.build.sourceEncodeing 此名可随便取,必须与下面引用相匹配。 -->
  <properties>
		<org.springframework-version>4.0.0.RELEASE</org.springframework-version>
		<org.hibernate-version>4.3.1.Final</org.hibernate-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
dependencies 节点内,可添加相关联的包

<!-- 下面是springframwork 4.xx 引用的包 -->
    <!-- spring 4 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
   	 <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

Apache Commons 基础组件


<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.8</version>
		</dependency>
		<dependency>
			<groupId>commons-configuration</groupId>
			<artifactId>commons-configuration</artifactId>
			<version>1.10</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3.6</version>
		</dependency>
返回json串时,使用到的处理相关包 Jackson 

<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
slf4j 日志文件框架使用的jar包

<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
mysql driver 数据库驱动包

	<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>
 数据库联接池使用的

<!-- c3p0 datasource  数据库联接池使用的,此处是c3p0-->
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<!-- druid 联接池,同时也提供内部默认的监控,个人推荐 -->
		 <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.23</version>
		</dependency>
		<!-- dbcp使用的默认联接池  配合 commons-pool 使用-->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.5.4</version>
		</dependency>
		
		
		<!-- 中间件 ibatis -->
		<dependency>
			<groupId>org.apache.ibatis</groupId>
			<artifactId>ibatis-core</artifactId>
			<version>3.0</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
 hiberante 4

<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>${org.hibernate-version}</version>
		</dependency>
		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.1-GA</version>
		</dependency>
		<!-- http-client -->
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.3</version>
		</dependency>
		
其他可以用到的

<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.7.4</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.7.4</version>
		</dependency>
		<!-- json-lib -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.7</version>
		</dependency>
		<!-- memcached -->
		<dependency>
			<groupId>com.whalin</groupId>
			<artifactId>Memcached-Java-Client</artifactId>
			<version>3.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.maven-play-plugin.spy</groupId>
			<artifactId>spymemcached</artifactId>
			<version>2.6</version>
		</dependency>
		
		<!-- servlet3 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.3</version>
			<scope>provided</scope>
		</dependency>

完整的文件可以下载地址 http://file.xuahua.com/images/blog/2016/0728/pom.xml

spring实战系列一MAVEN工程建立 有更新!

1,前提,maven工程需要的nexus 另外自己搭建;

2,eclipse开发工具流程


2.1 选择maven project

maven-喧哗博客


 指定工程目录


maven-喧哗博客

 建立maven工程对应配置

maven-喧哗博客

maven pom.xml文件指定的groupid


点 Fisnish 。至此 maven工程已经建立起来了。。如果需要运行,请见spring实战系列二配置

spring3定时任务之定时任务管理(一) 有更新!

在web互联网时代,定时任务随处可见,做一个定时任务管理界面,由后端操作人员来控制可省不少事情,而且时间可动态变更。也可由开发人员根据业务需求手动动态变更时间。

现在提供一个简单的可用的定时任务管理。

定时任务把任务保存在数据库,也可保存在文件中。下面的例子为保存在服务器文件。

准备工作

1.定义定时任务--包括定时任务名称以及对应的执行方法类;此类任务保存在 taskClass.properties文件中。

2,定义定时任务运行的业务,包括定时任务名称,定时任务的分组,定时任务执行频率,开始执行时间;此类任务定义保存在task.properties文件中。

3,后端的管理操作界面有展示有定时任务名称,执行方法,定时任务操作有(增加,删除,修改,暂停)。

样例图片--喧哗-blog.xuahua.com

关键执行代码:


 @RequestMapping("/taskindex.shtml")
    public String index(Model model){
        try{
            Map<String,String > map= TaskClassPropertiesUtil.getTaskClass();
            model.addAttribute("selectClass",map);

        }catch (Exception e){

        }
        return "admin/task/taskindex";
    }
jsp  下载页面 http://file.xuahua.com/js/blog/taskindex.jsp


js  下载页面   http://file.xuahua.com/js/blog/taskindex.js


TaskClassPropertiesUtil类文件,关键代码


public static String pathUrl=TaskClassPropertiesUtil.class.getResource("/").getPath()+"taskClass.properties";
    public static Map<String ,String> getTaskClass() throws Exception {
        Map<String ,String> map=new HashMap<String ,String>();
            Properties properties =new Properties();
            InputStream in=new FileInputStream(pathUrl);
            BufferedReader bf = new BufferedReader(new  InputStreamReader(in));
            properties.load(bf);
            in.close();
            Enumeration enu=properties.keys();
            while(enu.hasMoreElements()){
                String key=enu.nextElement().toString();
                String value=properties.getProperty(key);
                map.put(key,value);
        
            }
           return  map;
    }

 taskClass.properties 示例下载 http://file.xuahua.com/blog/taskClass.properties

 后续的如何操作定时任务以及动态变更定时任务请见定时任务管理(二)


spring--secrutiy--控制到按钮 有更新!

使用spring security taglib: 
Java代码 
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> 
... 
<security:authorize ifAnyGranted="ROLE_ADMIN"> 
<a href="user/input/id/${nuId}.html">编辑</a> 
</security:authorize>

spring4.x+json+中文乱码解决

基本配置:
1,在配置文件web.xml中设置统一设置过滤字符串
        <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>
         </filter>
 
         <filter-mapping>
              <filter-name>encodingFilter</filter-name>
              <url-pattern>/*</url-pattern>
         </filter-mapping>
2,在applicationContent.xml中配置返回json编码
        <bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
 <bean
  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  <property name="messageConverters">
   <list>
    <bean
     class="org.springframework.http.converter.StringHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list>
       <value>text/plain;charset=UTF-8</value>
       <value>text/html;charset=UTF-8</value>
      </list>
     </property>
    </bean>
    <bean
     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list>
       <value>text/plain;charset=UTF-8</value>
       <value>application/json;charset=UTF-8</value>
      </list>
     </property>
    </bean>
   </list>
  </property>
 </bean>
 
3,在response返回流中,设置响应头编码格式,统一为 UTF-8
       response.setHeader("Content-type", "text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
4,在tomcat中配置文件中server.xml中<connector>节点,添加 URIEncoding="UTF-8"
 
 
第一种解决方案:
        在@RequestMapping(value="/index" ,produces = "text/html;charset=UTF-8")
 在使用public Map<String,Object) index(){} 这样的方法时,一定要写这样的注解才可以保持中文不乱码。

但是这种写法每个都需要硬编码 ,可以使用第二种方案。
 
第二种解决方案:
<!-- spring4.x json中文乱码处理,这一句一定要放在context:compent-scan前面 -->
 <mvc:annotation-driven>
  <mvc:message-converters>
   <bean class="org.springframework.http.converter.StringHttpMessageConverter">
    <property name="supportedMediaTypes">
     <list>
      <value>text/plain;charset=UTF-8</value>
      <value>text/html;charset=UTF-8</value>
     </list>
    </property>
   </bean>
  </mvc:message-converters>
 </mvc:annotation-driven>

开源并且安全使用很多年的后台权限登录系统 有更新!

曾经的我们,也为企业使用后台的权限管理系统头疼了好久,后来发现有套源码叫acegi的spring自带开源的权限管理系统。

现在共享出来给大家使用。

源码下载地址为: http://www.xuahua.com/download/blog/t_Vcasmin.tar.gz

公告

喧哗博客--繁华过后的沉寂--技术经验分享^-^
Copyright (c) 2009-2019, b3log.org & hacpai.com