码迷,mamicode.com
首页 > 其他好文 > 详细

SSM+dubbo+zookeeper实现基本的增删改查

时间:2018-12-02 19:19:48      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:names   server   hang   lse   fun   初始   打开   sch   work   

前言

本文中使用的项目是由上一篇文章中的项目改造而来。具体来说,就是引入了dubbo和zookeeper,并将Controller层与service层dao层进行了拆分,使双方通过service接口远程调用的形式,再次实现了基本的增删改查。

上一篇文章:http://www.cnblogs.com/hanzx/p/10016468.html

 

名词解释

dubbo:dubbo是阿里开源的一款优秀的java RPC框架,可以配合spring和zookeeper使用。它提供了这些功能:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。

zookeeper:zookeeper 是由雅虎创建的一个开源的分布式协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它提供了这些功能:配置维护、域名服务、分布式同步、组服务等。

 

zookeeper的windows版安装方法

https://blog.csdn.net/weixin_37715446/article/details/78642052

 

程序结构

interface:

技术分享图片

provider:

技术分享图片

consumer:

技术分享图片

 

程序源码

interface

pom.xml

没添加什么东西,所以不贴出来了

 

UserModel

技术分享图片
 1 package org.hanzx.model;
 2 
 3 
 4 import java.io.Serializable;
 5 
 6 public class UserModel implements Serializable{
 7 
 8     private Integer id;
 9 
10     private String name;
11 
12     private Integer age;
13 
14     private String password;
15 
16     public Integer getId() {
17         return id;
18     }
19 
20     public void setId(Integer id) {
21         this.id = id;
22     }
23 
24     public String getName() {
25         return name;
26     }
27 
28     public void setName(String name) {
29         this.name = name;
30     }
31 
32     public Integer getAge() {
33         return age;
34     }
35 
36     public void setAge(Integer age) {
37         this.age = age;
38     }
39 
40     public String getPassword() {
41         return password;
42     }
43 
44     public void setPassword(String password) {
45         this.password = password;
46     }
47 }
View Code

 

UserService

技术分享图片
 1 package org.hanzx.service;
 2 
 3 
 4 import org.hanzx.model.UserModel;
 5 
 6 import java.util.List;
 7 
 8 public interface UserService {
 9 
10     List<UserModel> getAllUser();
11 
12     void addUser(UserModel userModel);
13 
14     UserModel getUserById(Integer id);
15 
16     void updateUser(UserModel userModel);
17 
18     void deleteUser(Integer[] ids);
19 }
View Code

 

provider

pom.xml

技术分享图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0"
  3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <parent>
  6         <artifactId>web_ssm_dubbo</artifactId>
  7         <groupId>org.hanzx</groupId>
  8         <version>1.0-SNAPSHOT</version>
  9     </parent>
 10     <modelVersion>4.0.0</modelVersion>
 11 
 12     <artifactId>provider</artifactId>
 13 
 14     <properties>
 15         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 16         <spring.version>4.2.5.RELEASE</spring.version>
 17         <mybatis.version>3.2.1</mybatis.version>
 18         <slf4j.version>1.6.6</slf4j.version>
 19         <log4j.version>1.2.12</log4j.version>
 20         <mysql.version>5.1.35</mysql.version>
 21     </properties>
 22 
 23     <dependencies>
 24         <dependency>
 25             <groupId>org.hanzx</groupId>
 26             <artifactId>interface</artifactId>
 27             <version>1.0-SNAPSHOT</version>
 28         </dependency>
 29 
 30         <dependency>
 31             <groupId>junit</groupId>
 32             <artifactId>junit</artifactId>
 33             <version>4.11</version>
 34             <scope>test</scope>
 35         </dependency>
 36         <!-- 添加Spring依赖 -->
 37         <dependency>
 38             <groupId>org.springframework</groupId>
 39             <artifactId>spring-core</artifactId>
 40             <version>${spring.version}</version>
 41         </dependency>
 42         <dependency>
 43             <groupId>org.springframework</groupId>
 44             <artifactId>spring-context</artifactId>
 45             <version>${spring.version}</version>
 46         </dependency>
 47         <dependency>
 48             <groupId>org.springframework</groupId>
 49             <artifactId>spring-context-support</artifactId>
 50             <version>${spring.version}</version>
 51         </dependency>
 52         <dependency>
 53             <groupId>org.springframework</groupId>
 54             <artifactId>spring-aop</artifactId>
 55             <version>${spring.version}</version>
 56         </dependency>
 57         <dependency>
 58             <groupId>org.springframework</groupId>
 59             <artifactId>spring-aspects</artifactId>
 60             <version>${spring.version}</version>
 61         </dependency>
 62         <dependency>
 63             <groupId>org.springframework</groupId>
 64             <artifactId>spring-tx</artifactId>
 65             <version>${spring.version}</version>
 66         </dependency>
 67         <dependency>
 68             <groupId>org.springframework</groupId>
 69             <artifactId>spring-jdbc</artifactId>
 70             <version>${spring.version}</version>
 71         </dependency>
 72         <!--spring单元测试依赖 -->
 73         <dependency>
 74             <groupId>org.springframework</groupId>
 75             <artifactId>spring-test</artifactId>
 76             <version>${spring.version}</version>
 77             <scope>test</scope>
 78         </dependency>
 79         <!-- mysql驱动包 -->
 80         <dependency>
 81             <groupId>mysql</groupId>
 82             <artifactId>mysql-connector-java</artifactId>
 83             <version>${mysql.version}</version>
 84         </dependency>
 85 
 86         <!-- alibaba data source 相关jar包-->
 87         <dependency>
 88             <groupId>com.alibaba</groupId>
 89             <artifactId>druid</artifactId>
 90             <version>0.2.23</version>
 91         </dependency>
 92         <!-- logback start -->
 93         <dependency>
 94             <groupId>log4j</groupId>
 95             <artifactId>log4j</artifactId>
 96             <version>${log4j.version}</version>
 97         </dependency>
 98         <dependency>
 99             <groupId>org.slf4j</groupId>
100             <artifactId>slf4j-api</artifactId>
101             <version>${slf4j.version}</version>
102         </dependency>
103         <dependency>
104             <groupId>ch.qos.logback</groupId>
105             <artifactId>logback-classic</artifactId>
106             <version>1.1.2</version>
107         </dependency>
108         <dependency>
109             <groupId>ch.qos.logback</groupId>
110             <artifactId>logback-core</artifactId>
111             <version>1.1.2</version>
112         </dependency>
113         <dependency>
114             <groupId>org.logback-extensions</groupId>
115             <artifactId>logback-ext-spring</artifactId>
116             <version>0.1.1</version>
117         </dependency>
118 
119         <!--mybatis依赖 -->
120         <dependency>
121             <groupId>org.mybatis</groupId>
122             <artifactId>mybatis</artifactId>
123             <version>${mybatis.version}</version>
124         </dependency>
125 
126         <!-- mybatis/spring包 -->
127         <dependency>
128             <groupId>org.mybatis</groupId>
129             <artifactId>mybatis-spring</artifactId>
130             <version>1.2.0</version>
131         </dependency>
132 
133         <!--dubbo-->
134         <dependency>
135             <groupId>com.alibaba</groupId>
136             <artifactId>dubbo</artifactId>
137             <version>2.5.7</version>
138         </dependency>
139         <dependency>
140             <groupId>org.apache.zookeeper</groupId>
141             <artifactId>zookeeper</artifactId>
142             <version>3.5.4-beta</version>
143             <type>pom</type>
144         </dependency>
145         <dependency>
146             <groupId>com.101tec</groupId>
147             <artifactId>zkclient</artifactId>
148             <version>0.10</version>
149         </dependency>
150         <dependency>
151             <groupId>org.apache.curator</groupId>
152             <artifactId>curator-framework</artifactId>
153             <version>2.7.1</version>
154         </dependency>
155     </dependencies>
156 
157 
158 </project>
View Code

applicationContext.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 6 
 7     <!-- 1.配置jdbc文件 -->
 8     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 9         <property name="locations" value="classpath:jdbc.properties"/>
10     </bean>
11     <!-- 2.扫描的包路径 --><!--使用<context:component-scan/> 可以不再配置<context:annotation-config/> -->
12     <context:component-scan base-package="org.hanzx"/>
13     <!--6 容器自动扫描IOC组件  -->
14     <!--<context:component-scan base-package="org.hanzx.model"/>-->
15     <import resource="spring-mybatis.xml"/>
16     <import resource="spring-dubbo.xml"/>
17 </beans>
View Code

jdbc.properties

技术分享图片
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/web_test?useUnicode=true&characterEncoding=utf8&useSSL=false
3 jdbc.username=root
4 jdbc.password=root
View Code

log4j2.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <Configuration status="warn">
 4     <Appenders>
 5         <Console name="Console" target="SYSTEM_OUT">
 6             <PatternLayout pattern="%m%n" />
 7         </Console>
 8     </Appenders>
 9     <Loggers>
10         <Root level="INFO">
11             <AppenderRef ref="Console" />
12         </Root>
13     </Loggers>
14 </Configuration>
View Code

logback.xml

技术分享图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <configuration>
  3     <!-- 尽量别用绝对路径,如果带参数不同容器路径解释可能不同,以下配置参数在pom.xml里 -->
  4     <property name="log.root.level" value="${log.root.level}" /> <!-- 日志级别 -->
  5     <property name="log.other.level" value="${log.other.level}" /> <!-- 其他日志级别 -->
  6     <property name="log.base" value="${log.base}" /> <!-- 日志路径,这里是相对路径,web项目eclipse下会输出到eclipse的安装目录下,如果部署到linux上的tomcat下,会输出到tomcat/bin目录 下 -->
  7     <property name="log.moduleName" value="${log.moduleName}" />  <!-- 模块名称, 影响日志配置名,日志文件名 -->
  8     <property name="log.max.size" value="100MB" /> <!-- 日志文件大小,超过这个大小将被压缩 -->
  9 
 10     <!--控制台输出 -->
 11     <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
 12         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
 13             <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</Pattern>
 14         </encoder>
 15     </appender>
 16 
 17     <!-- 用来保存输出所有级别的日志 -->
 18     <appender name="file.all" class="ch.qos.logback.core.rolling.RollingFileAppender">
 19         <File>${log.base}/${log.moduleName}.log</File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果
 20             是web项目会保存到Tomcat的bin目录 下 -->
 21         <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。 -->
 22         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 23             <FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
 24             </FileNamePattern>
 25             <!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件备份) -->
 26             <timeBasedFileNamingAndTriggeringPolicy
 27                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 28                 <maxFileSize>${log.max.size}</maxFileSize>
 29             </timeBasedFileNamingAndTriggeringPolicy>
 30         </rollingPolicy>
 31         <!-- 日志输出的文件的格式 -->
 32         <layout class="ch.qos.logback.classic.PatternLayout">
 33             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</pattern>
 34         </layout>
 35     </appender>
 36 
 37     <!-- 这也是用来保存输出所有级别的日志 -->
 38     <appender name="file.all.other" class="ch.qos.logback.core.rolling.RollingFileAppender">
 39         <File>${log.base}/${log.moduleName}_other.log</File>
 40         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 41             <FileNamePattern>${log.base}/archive/${log.moduleName}_other_%d{yyyy-MM-dd}.%i.log.zip
 42             </FileNamePattern>
 43             <timeBasedFileNamingAndTriggeringPolicy
 44                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 45                 <maxFileSize>${log.max.size}</maxFileSize>
 46             </timeBasedFileNamingAndTriggeringPolicy>
 47         </rollingPolicy>
 48         <layout class="ch.qos.logback.classic.PatternLayout">
 49             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L -%msg%n</pattern>
 50         </layout>
 51     </appender>
 52 
 53     <!-- 只用保存输出error级别的日志 -->
 54     <appender name="file.error"
 55               class="ch.qos.logback.core.rolling.RollingFileAppender">
 56         <File>${log.base}/${log.moduleName}_err.log</File>
 57         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 58             <FileNamePattern>${log.base}/archive/${log.moduleName}_err_%d{yyyy-MM-dd}.%i.log.zip
 59             </FileNamePattern>
 60             <timeBasedFileNamingAndTriggeringPolicy
 61                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 62                 <maxFileSize>${log.max.size}</maxFileSize>
 63             </timeBasedFileNamingAndTriggeringPolicy>
 64         </rollingPolicy>
 65         <layout class="ch.qos.logback.classic.PatternLayout">
 66             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L - %msg%n</pattern>
 67         </layout>
 68         <!-- 下面为配置只输出error级别的日志 -->
 69         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 70             <level>ERROR</level>
 71             <onMatch>ACCEPT</onMatch>
 72             <onMismatch>DENY</onMismatch>
 73         </filter>
 74     </appender>
 75 
 76     <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
 77     <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
 78     <!-- 添加附加的appender,最多只能添加一个 -->
 79     <appender name="file.async" class="ch.qos.logback.classic.AsyncAppender">
 80         <discardingThreshold>0</discardingThreshold>
 81         <queueSize>256</queueSize>
 82         <includeCallerData>true</includeCallerData>
 83         <appender-ref ref="file.all" />
 84     </appender>
 85 
 86     <appender name="file.async.other" class="ch.qos.logback.classic.AsyncAppender">
 87         <discardingThreshold>0</discardingThreshold>
 88         <queueSize>256</queueSize>
 89         <includeCallerData>true</includeCallerData>
 90         <appender-ref ref="file.all.other" />
 91     </appender>
 92 
 93     <!-- 为某个包下的所有类的指定Appender 这里也可以指定类名称例如:com.aa.bb.ClassName -->
 94     <logger name="com.lin" additivity="false">
 95         <level value="${log.root.level}" />
 96         <appender-ref ref="stdout" />
 97         <appender-ref ref="file.async" /><!-- 即com.lin包下级别为 ${log.root.level}的才会使用file.async来打印 -->
 98         <appender-ref ref="file.error" />
 99     </logger>
100 
101     <!-- root将级别为${log.root.level}及大于${log.root.level}的日志信息交给已经配置好的名为“Console”的appender处理,“Console”appender将信息打印到Console,其它同理 -->
102     <root level="${log.root.level}">
103         <appender-ref ref="stdout" /> <!--  标识这个appender将会添加到这个logger -->
104         <appender-ref ref="file.async.other" />
105         <appender-ref ref="file.error" />
106     </root>
107 </configuration>
View Code

spring-dubbo.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
 4        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">
 5     <!-- 提供方应用信息,用于计算依赖关系 -->
 6     <dubbo:application name="provider"/>
 7     <!-- 使用zookeeper注册中心暴露服务地址 -->
 8     <dubbo:registry address="zookeeper://127.0.0.1:2181"/>
 9     <!-- 用dubbo协议在20880端口暴露服务 -->
10     <dubbo:protocol name="dubbo" port="20880"/>
11     <!-- 声明需要暴露的服务接口 -->
12     <dubbo:service interface="org.hanzx.service.UserService" ref="userService" protocol="dubbo"/>
13     <!-- 具体的实现bean -->
14     <bean id="userService" class="org.hanzx.serviceimpl.UserServiceImpl"/>
15 </beans>
View Code

spring-mybatis.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 5     <!-- 3.配置数据源 ,使用的alibba的数据库-->
 6     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
 7         <!-- 基本属性 url、userEntity、password -->
 8         <property name="driverClassName" value="${jdbc.driver}"/>
 9         <property name="url" value="${jdbc.url}"/>
10         <property name="username" value="${jdbc.username}"/>
11         <property name="password" value="${jdbc.password}"/>
12 
13         <!-- 配置初始化大小、最小、最大 -->
14         <property name="initialSize" value="10"/>
15         <property name="minIdle" value="10"/>
16         <property name="maxActive" value="50"/>
17 
18         <!-- 配置获取连接等待超时的时间 -->
19         <property name="maxWait" value="60000"/>
20         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
21         <property name="timeBetweenEvictionRunsMillis" value="60000" />
22 
23         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
24         <property name="minEvictableIdleTimeMillis" value="300000" />
25 
26         <property name="validationQuery" value="SELECT ‘x‘" />
27         <property name="testWhileIdle" value="true" />
28         <property name="testOnBorrow" value="false" />
29         <property name="testOnReturn" value="false" />
30 
31         <!-- 打开PSCache,并且指定每个连接上PSCache的大小  如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。-->
32         <property name="poolPreparedStatements" value="false" />
33         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
34 
35         <!-- 配置监控统计拦截的filters -->
36         <property name="filters" value="wall,stat" />
37     </bean>
38 
39 
40 
41     <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
42     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
43         <property name="dataSource" ref="dataSource" />
44         <!-- 自动扫描mapping.xml文件 -->
45         <property name="mapperLocations" value="classpath:mappers/*.xml" />
46     </bean>
47 
48 
49     <!-- DAO接口所在包名,Spring会自动查找其下的类 ,自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,只要Mapper接口类和Mapper映射文件对应起来就可以了-->
50     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
51         <property name="basePackage" value="org.hanzx.dao" />
52         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
53     </bean>
54 
55     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
56     <!-- 配置事务管理器 -->
57     <bean id="transactionManager"
58           class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
59         <property name="dataSource" ref="dataSource" />
60     </bean>
61 
62     <!--======= 事务配置 End =================== -->
63     <!-- 配置基于注解的声明式事务 -->
64     <!-- enables scanning for @Transactional annotations -->
65     <tx:annotation-driven transaction-manager="transactionManager" />
66 </beans>
View Code

ProviderRunner

技术分享图片
 1 package org.hanzx;
 2 
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 import java.io.IOException;
 6 
 7 public class ProviderRunner {
 8 
 9 
10     public static void main(String[] args) throws IOException {
11         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
12         context.start();
13         System.out.println("provider start");
14         int x = System.in.read();
15     }
16 
17 }
View Code

UserEntity

技术分享图片
 1 package org.hanzx.entity;
 2 
 3 
 4 
 5 public class UserEntity {
 6 
 7     private Integer id;
 8 
 9     private String name;
10 
11     private Integer age;
12 
13     private String password;
14 
15     public Integer getId() {
16         return id;
17     }
18 
19     public void setId(Integer id) {
20         this.id = id;
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public Integer getAge() {
32         return age;
33     }
34 
35     public void setAge(Integer age) {
36         this.age = age;
37     }
38 
39     public String getPassword() {
40         return password;
41     }
42 
43     public void setPassword(String password) {
44         this.password = password;
45     }
46 }
View Code

UserServiceImpl

技术分享图片
 1 package org.hanzx.serviceimpl;
 2 
 3 import org.hanzx.dao.UserDao;
 4 import org.hanzx.entity.UserEntity;
 5 import org.hanzx.model.UserModel;
 6 import org.hanzx.service.UserService;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 
10 import java.util.ArrayList;
11 import java.util.List;
12 
13 @Service
14 public class UserServiceImpl implements UserService{
15 
16     private final UserDao userDao;
17 
18     @Autowired
19     public UserServiceImpl(UserDao userDao) {
20         this.userDao = userDao;
21     }
22 
23     @Override
24     public List<UserModel> getAllUser() {
25         List<UserEntity> userEntityList = userDao.getAllUser();
26         List<UserModel> userModelList = new ArrayList<>();
27         for (UserEntity userEntity : userEntityList){
28             UserModel userModel = new UserModel();
29             userModel.setName(userEntity.getName());
30             userModel.setId(userEntity.getId());
31             userModel.setAge(userEntity.getAge());
32             userModelList.add(userModel);
33         }
34         return userModelList;
35 //        return null;
36     }
37 
38     @Override
39     public void addUser(UserModel userModel) {
40         UserEntity userEntity = new UserEntity();
41         userEntity.setName(userModel.getName());
42         userEntity.setAge(userModel.getAge());
43         userEntity.setPassword(userModel.getPassword());
44         userDao.addUser(userEntity);
45     }
46 
47     @Override
48     public UserModel getUserById(Integer id) {
49         UserEntity userEntity = userDao.getUserById(id);
50         UserModel userModel = new UserModel();
51         userModel.setAge(userEntity.getAge());
52         userModel.setId(userEntity.getId());
53         userModel.setName(userEntity.getName());
54         userModel.setPassword(userEntity.getPassword());
55         return userModel;
56 //        return null;
57     }
58 
59     @Override
60     public void updateUser(UserModel userModel) {
61         UserEntity userEntity = userDao.getUserById(userModel.getId());
62         userEntity.setPassword(userModel.getPassword());
63         userEntity.setAge(userModel.getAge());
64         userEntity.setName(userModel.getName());
65         userDao.updateUser(userEntity);
66     }
67 
68     @Override
69     public void deleteUser(Integer[] ids) {
70         for (Integer id : ids){
71             userDao.deleteUserById(id);
72         }
73     }
74 }
View Code

UserDao

技术分享图片
 1 package org.hanzx.dao;
 2 
 3 
 4 import org.hanzx.entity.UserEntity;
 5 import org.springframework.stereotype.Repository;
 6 
 7 import java.util.List;
 8 
 9 @Repository
10 public interface UserDao {
11 
12     List<UserEntity> getAllUser();
13 
14     void addUser(UserEntity userEntity);
15 
16     UserEntity getUserById(Integer id);
17 
18     void updateUser(UserEntity userEntity);
19 
20     void deleteUserById(Integer id);
21 }
View Code

userMapper.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 
 4 <mapper namespace="org.hanzx.dao.UserDao">
 5     <resultMap id="BaseResultMap" type="org.hanzx.entity.UserEntity" >
 6         <id column="id" property="id" jdbcType="INTEGER" />
 7         <result column="name" property="name" jdbcType="VARCHAR" />
 8         <result column="password" property="password" jdbcType="VARCHAR" />
 9         <result column="age" property="age" jdbcType="INTEGER" />
10     </resultMap>
11     <select id="getAllUser" resultMap="BaseResultMap" >
12       SELECT * FROM user;
13     </select>
14 
15     <insert id="addUser">
16         INSERT USER VALUES (null, #{name}, #{age}, #{password});
17     </insert>
18 
19     <select id="getUserById" resultMap="BaseResultMap">
20         SELECT * FROM user WHERE user.id = #{id};
21     </select>
22 
23     <update id="updateUser">
24         UPDATE user SET name = #{name}, age = #{age}, password = #{password} WHERE id = #{id};
25     </update>
26 
27     <delete id="deleteUserById">
28         DELETE FROM user where id = #{id};
29     </delete>
30 
31 </mapper>
View Code

 

consumer

pom.xml

技术分享图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <parent>
  6         <artifactId>web_ssm_dubbo</artifactId>
  7         <groupId>org.hanzx</groupId>
  8         <version>1.0-SNAPSHOT</version>
  9     </parent>
 10     <modelVersion>4.0.0</modelVersion>
 11 
 12     <artifactId>consumer</artifactId>
 13     <packaging>war</packaging>
 14 
 15     <name>consumer Maven Webapp</name>
 16     <!-- FIXME change it to the project‘s website -->
 17     <url>http://www.example.com</url>
 18 
 19     <properties>
 20         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 21         <spring.version>4.2.5.RELEASE</spring.version>
 22         <mybatis.version>3.2.1</mybatis.version>
 23         <slf4j.version>1.6.6</slf4j.version>
 24         <log4j.version>1.2.12</log4j.version>
 25         <mysql.version>5.1.35</mysql.version>
 26         <jackson.version>2.9.2</jackson.version>
 27     </properties>
 28 
 29     <dependencies>
 30         <dependency>
 31             <groupId>junit</groupId>
 32             <artifactId>junit</artifactId>
 33             <version>4.11</version>
 34             <scope>test</scope>
 35         </dependency>
 36         <dependency>
 37             <groupId>org.hanzx</groupId>
 38             <artifactId>interface</artifactId>
 39             <version>1.0-SNAPSHOT</version>
 40         </dependency>
 41 
 42         <!-- 添加Spring依赖 -->
 43         <dependency>
 44             <groupId>org.springframework</groupId>
 45             <artifactId>spring-core</artifactId>
 46             <version>${spring.version}</version>
 47         </dependency>
 48         <dependency>
 49             <groupId>org.springframework</groupId>
 50             <artifactId>spring-context</artifactId>
 51             <version>${spring.version}</version>
 52         </dependency>
 53         <dependency>
 54             <groupId>org.springframework</groupId>
 55             <artifactId>spring-context-support</artifactId>
 56             <version>${spring.version}</version>
 57         </dependency>
 58         <!--<dependency>-->
 59             <!--<groupId>org.springframework</groupId>-->
 60             <!--<artifactId>spring-aop</artifactId>-->
 61             <!--<version>${spring.version}</version>-->
 62         <!--</dependency>-->
 63         <!--<dependency>-->
 64             <!--<groupId>org.springframework</groupId>-->
 65             <!--<artifactId>spring-aspects</artifactId>-->
 66             <!--<version>${spring.version}</version>-->
 67         <!--</dependency>-->
 68         <!--<dependency>-->
 69             <!--<groupId>org.springframework</groupId>-->
 70             <!--<artifactId>spring-tx</artifactId>-->
 71             <!--<version>${spring.version}</version>-->
 72         <!--</dependency>-->
 73         <!--<dependency>-->
 74             <!--<groupId>org.springframework</groupId>-->
 75             <!--<artifactId>spring-jdbc</artifactId>-->
 76             <!--<version>${spring.version}</version>-->
 77         <!--</dependency>-->
 78         <dependency>
 79             <groupId>org.springframework</groupId>
 80             <artifactId>spring-web</artifactId>
 81             <version>${spring.version}</version>
 82         </dependency>
 83         <!--spring单元测试依赖 -->
 84         <dependency>
 85             <groupId>org.springframework</groupId>
 86             <artifactId>spring-test</artifactId>
 87             <version>${spring.version}</version>
 88             <scope>test</scope>
 89         </dependency>
 90 
 91         <!-- spring webmvc相关jar -->
 92         <dependency>
 93             <groupId>org.springframework</groupId>
 94             <artifactId>spring-webmvc</artifactId>
 95             <version>${spring.version}</version>
 96         </dependency>
 97 
 98         <!-- mysql驱动包 -->
 99         <!--<dependency>-->
100             <!--<groupId>mysql</groupId>-->
101             <!--<artifactId>mysql-connector-java</artifactId>-->
102             <!--<version>${mysql.version}</version>-->
103         <!--</dependency>-->
104 
105         <!-- alibaba data source 相关jar包-->
106         <!--<dependency>-->
107             <!--<groupId>com.alibaba</groupId>-->
108             <!--<artifactId>druid</artifactId>-->
109             <!--<version>0.2.23</version>-->
110         <!--</dependency>-->
111 
112         <!-- alibaba fastjson 格式化对 -->
113         <dependency>
114             <groupId>com.alibaba</groupId>
115             <artifactId>fastjson</artifactId>
116             <version>1.1.41</version>
117         </dependency>
118 
119         <!-- logback start -->
120         <dependency>
121             <groupId>log4j</groupId>
122             <artifactId>log4j</artifactId>
123             <version>${log4j.version}</version>
124         </dependency>
125         <dependency>
126             <groupId>org.slf4j</groupId>
127             <artifactId>slf4j-api</artifactId>
128             <version>${slf4j.version}</version>
129         </dependency>
130         <dependency>
131             <groupId>ch.qos.logback</groupId>
132             <artifactId>logback-classic</artifactId>
133             <version>1.1.2</version>
134         </dependency>
135         <dependency>
136             <groupId>ch.qos.logback</groupId>
137             <artifactId>logback-core</artifactId>
138             <version>1.1.2</version>
139         </dependency>
140         <dependency>
141             <groupId>org.logback-extensions</groupId>
142             <artifactId>logback-ext-spring</artifactId>
143             <version>0.1.1</version>
144         </dependency>
145 
146         <!--mybatis依赖 -->
147         <!--<dependency>-->
148             <!--<groupId>org.mybatis</groupId>-->
149             <!--<artifactId>mybatis</artifactId>-->
150             <!--<version>${mybatis.version}</version>-->
151         <!--</dependency>-->
152 
153         <!-- mybatis/spring包 -->
154         <!--<dependency>-->
155             <!--<groupId>org.mybatis</groupId>-->
156             <!--<artifactId>mybatis-spring</artifactId>-->
157             <!--<version>1.2.0</version>-->
158         <!--</dependency>-->
159         <!-- 添加servlet3.0核心包 -->
160         <dependency>
161             <groupId>javax.servlet</groupId>
162             <artifactId>javax.servlet-api</artifactId>
163             <version>3.0.1</version>
164         </dependency>
165         <dependency>
166             <groupId>javax.servlet.jsp</groupId>
167             <artifactId>javax.servlet.jsp-api</artifactId>
168             <version>2.3.2-b01</version>
169         </dependency>
170         <!-- jstl -->
171         <dependency>
172             <groupId>javax.servlet</groupId>
173             <artifactId>jstl</artifactId>
174             <version>1.2</version>
175         </dependency>
176         <!--thymeleaf-->
177         <dependency>
178             <groupId>org.thymeleaf</groupId>
179             <artifactId>thymeleaf-spring5</artifactId>
180             <version>3.0.9.RELEASE</version>
181         </dependency>
182 
183 
184         <!-- json -->
185         <dependency>
186             <groupId>com.fasterxml.jackson.core</groupId>
187             <artifactId>jackson-core</artifactId>
188             <version>${jackson.version}</version>
189         </dependency>
190         <dependency>
191             <groupId>com.fasterxml.jackson.core</groupId>
192             <artifactId>jackson-databind</artifactId>
193             <version>${jackson.version}</version>
194         </dependency>
195 
196         <!--dubbo-->
197         <dependency>
198             <groupId>com.alibaba</groupId>
199             <artifactId>dubbo</artifactId>
200             <version>2.5.7</version>
201         </dependency>
202         <dependency>
203             <groupId>org.apache.zookeeper</groupId>
204             <artifactId>zookeeper</artifactId>
205             <version>3.5.4-beta</version>
206             <type>pom</type>
207         </dependency>
208         <dependency>
209             <groupId>com.101tec</groupId>
210             <artifactId>zkclient</artifactId>
211             <version>0.10</version>
212         </dependency>
213         <dependency>
214             <groupId>org.apache.curator</groupId>
215             <artifactId>curator-framework</artifactId>
216             <version>2.7.1</version>
217         </dependency>
218     </dependencies>
219 
220     <build>
221         <finalName>consumer</finalName>
222         <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
223             <plugins>
224                 <plugin>
225                     <artifactId>maven-clean-plugin</artifactId>
226                     <version>3.0.0</version>
227                 </plugin>
228                 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
229                 <plugin>
230                     <artifactId>maven-resources-plugin</artifactId>
231                     <version>3.0.2</version>
232                 </plugin>
233                 <plugin>
234                     <artifactId>maven-compiler-plugin</artifactId>
235                     <version>3.7.0</version>
236                 </plugin>
237                 <plugin>
238                     <artifactId>maven-surefire-plugin</artifactId>
239                     <version>2.20.1</version>
240                 </plugin>
241                 <plugin>
242                     <artifactId>maven-war-plugin</artifactId>
243                     <version>3.2.0</version>
244                 </plugin>
245                 <plugin>
246                     <artifactId>maven-install-plugin</artifactId>
247                     <version>2.5.2</version>
248                 </plugin>
249                 <plugin>
250                     <artifactId>maven-deploy-plugin</artifactId>
251                     <version>2.8.2</version>
252                 </plugin>
253             </plugins>
254         </pluginManagement>
255     </build>
256 </project>
View Code

web.xml

技术分享图片
 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7   <!-- 读取spring配置文件 -->
 8   <context-param>
 9     <param-name>contextConfigLocation</param-name>
10     <param-value>classpath:applicationContext.xml</param-value>
11   </context-param>
12 
13   <context-param>
14     <param-name>logbackConfigLocation</param-name>
15     <param-value>classpath:logback.xml</param-value>
16   </context-param>
17 
18   <!-- 设计路径变量值
19   <context-param>
20       <param-name>webAppRootKey</param-name>
21       <param-value>springmvc.root</param-value>
22   </context-param>
23   -->
24 
25   <!-- Spring字符集过滤器 -->
26   <filter>
27     <filter-name>SpringEncodingFilter</filter-name>
28     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
29     <init-param>
30       <param-name>encoding</param-name>
31       <param-value>UTF-8</param-value>
32     </init-param>
33     <init-param>
34       <param-name>forceEncoding</param-name>
35       <param-value>true</param-value>
36     </init-param>
37   </filter>
38   <filter-mapping>
39     <filter-name>SpringEncodingFilter</filter-name>
40     <url-pattern>/*</url-pattern>
41   </filter-mapping>
42   <!-- 添加日志监听器 -->
43   <listener>
44     <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
45   </listener>
46 
47   <listener>
48     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
49   </listener>
50 
51   <!-- springMVC核心配置 -->
52   <servlet>
53     <servlet-name>dispatcherServlet</servlet-name>
54     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
55     <init-param>
56       <param-name>contextConfigLocation</param-name>
57       <!--spingMVC的配置路径 -->
58       <param-value>classpath:spring-mvc.xml</param-value>
59     </init-param>
60     <load-on-startup>1</load-on-startup>
61   </servlet>
62   <!-- 拦截设置 -->
63   <servlet-mapping>
64     <servlet-name>dispatcherServlet</servlet-name>
65     <url-pattern>/</url-pattern>
66   </servlet-mapping>
67 
68 
69   <welcome-file-list>
70     <welcome-file>index.jsp</welcome-file>
71   </welcome-file-list>
72 
73 </web-app>
View Code

applicationContext.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
 7 
 8     <!-- 提供方应用信息,用于计算依赖关系 -->
 9     <dubbo:application name="consumer" owner="user" organization="dubbox"  />
10     <!-- 使用zookeeper注册中心暴露服务地址 -->
11     <dubbo:registry check="false" address="zookeeper://localhost:2181" />
12     <!-- 使用dubbo协议调用定义好的api接口 -->
13     <dubbo:consumer check="false"/>
14     <!-- 使用dubbo协议调用定义好的api接口 -->
15     <dubbo:reference id="userService" interface="org.hanzx.service.UserService" check="false"/>
16     <context:component-scan base-package="org.hanzx.controller"/>
17 </beans>
View Code

logback.xml

技术分享图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <configuration>
  3     <!-- 尽量别用绝对路径,如果带参数不同容器路径解释可能不同,以下配置参数在pom.xml里 -->
  4     <property name="log.root.level" value="${log.root.level}" /> <!-- 日志级别 -->
  5     <property name="log.other.level" value="${log.other.level}" /> <!-- 其他日志级别 -->
  6     <property name="log.base" value="${log.base}" /> <!-- 日志路径,这里是相对路径,web项目eclipse下会输出到eclipse的安装目录下,如果部署到linux上的tomcat下,会输出到tomcat/bin目录 下 -->
  7     <property name="log.moduleName" value="${log.moduleName}" />  <!-- 模块名称, 影响日志配置名,日志文件名 -->
  8     <property name="log.max.size" value="100MB" /> <!-- 日志文件大小,超过这个大小将被压缩 -->
  9 
 10     <!--控制台输出 -->
 11     <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
 12         <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
 13             <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</Pattern>
 14         </encoder>
 15     </appender>
 16 
 17     <!-- 用来保存输出所有级别的日志 -->
 18     <appender name="file.all" class="ch.qos.logback.core.rolling.RollingFileAppender">
 19         <File>${log.base}/${log.moduleName}.log</File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果
 20             是web项目会保存到Tomcat的bin目录 下 -->
 21         <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。 -->
 22         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 23             <FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
 24             </FileNamePattern>
 25             <!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件备份) -->
 26             <timeBasedFileNamingAndTriggeringPolicy
 27                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 28                 <maxFileSize>${log.max.size}</maxFileSize>
 29             </timeBasedFileNamingAndTriggeringPolicy>
 30         </rollingPolicy>
 31         <!-- 日志输出的文件的格式 -->
 32         <layout class="ch.qos.logback.classic.PatternLayout">
 33             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</pattern>
 34         </layout>
 35     </appender>
 36 
 37     <!-- 这也是用来保存输出所有级别的日志 -->
 38     <appender name="file.all.other" class="ch.qos.logback.core.rolling.RollingFileAppender">
 39         <File>${log.base}/${log.moduleName}_other.log</File>
 40         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 41             <FileNamePattern>${log.base}/archive/${log.moduleName}_other_%d{yyyy-MM-dd}.%i.log.zip
 42             </FileNamePattern>
 43             <timeBasedFileNamingAndTriggeringPolicy
 44                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 45                 <maxFileSize>${log.max.size}</maxFileSize>
 46             </timeBasedFileNamingAndTriggeringPolicy>
 47         </rollingPolicy>
 48         <layout class="ch.qos.logback.classic.PatternLayout">
 49             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L -%msg%n</pattern>
 50         </layout>
 51     </appender>
 52 
 53     <!-- 只用保存输出error级别的日志 -->
 54     <appender name="file.error"
 55               class="ch.qos.logback.core.rolling.RollingFileAppender">
 56         <File>${log.base}/${log.moduleName}_err.log</File>
 57         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
 58             <FileNamePattern>${log.base}/archive/${log.moduleName}_err_%d{yyyy-MM-dd}.%i.log.zip
 59             </FileNamePattern>
 60             <timeBasedFileNamingAndTriggeringPolicy
 61                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
 62                 <maxFileSize>${log.max.size}</maxFileSize>
 63             </timeBasedFileNamingAndTriggeringPolicy>
 64         </rollingPolicy>
 65         <layout class="ch.qos.logback.classic.PatternLayout">
 66             <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L - %msg%n</pattern>
 67         </layout>
 68         <!-- 下面为配置只输出error级别的日志 -->
 69         <filter class="ch.qos.logback.classic.filter.LevelFilter">
 70             <level>ERROR</level>
 71             <onMatch>ACCEPT</onMatch>
 72             <onMismatch>DENY</onMismatch>
 73         </filter>
 74     </appender>
 75 
 76     <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
 77     <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
 78     <!-- 添加附加的appender,最多只能添加一个 -->
 79     <appender name="file.async" class="ch.qos.logback.classic.AsyncAppender">
 80         <discardingThreshold>0</discardingThreshold>
 81         <queueSize>256</queueSize>
 82         <includeCallerData>true</includeCallerData>
 83         <appender-ref ref="file.all" />
 84     </appender>
 85 
 86     <appender name="file.async.other" class="ch.qos.logback.classic.AsyncAppender">
 87         <discardingThreshold>0</discardingThreshold>
 88         <queueSize>256</queueSize>
 89         <includeCallerData>true</includeCallerData>
 90         <appender-ref ref="file.all.other" />
 91     </appender>
 92 
 93     <!-- 为某个包下的所有类的指定Appender 这里也可以指定类名称例如:com.aa.bb.ClassName -->
 94     <logger name="com.lin" additivity="false">
 95         <level value="${log.root.level}" />
 96         <appender-ref ref="stdout" />
 97         <appender-ref ref="file.async" /><!-- 即com.lin包下级别为 ${log.root.level}的才会使用file.async来打印 -->
 98         <appender-ref ref="file.error" />
 99     </logger>
100 
101     <!-- root将级别为${log.root.level}及大于${log.root.level}的日志信息交给已经配置好的名为“Console”的appender处理,“Console”appender将信息打印到Console,其它同理 -->
102     <root level="${log.root.level}">
103         <appender-ref ref="stdout" /> <!--  标识这个appender将会添加到这个logger -->
104         <appender-ref ref="file.async.other" />
105         <appender-ref ref="file.error" />
106     </root>
107 </configuration>
View Code

spring-mvc.xml

技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 7 
 8     <!-- 扫描controller(controller层注入) -->
 9     <context:component-scan base-package="org.hanzx.controller" use-default-filters="false">
10         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
11     </context:component-scan>
12 
13     <mvc:annotation-driven />
14 
15     <!-- 内容协商管理器  -->
16     <!--1、首先检查路径扩展名(如my.pdf);2、其次检查Parameter(如my?format=pdf);3、检查Accept Header-->
17     <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
18         <!-- 扩展名至mimeType的映射,即 /userEntity.json => application/json -->
19         <property name="favorPathExtension" value="true"/>
20         <!-- 用于开启 /userinfo/123?format=json 的支持 -->
21         <property name="favorParameter" value="true"/>
22         <property name="parameterName" value="format"/>
23         <!-- 是否忽略Accept Header -->
24         <property name="ignoreAcceptHeader" value="false"/>
25 
26         <property name="mediaTypes"> <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用  -->
27             <value>
28                 json=application/json
29                 xml=application/xml
30                 html=text/html
31             </value>
32         </property>
33         <!-- 默认的content type -->
34         <property name="defaultContentType" value="text/html"/>
35     </bean>
36 
37 
38     <!-- 当在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 -->
39     <mvc:default-servlet-handler />
40     <!-- 静态资源映射 -->
41     <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
42 
43 
44     <!-- 对模型视图添加前后缀 -->
45     <!--<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"-->
46           <!--p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>-->
47 
48     <bean id="templateResolver"
49           class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
50         <property name="prefix" value="/WEB-INF/templates/"/>
51         <property name="suffix" value=".html"/>
52         <property name="characterEncoding" value="UTF-8"/>
53         <property name="order" value="1"/>
54         <property name="templateMode" value="HTML5"/>
55         <property name="cacheable" value="false"/>
56     </bean>
57 
58     <bean id="templateEngine"
59           class="org.thymeleaf.spring5.SpringTemplateEngine">
60         <property name="templateResolver" ref="templateResolver"/>
61     </bean>
62 
63     <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
64         <property name="templateEngine" ref="templateEngine"/>
65         <property name="characterEncoding" value="UTF-8"/>
66     </bean>
67 
68     <!--拦截器 跨域拦截器-->
69     <mvc:interceptors>
70         <mvc:interceptor>
71             <mvc:mapping path="/**"/>
72             <mvc:exclude-mapping path="/WEB-INF/static/**" />
73             <bean class="org.hanzx.interceptors.CORSInterceptor" />
74         </mvc:interceptor>
75     </mvc:interceptors>
76 
77 
78 
79 </beans>
View Code

UserController

技术分享图片
 1 package org.hanzx.controller;
 2 
 3 import org.hanzx.model.UserModel;
 4 import org.hanzx.service.UserService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.ui.ModelMap;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestParam;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 @Controller
13 @RequestMapping("/user")
14 public class UserController {
15 
16     private final UserService userService;
17     private String prefix = "user/";
18 
19     @Autowired
20     public UserController(UserService userService) {
21         this.userService = userService;
22     }
23 
24 
25 
26 //    @RequestMapping(value="/getAllUser")
27 //    @ResponseBody
28 //    public List<UserModel> getAllUser(){
29 //        return userService.getAllUser();
30 //    }
31 //
32 //    @RequestMapping(value="/addUser")
33 //    @ResponseBody
34 //    public boolean addUser(UserModel userModel){
35 //        userService.addUser(userModel);
36 //        return true;
37 //    }
38 //
39 //    @RequestMapping(value="/updateUser")
40 //    @ResponseBody
41 //    public boolean updateUser(UserModel userModel){
42 //        userService.updateUser(userModel);
43 //        return true;
44 //    }
45 //
46 //    @RequestMapping(value="/deleteUser")
47 //    @ResponseBody
48 //    public boolean deleteUser(@RequestParam(value = "ids[]") Integer[] ids){
49 //        userService.deleteUser(ids);
50 //        return true;
51 //    }
52 
53 
54 //    @RequestMapping(value="/getUserListForm")
55 //    public String getUserListForm(){
56 //        return prefix + "user_list";
57 //    }
58 
59     @RequestMapping(value="/getAllUser")
60     public String getAllUser(ModelMap modelMap){
61         modelMap.put("userModelList", userService.getAllUser());
62         return prefix + "user_list";
63     }
64 
65     @RequestMapping(value="/getUserDetailForm")
66     public String getUserDetailForm(ModelMap modelMap, Integer id){
67         if (id != null){
68             modelMap.put("userModel", userService.getUserById(id));
69         }
70         return prefix + "user_detail";
71     }
72 
73     @RequestMapping(value="/addUser")
74     public String addUser(UserModel userModel){
75         userService.addUser(userModel);
76         return "redirect:getAllUser";
77     }
78 
79     @RequestMapping(value="/updateUser")
80     public String updateUser(UserModel userModel){
81         userService.updateUser(userModel);
82         return "redirect:getAllUser";
83     }
84 
85     @RequestMapping(value="/deleteUser")
86     @ResponseBody
87     public boolean deleteUser(@RequestParam(value = "ids[]") Integer[] ids){
88         userService.deleteUser(ids);
89         return true;
90     }
91 
92 
93 }
View Code

CORSInterceptor

技术分享图片
 1 package org.hanzx.interceptors;
 2 
 3 
 4 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 public class CORSInterceptor extends HandlerInterceptorAdapter {
10 
11     @Override
12     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
13         System.out.println("拦截请求: " + request.getServletPath());
14         response.setHeader("Access-Control-Allow-Origin", "*");
15         response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
16         response.setHeader("Access-Control-Max-Age", "0");
17         response.setHeader("Access-Control-Allow-Headers",
18                 "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
19         response.setHeader("Access-Control-Allow-Credentials", "true");
20         response.setHeader("XDomainRequestAllowed", "1");
21         return true;
22     }
23 }
View Code

user_list.html

技术分享图片
 1 <!DOCTYPE html>
 2 <html lang="cn" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>userEntityList</title>
 6     <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js" ></script>
 7     <script type="text/javascript">
 8         $(function () {
 9             //全选
10             $("#selectAll").click(function () {
11                 if (this.checked) {
12                     $("input[name=deleteId]").prop("checked", true);
13                 } else {
14                     $("input[name=deleteId]").prop("checked", false);
15                 }
16             });
17 
18             $("input[name=deleteId]").click(function () {
19                 var allChecked = true;
20                 $("input[name=deleteId]").each(function(){
21                     if(!$(this).prop("checked")){
22                         allChecked = false;
23                     }
24                 });
25                 if(allChecked){
26                     $("#selectAll").prop("checked",true);
27                 } else {
28                     $("#selectAll").prop("checked",false);
29                 }
30             });
31 
32             //删除用户
33             $("#delete").click(function () {
34                 var ids = [];
35                 $("input[name=deleteId]:checked").each(function(index){
36                     ids[index] = $(this).val();
37                 });
38                 if (ids.length === 0){
39                     alert("没有选中的选项");
40                     return false;
41                 }
42                 $.ajax({
43                     url : "deleteUser",
44                     data: {"ids": ids},
45                     cache : false,
46                     async : false,
47                     type : "GET",
48                     success:function(data){
49                         if (data === true){
50                             window.location.reload();
51                         }
52                     }
53                 });
54             });
55 
56         });
57 
58     </script>
59 </head>
60 <body>
61     <a th:href="getUserDetailForm">添加</a>
62     <a th:id="delete" href="#" >删除</a>
63     <table>
64         <tr>
65             <th><input th:type="checkbox" th:id="selectAll" title="点击全选/取消"/></th>
66             <th>用户名</th>
67             <th>年龄</th>
68             <th>操作</th>
69         </tr>
70         <tr th:each="userModel : ${userModelList}">
71             <td><input th:type="checkbox" th:value="${userModel.id}" th:name="deleteId"/></td>
72             <td th:text="${userModel.name}">abc</td>
73             <td th:text="${userModel.age}">15</td>
74             <td><a th:href="‘getUserDetailForm?id=‘ + ${userModel.id}">修改</a></td>
75         </tr>
76     </table>
77 </body>
78 </html>
View Code

user_detail.html

技术分享图片
 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <div th:if="${userModel} eq null">
 9         <form th:action="addUser" th:method="post">
10     </div>
11     <div th:if="${userModel} ne null">
12         <form th:action="updateUser" th:method="post">
13     </div>
14         <table>
15             <tr>
16                 <th>用户名</th>
17                 <td><input th:type="text" th:name="name" th:value="${userModel == null? ‘‘ : userModel.name}" th:title="请输入用户名"/></td>
18             </tr>
19             <tr>
20                 <th>密码</th>
21                 <td><input th:type="password" th:name="password" th:title="请输入密码"/></td>
22             </tr>
23             <tr>
24                 <th>年龄</th>
25                 <td><input th:type="number" th:name="age" th:value="${userModel == null? ‘‘ : userModel.age}" th:title="请输入年龄"/></td>
26             </tr>
27             <tr><td th:colspan="2" ><input th:type="submit" th:value="提交" /></td></tr>
28         </table>
29         <input th:type="hidden" th:name="id" th:value="${userModel == null? null : userModel.id}" />
30     </form>
31 </body>
32 </html>
View Code

 

运行结果

先启动zookeeper:双击 zookeeper文件夹/bin/zkServer.cmd

启动结果如下:

技术分享图片

然后直接启动provider的main方法(注意这里不使用tomcat),启动结果如下:

技术分享图片

使用tomcat启动consumer,结果如下:

技术分享图片

浏览器输入:http://localhost:8080/user/getAllUser,结果如下:

技术分享图片

 

参考资料

https://blog.csdn.net/weixin_37715446/article/details/78642052

https://blog.csdn.net/u013374645/article/details/81809576

SSM+dubbo+zookeeper实现基本的增删改查

标签:names   server   hang   lse   fun   初始   打开   sch   work   

原文地址:https://www.cnblogs.com/hanzx/p/10054429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!