使用spring-boot实现的rest接口抛出异常时,页面显示中文乱码解决

代码:

    @CrossOrigin
    @RestController
    @RequestMapping(“api”)
    public class RestAPI {    

        @GetMapping(“/exception”)
            public int exception() throws Exception{
                    throw new Exception(“中文乱码”);
            }
    }

现象:

    

解决步骤:

     1.使用chrome的开发人员工具,发现如下图中红框部分县市,charset设置不当,应为utf-8

     

    2.创建类继承HandlerExceptionResolver接口,在接口中进行charset的重新设置,代码如下

    @Component
    public class AExceptionHandler implements HandlerExceptionResolver {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                    response.setCharacterEncoding(“utf-8”);
                    return null;
            }
    }

    备注:@Component注解时必须的,这样,才能保证在启动时,扩展的AExceptionHandler类被成功加载

    3.解决之后的现象

    

作者:掠燕翔云

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现 API 接口合并可以通过 Spring Boot 中的 Feign 和 Ribbon 组件来实现。具体步骤如下: 1. 在 pom.xml 中添加依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> ``` 2. 创建一个 Feign 接口,用于调用需要合并的 API 接口: ``` @FeignClient(name = "service-name") public interface ApiService { @GetMapping("/api/path") String getData(); } ``` 3. 在 Spring Boot 启动类中添加 @EnableFeignClients 和 @RibbonClients 注解: ``` @SpringBootApplication @EnableFeignClients @RibbonClients(defaultConfiguration = RibbonConfiguration.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 4. 创建一个 Ribbon 配置类,用于配置负载均衡策略: ``` @Configuration public class RibbonConfiguration { @Bean public IRule ribbonRule() { // 配置负载均衡策略 return new RandomRule(); } } ``` 5. 创建一个自定义的 API 接口,用于合并多个 API 接口: ``` @RestController @RequestMapping("/api") public class CombinedApiController { @Autowired private ApiService apiService; @GetMapping("/combined") public List<String> getDataFromMultipleApis() { List<String> result = new ArrayList<>(); result.add(apiService.getData()); // 调用其他需要合并的接口并将结果加入到 result 中 return result; } } ``` 通过以上步骤,就可以实现 API 接口的合并。在 CombinedApiController 中,通过调用 ApiService 中的接口来获取数据,然后将多个接口返回的数据合并在一起返回给客户端。同,通过 Ribbon 配置负载均衡策略,可以实现对多个 API 服务的负载均衡。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值