账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何预处理controller中RequestMapping注解的方法的入参?将token转成user传入方法
    54
    0

    前端访问的请求头headers中携带了token,如何将token转成user传入我的这个方法中呢?
    如下是我想要的结果:
    User user就是token转成的user,

    @PostMapping("add")
    @ResponseBody
    public Comment commentAdd(@RequestBody CommentAddVO VO, User user) {
        Comment comment =  comRep.save(VO.toComment(user));
        //获取所有说说
        return comment;
    }
    

    应该怎么做呢?

    我现在的写法是弄了一个静态方法,获取当前请求中的token,再把token转成user通过方法返回,如下:

    public static String getUserName() {
        //获取到当前线程绑定的请求对象
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String cookieToken =CookieUtils.getCookie(request,"token");
        System.out.println("cookieToken:" + cookieToken);
    
        String headerToken = request.getHeader("token");
        System.out.println("headerToken:" + headerToken);
        return headerToken;
    }
    

    但我觉得这样不如直接将 token转成user放到方法入参中简单,所以想请教一下怎么做比较好

    或者如何将头请求放到方法入参中?

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 宇智波可达鸭 普通会员 1楼

      在Spring MVC中,@RequestMapping注解的入参是一个带有泛型的数组。为了将token转成user传入方法,你需要首先将token转换为用户对象,然后使用这个用户对象作为参数传递给@RequestMapping注解的方法。

      以下是一个简单的示例:

      ```java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;

      @Controller public class TokenController {

      @GetMapping("/token")
      public User token(@RequestParam("token") String token) {
          // 使用token来创建一个用户对象
          User user = new User(token);
      
          // 将用户对象作为参数传递给@RequestMapping方法
          return new ResponseEntity<>(user, HttpStatus.OK);
      }
      

      } ```

      在这个示例中,我们首先创建了一个带有token的用户对象。然后,我们将这个用户对象作为参数传递给@RequestMapping方法,并返回一个包含用户对象的ResponseEntity

      注意,这只是一个基本的示例,实际的代码可能会更复杂,因为实际的令牌可能包含更多的信息,如用户的角色等。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部