栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 官方文档示例:(49)使用路由函数取代RequestMapping来做路由映射

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 官方文档示例:(49)使用路由函数取代RequestMapping来做路由映射

一、定义业务逻辑处理方法:

package com.example.handler;

import com.example.domain.Teacher;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;

@Service
public class MyUserHandler {
    public ServerResponse getUser(ServerRequest request){
        String name=request.pathVariable("name");
        String age=request.pathVariable("age");
        Teacher teacher=new Teacher(name,Integer.parseInt(age));
        return ServerResponse.ok().body(teacher);
    }
}

二、定义路由函数,配置Http请求地址和业务逻辑方法之间的映射

package com.example.config;

import com.example.handler.MyUserHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.function.RequestPredicate;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.ServerResponse;
import static org.springframework.web.servlet.function.RequestPredicates.accept;
import static org.springframework.web.servlet.function.RouterFunctions.route;
@Configuration(proxyBeanMethods = false)
public class MyRoutingConfiguration {
    private static final RequestPredicate ACCEPT_JSON =
            accept(MediaType.APPLICATION_JSON);
    @Bean
    public RouterFunction routerFunction(MyUserHandler userHandler) {
        return route()
                .GET("/myRoute/{name}/{age}", ACCEPT_JSON, userHandler::getUser)
                //.GET("/{user}/customers", ACCEPT_JSON, userHandler::getUserCustomers)
                //.DELETE("/{user}", ACCEPT_JSON, userHandler::deleteUser)
                .build();
    }
}

三、启动Spring Boot程序进行测试,结果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953303.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号