基于idea的springcloud的helloworld项目搭建过程整理

Springcloud的搭建主要包括三个部分:服务注册中心、服务提供者、服务消费者。每一个部分都是一个springboot项目,它们通过配置文件(application.properties或application.yml)关联在一起。

一、创建服务注册中心

1、 按照如下过程依次操作

2、 在application.properties中填写如下内容,声明本服务是一个注册中心

server.port:7770
eureka.instance.hostname:localhost
#一下两行表明本服务是一个注册中心,而非服务提供或者消费方
eureka.client.registerWithEureka: false
eureka.client.fetchRegistry
: false
#服务注册到哪里
eureka.client.serviceUrl.defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
#本服务的名称
spring.application.name: eurka-server

3、 在启动类上面添加@EnableEurekaServer注解即可

4、 启动服务即可,注意服务端口是application.properties中配置的server.port

二、创建服务提供者

1、 类似注册中心创建springboot,只是以下这个地方有些不同。

2、 在application.properties中进行注册信息的配置

#本服务端口号
server.port: 7771
#本服务名
spring.application.name: hello-springcloud-service
#注册中心的地址
eureka.client.serviceUrl.defaultZone: http://localhost:7770/eureka/

注:服务名可以重复,会认为是同一个服务,负载均衡使用

3、 在启动类上面添加@EnableEurekaClient注解

4、 创建VO,用于接收参数

1) VO类的属性名要与参数名完全一致

2) 提供setter/getter方法

3) Get和Post接收的vo不要共用一个,最好分着设计

5、 创建Controller

1) 本质上就是ssh中创建controller一样,注解使用@RestController

2) 写出这个请求是get还是post请求

3) 返回值类型可以是字符串或者map、List等类型都是可以的

4) 参数注意事项

A) 如果是get请求,可以使用VO这个pojo类接收,也可以通过“类型 参数名”这种方式接收(普通类型的参数接收而已)。

最正规的方式是:@RequestParam(“参数名”) 类型 参数名这种方式。

B) 如果是post请求,必须使用VO这个pojo类的方式接收,由于传递的是json字符串,所以必须使用@RequestBody修饰。而且,只能有一个@RequestBody

例如:@RequestBody PoJo类 pojo类的对象

此外,如果请求中除了一个json字符串以外,还有其他参数,那么json字符串用@RequestBody的方式接收,而其余参数参考get的方式接收即可。

5) 该Controller不仅可以作为其他服务的提供者,也可以直接通过前端请求。只是注意post请求的特殊处理。

package com.lennar.serviceprovider.controller;

import com.lennar.serviceprovider.vo.GetVO;
import com.lennar.serviceprovider.vo.HelloWorldTestVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MyController {

    @Value("${server.port}")
    String port;//负载均衡的时候便于打印识别是哪个服务(端口不同,服务不同)

    //1.get请求
    //1.1.返回字符串
    @RequestMapping(value = "/test/getMethod1", method = RequestMethod.GET)
    public String getMethod1(GetVO getVO) {
        return "get-字符串(RequestMapping):hello " + getVO.getStudentName() + " ,I am from port:" + port;
    }

//    public String getMethod1(@RequestParam(value = "studentName") String name) {
//        return "get-字符串(RequestMapping):hello " + name + " ,I am from port:" + port;
//    }

    @GetMapping(value = "/test/getMethod2")
    public String getMethod2(@RequestParam(value = "studentName") String name) {
        return "get-字符串(GetMapping):hello " + name + " ,I am from port:" + port;
    }

    //1.2.返回Map
    @RequestMapping(value = "/test/getMethod3", method = RequestMethod.GET)
    public Map<String, Object> getMethod3(@RequestParam(value = "studentName") String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("resultMessage", "get-Map(RequestMapping):hello " + name + " ,I am from port:" + port);
        return map;
    }

    @GetMapping(value = "/test/getMethod4")
    public Map<String, Object> getMethod4(@RequestParam(value = "studentName") String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("resultMessage", "get-Map(GetMapping):hello " + name + " ,I am from port:" + port);
        return map;
    }

    //2.post请求
    //2.1.返回字符串
    @RequestMapping(value = "/test/postMethod1", method = RequestMethod.POST)
    public String postMethod1(GetVO getVO, @RequestBody HelloWorldTestVO helloWorldTestVO) {
        return "post-字符串(RequestMapping):hello " + helloWorldTestVO.getName() + "(" + helloWorldTestVO.getAge() + ")" + "your score is " + getVO.getStudentScore() + " ,I'm from port:" + port;
    }
//    @RequestMapping(value = "/test/postMethod1", method = RequestMethod.POST)
//    public String postMethod1(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO) {
//        return "post-字符串(RequestMapping):hello " + helloWorldTestVO.getName() + "(" + helloWorldTestVO.getAge() + ")" + "your score is " + score + " ,I'm from port:" + port;
//    }

    @PostMapping(value = "/test/postMethod2")
    public List<String> postMethod2(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO) {
        List<String> list = new ArrayList<>();
        list.add("post-字符串(PostMapping):hello " + helloWorldTestVO.getName() + "(" + helloWorldTestVO.getAge() + ")" + "your score is " + score + " ,I'm from port:" + port);
        return list;

    }

    //1.2.返回Map
    @RequestMapping(value = "/test/postMethod3", method = RequestMethod.POST)
    public Map<String, Object> postMethod3(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("resultMessage", "post-map(RequestMapping):hello " + helloWorldTestVO.getName() + "(" + helloWorldTestVO.getAge() + ")" + "your score is " + score + " ,I'm from port:" + port);
        return map;
    }

    @PostMapping(value = "/test/postMethod4")
    public Map<String, Object> postMethod4(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO) {
        Map<String, Object> map = new HashMap<>();
        map.put("resultMessage", "post-map(PostMapping):hello " + helloWorldTestVO.getName() + "(" + helloWorldTestVO.getAge() + ")" + "your score is " + score + " ,I'm from port:" + port);
        return map;
    }
}

6、 启动即可(前提:注册中心处于开启状态)

注:为了实现负载均衡的集群效果,可以修改端口,多启动几个项目。

可以参考:https://blog.csdn.net/forezp/article/details/76408139

三、创建服务消费者(使用@Feign版本)

1、 创建项目与二中一样

 2、 在application.properties中添加如下内容,以便消费服务

#注册中心的地址
eureka.client.serviceUrl.defaultZone: http://localhost:7770/eureka/
#本服务的端口
server.port: 7772
#服务名
spring.application.name: service-consumer-feign


#调用集群的时候需要设置超时时间,否则可能无法连接成功或者无法正常返回数据
#程序会报nested exception is feign.RetryableException: connect timed out executing POST类似的超时错误
#请求连接的超时时间(单位:毫秒)
ribbon.ConnectTimeout: 30000
#请求处理的超时时间(单位:毫秒)
ribbon.ReadTimeout: 120000

3、 在启动类上添加注解@EnableEurekaClient、@EnableDiscoveryClient、@EnableFeignClients

4、 创建VO,路径不需要和服务提供者完全一样,只需要保证参数名一致即可。主要用于调用服务时传递参数(尤其是post请求)

5、 创建service层接口即可,主要用于调用服务提供者。服务提供者接口处如何编写调用规则(mapping类型、请求方式、参数格式以及返回类型等),这里就如何调用和编写接口。

package com.lennar.service;

import com.lennar.serviceconsumer.HelloWorldTestVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

//value中为服务名
//FeignClient内部封装了ribbon,可以负载均衡
@FeignClient(value = "hello-springcloud-service")//value就是服务提供者的服务名称,在服务提供者的application.properties中设置
public interface FeignService {

    //1.get请求
    //1.1.返回字符串
    @RequestMapping(value = "/test/getMethod1", method = RequestMethod.GET)
    String myGetQuery1(@RequestParam(value = "studentName") String myName);

    @GetMapping(value = "/test/getMethod1")
    String myGetQuery2(@RequestParam(value = "studentName") String myName);

    @RequestMapping(value = "/test/getMethod2", method = RequestMethod.GET)
    String myGetQuery3(@RequestParam(value = "studentName") String myName);

    @GetMapping(value = "/test/getMethod2")
    String myGetQuery4(@RequestParam(value = "studentName") String myName);

    //1.2.返回map
    @RequestMapping(value = "/test/getMethod3", method = RequestMethod.GET)
    Map<String, Object> myGetQuery5(@RequestParam(value = "studentName") String myName);

    @GetMapping(value = "/test/getMethod3")
    Map<String, Object> myGetQuery6(@RequestParam(value = "studentName") String myName);

    @RequestMapping(value = "/test/getMethod4", method = RequestMethod.GET)
    Map<String, Object> myGetQuery7(@RequestParam(value = "studentName") String myName);

    @GetMapping(value = "/test/getMethod4")
    Map<String, Object> myGetQuery8(@RequestParam(value = "studentName") String myName);

    //2.post请求
    //2.1.返回字符串
    @RequestMapping(value = "/test/postMethod1", method = RequestMethod.POST)
    String myPostQuery1(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @PostMapping(value = "/test/postMethod1")
    String myPostQuery2(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @RequestMapping(value = "/test/postMethod2", method = RequestMethod.POST)
    List<String> myPostQuery3(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @PostMapping(value = "/test/postMethod2")
    List<String> myPostQuery4(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    //2.2.返回map
    @RequestMapping(value = "/test/postMethod3", method = RequestMethod.POST)
    Map<String, Object> myPostQuery5(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @PostMapping(value = "/test/postMethod3")
    Map<String, Object> myPostQuery6(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @RequestMapping(value = "/test/postMethod4", method = RequestMethod.POST)
    Map<String, Object> myPostQuery7(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);

    @PostMapping(value = "/test/postMethod4")
    Map<String, Object> myPostQuery8(@RequestParam(value = "studentScore") String score, @RequestBody HelloWorldTestVO helloWorldTestVO);
}

6、 创建Controller,就是前端调用的Controller,Controller中的方法调用5中的Service接口的方法,进而调用服务提供者的方法。

package com.lennar.controller;

import com.lennar.service.FeignService;
import com.lennar.serviceconsumer.HelloWorldTestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class MyController {

    @Autowired
    FeignService feignService;

    //1.get请求
    @GetMapping("/hello1")
    public String sayGetHello1(@RequestParam("name") String name) {
        return feignService.myGetQuery1(name);
    }

    @GetMapping("/hello2")
    public String sayGetHello2(@RequestParam("name") String name) {
        return feignService.myGetQuery2(name);
    }

    @GetMapping("/hello3")
    public String sayGetHello3(@RequestParam("name") String name) {
        return feignService.myGetQuery3(name);
    }

    @GetMapping("/hello4")
    public String sayGetHello4(@RequestParam("name") String name) {
        return feignService.myGetQuery4(name);
    }

    @GetMapping("/hello5")
    public Map<String, Object> sayGetHello5(@RequestParam("name") String name) {
        return feignService.myGetQuery5(name);
    }

    @GetMapping("/hello6")
    public Map<String, Object> sayGetHello6(@RequestParam("name") String name) {
        return feignService.myGetQuery6(name);
    }

    @GetMapping("/hello7")
    public Map<String, Object> sayGetHello7(@RequestParam("name") String name) {
        return feignService.myGetQuery7(name);
    }

    @GetMapping("/hello8")
    public Map<String, Object> sayGetHello8(@RequestParam("name") String name) {
        return feignService.myGetQuery8(name);
    }

    //2.post请求
    @PostMapping(value = "/hello1")
    public String sayPostHello1(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery1(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello2")
    public String sayPostHello2(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery2(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello3")
    public List<String> sayPostHello3(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery3(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello4")
    public List<String> sayPostHello4(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery4(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello5")
    public Map<String, Object> sayPostHello5(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery5(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello6")
    public Map<String, Object> sayPostHello6(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery6(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello7")
    public Map<String, Object> sayPostHello7(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery7(score, helloWorldTestVO);
    }

    @PostMapping(value = "/hello8")
    public Map<String, Object> sayPostHello8(String name, String age, String score) {
        HelloWorldTestVO helloWorldTestVO = new HelloWorldTestVO();
        helloWorldTestVO.setName(name);
        helloWorldTestVO.setAge(age);
        return feignService.myPostQuery8(score, helloWorldTestVO);
    }

}

7、 启动即可

注:消费者只会调用服务提供者已经注册(先于消费者打开服务前已经在注册中心注册过的)且处于打开状态的服务。

四、创建前端调用项目(以AJAX为例)

1、 保证谷歌浏览器跨域,并且使用该浏览器打开前端服务。

https://jingyan.baidu.com/article/148a1921c9dbf24d71c3b11f.html

2、 编写前端代码即可

 修改pom文件中的properties和dependencies

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.7</maven.compiler.source>
  <maven.compiler.target>1.7</maven.compiler.target>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.version>4.1.4.RELEASE</spring.version>
  <hibernate.version>4.3.8.Final</hibernate.version>
  <jackson.version>2.5.0</jackson.version>
</properties>

<dependencies>
  <!-- junit -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <!-- spring -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>

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

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

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

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

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>

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

  <!-- 使用SpringMVC需配置 -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <!-- hibernate -->
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate.version}</version>
  </dependency>

  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>${hibernate.version}</version>
  </dependency>

  <!-- 二级缓存ehcache -->
  <dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.9.0</version>
  </dependency>

  <!-- log4j -->
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.14</version>
  </dependency>

  <!--postgresql-->
  <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.2</version>
  </dependency>
  <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2.2</version>
  </dependency>

  <!-- mysql连接 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.34</version>
  </dependency>

  <!--oracle-->
  <dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
  </dependency>

  <!-- c3p0数据源 -->
  <dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5-pre10</version>
  </dependency>

  <!-- json -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.3</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${jackson.version}</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${jackson.version}</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>

  <!-- aop -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.4</version>
  </dependency>
  <!-- servlet -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0-alpha-1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
  </dependency>
  <dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
  </dependency>
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.7</version>
  </dependency>
  <dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
  </dependency>
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
  </dependency>
  <!--用于保证jsp中基本api使用,比如request的方法等-->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
  </dependency>
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
  </dependency>

</dependencies>

修改web.xml(将原来的web.xml覆盖即可)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         id="WebApp_ID" version="3.1">
  <!--<context-param>-->
    <!--<param-name>contextConfigLocation</param-name>-->
    <!--<param-value>classpath:spring.xml</param-value>-->
  <!--</context-param>-->

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

  <!--<servlet>-->
    <!--<servlet-name>springDispatcherServlet</servlet-name>-->
    <!--<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>-->
    <!--<init-param>-->
      <!--<param-name>contextConfigLocation</param-name>-->
      <!--<param-value>classpath:springmvc.xml</param-value>-->
    <!--</init-param>-->
    <!--<load-on-startup>1</load-on-startup>-->
  <!--</servlet>-->

  <!--<servlet-mapping>-->
    <!--<servlet-name>springDispatcherServlet</servlet-name>-->
    <!--<url-pattern>*.action</url-pattern>-->
  <!--</servlet-mapping>-->

  <!--springmvc中文乱码-->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>  <!--字符的编码格式 -->
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>  <!--强制使用Encoding设置的编码格式-->
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

添加jquery.js并在index.jsp中导入

(index.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<
head>
    <
title>首界面</title>
    <
style>
    </
style>
</
head>
<
body>
<
hr>
<
hr>
<
div id="testDivId"></div>
<
hr>
<
hr>
<
div><font color="red">向消费者发出请求</font></div>
<
button class="testGet" id="testGetBtnId1">testGet1</button>
<
button class="testGet" id="testGetBtnId2">testGet2</button>
<
button class="testGet" id="testGetBtnId3">testGet3</button>
<
button class="testGet" id="testGetBtnId4">testGet4</button>
<
button class="testGet" id="testGetBtnId5">testGet5</button>
<
button class="testGet" id="testGetBtnId6">testGet6</button>
<
button class="testGet" id="testGetBtnId7">testGet7</button>
<
button class="testGet" id="testGetBtnId8">testGet8</button>
<
br>
<
br>
<
br>
<
button class="testPost" id="testPostBtnId1">testPost1</button>
<
button class="testPost" id="testPostBtnId2">testPost2</button>
<
button class="testPost" id="testPostBtnId3">testPost3</button>
<
button class="testPost" id="testPostBtnId4">testPost4</button>
<
button class="testPost" id="testPostBtnId5">testPost5</button>
<
button class="testPost" id="testPostBtnId6">testPost6</button>
<
button class="testPost" id="testPostBtnId7">testPost7</button>
<
button class="testPost" id="testPostBtnId8">testPost8</button>
<
br>
<
hr>
<
hr>
<
div><font color="red">向提供者发出请求</font></div>
<
button class="testProviderGet" id="testProviderGet1">testProviderGet1</button>
<
button class="testProviderGet" id="testProviderGet2">testProviderGet2</button>
<
button class="testProviderGet" id="testProviderGet3">testProviderGet3</button>
<
button class="testProviderGet" id="testProviderGet4">testProviderGet4</button>
<
br>
<
br>
<
br>
<
button class="testProviderPost" id="testProviderPost1">testProviderPost1</button>
<
button class="testProviderPost" id="testProviderPost2">testProviderPost2</button>
<
button class="testProviderPost" id="testProviderPost3">testProviderPost3</button>
<
button class="testProviderPost" id="testProviderPost4">testProviderPost4</button>
<
script>
   
var contextPath = "${pageContext.request.contextPath}";
</
script>
<
script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<
script src="${pageContext.request.contextPath}/js/myTestJS.js"></script>
</
body>
</
html>

(myTestJS.js文件)

$(function () {
    //向消费者发送请求,进而消费者调用服务者的服务,提供数据
    $(".testGet").on("click", function () {
        var flag = $(this).text().split("testGet")[1];
        $.ajax({
            url: "http://10.17.66.19:7772/hello" + flag,
            data: {name: "张三"},
            type: "GET",
            success: function (res) {
                if (Number(flag) > 4) {
                    $("#testDivId").html(res.resultMessage);
                } else {
                    $("#testDivId").html(res);
                }
            }
        });
    });

    $(".testPost").on("click", function () {
        var flag = $(this).text().split("testPost")[1];
        $.ajax({
            url: "http://10.17.66.19:7772/hello" + flag,
            data: {name: "王五", age: "24", score: "110"},
            type: "POST",
            success: function (res) {
                if (Number(flag) > 4) {
                    $("#testDivId").html(res.resultMessage);
                } else {
                    $("#testDivId").html(res);
                }
            }
        });
    });

    //直接向服务提供者发送请求
    //只是post请求中,如果有@RequestParam,则需要将参数放在请求头部,而@RequestBody修饰的内容放在data的json字符串中,且设置contentType: "application/json"
    $(".testProviderGet").on("click", function () {
        var flag = $(this).text().split("testProviderGet")[1];
        $.ajax({
            url: "http://10.17.66.19:7771/test/getMethod" + flag,
            data: {studentName: "李四"},
            type: "GET",
            success: function (res) {
                if (Number(flag) > 2) {
                    $("#testDivId").html(res.resultMessage);
                } else {
                    $("#testDivId").html(res);
                }
            }
        });
    });

    $(".testProviderPost").on("click", function () {
        var flag = $(this).text().split("testProviderPost")[1];
        $.ajax({
            url: "http://10.17.66.19:7771/test/postMethod" + flag + "?studentScore=120",
            data: JSON.stringify({name: "王五", age: "24"}),
            type: "POST",
            contentType: "application/json",
            success: function (res) {
                if (Number(flag) > 2) {
                    $("#testDivId").html(res.resultMessage);
                } else {
                    $("#testDivId").html(res);
                }
            }
        });
    });
});

3、 配置一个Tomcat,启动项目,使用跨域的谷歌浏览器测试即可

五、注意事项

1、 通过idea创建项目的时候,https://start.spring.io很有可能不能使用,这个时候,通过点击一下,在浏览器中打开一次,然后回到idea,再试一试。

2、 可以直接到https://start.spring.io中去创建项目。对于注册中心只需要Eureka Server;对于服务提供者需要web和Eureka Discovery;对于服务消费者需要web、Eureka Discovery和Feign。

猜你喜欢

转载自www.cnblogs.com/lennar/p/10430648.html
今日推荐