Request在控制器中获取另一个方法(SpringBoot)

时间:2018-03-20 15:41:39

标签: java spring-boot cors

我在控制器中有2个方法:

@RestController("/api/v1/users")
public class UserController {


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public List<User> getUserByEmailAndPassword(@RequestParam("email") String email, @RequestParam("password") String password) {
        logger.info("Request to get user with email and password: " + email + password);
        User user = userService.checkUserByEmailAndPassword(email, password);
        return user != null ? Collections.singletonList(user) : Collections.emptyList();
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<UserDto> getUserByEmail(@RequestParam("email") String email) {
        logger.info("Request to get user with email: " + email);
        UserDto userDto = userService.checkUserEmail(email);
        return userDto != null ? Collections.singletonList(userDto) : Collections.emptyList();
    }
}

CORS配置:

@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

当我向http://localhost:9092/api/v1/users/login?email=art&password=1037006322

发送请求时

我调用此方法 getUserByEmail

怎么可能? 如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

以这种方式映射。它将按照您的要求工作。使用@RequestMapping而不是@RestController映射您的网址模式。

@RestController
@RequestMapping("/api/v1/users")
public class UserController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public List<User> getUserByEmailAndPassword(@RequestParam("email") String email, @RequestParam("password") String password) {
        logger.info("Request to get user with email and password: " + email + password);
        User user = userService.checkUserByEmailAndPassword(email, password);
        return user != null ? Collections.singletonList(user) : Collections.emptyList();
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<UserDto> getUserByEmail(@RequestParam("email") String email) {
        logger.info("Request to get user with email: " + email);
        UserDto userDto = userService.checkUserEmail(email);
        return userDto != null ? Collections.singletonList(userDto) : Collections.emptyList();
    }

 }