在spring Controller中返回自定义的Http code

7 篇文章 0 订阅
3 篇文章 0 订阅

怎么在Spring Controller里面返回404

SEP 27TH2014 6:02 PM

由于大多的客户端和服务端是独立的(可能用不同语言编写),客户端无法获知服务端的异常,所以普通的异常处理并不足以提示客户端。而基于HTTP协议的服务,我们则需要按照服务端的异常而返回特定的状态码给客户端。

以返回404状态码为例,在Spring 的Controller里面我们可以有以下3种方式处理:

  1. 自定义异常+@ResponseStatus注解:

     //定义一个自定义异常,抛出时返回状态码404
     @ResponseStatus(value = HttpStatus.NOT_FOUND)
     public class ResourceNotFoundException extends RuntimeException {
         ...
     }
    
     //在Controller里面直接抛出这个异常
     @Controller
     public class SomeController {
         @RequestMapping(value="/video/{id}",method=RequestMethod.GET)
         public @ResponseBody Video getVidoeById(@PathVariable long id){
             if (isFound()) {
                 // 做该做的逻辑
             }
             else {
                 throw new ResourceNotFoundException();//把这个异常抛出 
             }
         }
     }
    
  2. 使用Spring的内置异常

    默认情况下,Spring 的DispatcherServlet注册了DefaultHandlerExceptionResolver,这个resolver会处理标准的Spring MVC异常来表示特定的状态码

      Exception                                   HTTP Status Code
      ConversionNotSupportedException             500 (Internal Server Error)
      HttpMediaTypeNotAcceptableException         406 (Not Acceptable)
      HttpMediaTypeNotSupportedException          415 (Unsupported Media Type)
      HttpMessageNotReadableException             400 (Bad Request)
      HttpMessageNotWritableException             500 (Internal Server Error)
      HttpRequestMethodNotSupportedException      405 (Method Not Allowed)
      MissingServletRequestParameterException     400 (Bad Request)
      NoSuchRequestHandlingMethodException        404 (Not Found)
      TypeMismatchException                       400 (Bad Request)
    
  3. 在Controller方法中通过HttpServletResponse参数直接设值

     //任何一个RequestMapping 的函数都可以接受一个HttpServletResponse类型的参数
     @Controller
     public class SomeController {
         @RequestMapping(value="/video/{id}",method=RequestMethod.GET)
         public @ResponseBody Video getVidoeById(@PathVariable long id ,HttpServletResponse response){
             if (isFound()) {
                 // 做该做的逻辑
             }
             else {
                 response.setStatus(HttpServletResponse.SC_NOT_FOUND);//设置状态码
             }
             return ....
         }
     }

转载地址:http://jaskey.github.io/blog/2014/09/27/how-to-return-404-in-spring-controller/

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现自定义短信验证码登录,可以按照以下步骤进行: 1. 添加依赖 在项目添加 Spring Security 和 Spring Security SMS 模块的依赖。 ``` <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>5.2.2.RELEASE</version> </dependency> <dependency> <groupId>com.github.lanceshohara</groupId> <artifactId>spring-security-sms</artifactId> <version>1.0.2</version> </dependency> ``` 2. 配置 Spring Security 在 Spring Security 配置文件添加配置,包括短信验证码登录相关的配置。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login/sms").permitAll() .anyRequest().authenticated() .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login/form") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 其,`SmsCodeAuthenticationSecurityConfig` 是短信验证码登录的相关配置类,需要单独实现。 3. 实现短信验证码登录相关配置 实现 `SmsCodeAuthenticationSecurityConfig` 配置类,其包括一个短信验证码过滤器和一个短信验证码认证提供者。 ``` @Configuration public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private UserDetailsService userDetailsService; @Autowired private SmsCodeAuthenticationSuccessHandler smsCodeAuthenticationSuccessHandler; @Autowired private SmsCodeAuthenticationFailureHandler smsCodeAuthenticationFailureHandler; @Override public void configure(HttpSecurity http) throws Exception { SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(smsCodeAuthenticationSuccessHandler); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(smsCodeAuthenticationFailureHandler); SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService); http.authenticationProvider(smsCodeAuthenticationProvider) .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 其,`SmsCodeAuthenticationFilter` 是短信验证码过滤器,需要单独实现。`SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 分别是短信验证码认证成功和失败的处理器,也需要单独实现。 4. 实现短信验证码过滤器 实现 `SmsCodeAuthenticationFilter` 过滤器,重写 `attemptAuthentication` 方法,来处理短信验证码认证请求。 ``` public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; public static final String SPRING_SECURITY_FORM_CODE_KEY = "code"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY; private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY; private boolean postOnly = true; public SmsCodeAuthenticationFilter() { super(new AntPathRequestMatcher("/login/sms", "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } String mobile = obtainMobile(request); String code = obtainCode(request); if (mobile == null) { mobile = ""; } if (code == null) { code = ""; } mobile = mobile.trim(); SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile, code); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected String obtainCode(HttpServletRequest request) { return request.getParameter(codeParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String mobileParameter) { this.mobileParameter = mobileParameter; } public void setCodeParameter(String codeParameter) { this.codeParameter = codeParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; } public final String getCodeParameter() { return codeParameter; } } ``` 其,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 5. 实现短信验证码认证提供者 实现 `SmsCodeAuthenticationProvider` 提供者,重写 `authenticate` 方法,来进行短信验证码认证。 ``` public class SmsCodeAuthenticationProvider implements AuthenticationProvider { private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; UserDetails userDetails = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } public UserDetailsService getUserDetailsService() { return userDetailsService; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } } ``` 6. 实现短信验证码认证成功和失败的处理器 实现 `SmsCodeAuthenticationSuccessHandler` 和 `SmsCodeAuthenticationFailureHandler` 处理器,来处理短信验证码认证成功和失败的情况。 ``` public class SmsCodeAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { super.onAuthenticationSuccess(request, response, authentication); } } ``` ``` public class SmsCodeAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { super.onAuthenticationFailure(request, response, exception); } } ``` 7. 编写控制器 编写控制器,处理短信验证码登录的请求。 ``` @Controller public class LoginController { private final static String SMS_LOGIN_PAGE = "sms-login"; @RequestMapping("/login/sms") public String smsLogin() { return SMS_LOGIN_PAGE; } @RequestMapping(value = "/login/sms", method = RequestMethod.POST) public void smsLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String mobile = request.getParameter("mobile"); String code = request.getParameter("code"); SmsCodeAuthenticationToken token = new SmsCodeAuthenticationToken(mobile, code); AuthenticationManager authenticationManager = new ProviderManager(Collections.singletonList(new SmsCodeAuthenticationProvider())); Authentication authentication = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); request.getRequestDispatcher("/").forward(request, response); } } ``` 其,`SmsCodeAuthenticationToken` 是短信验证码认证的 token 类型,需要单独实现。 以上就是实现自定义短信验证码登录的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值