zoukankan      html  css  js  c++  java
  • spring boot获取request

    1. Controller中

    1.1 通过静态方法获取

    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    
    

    但我在使用过程中发现遇到了一个警告

    Method invocation 'getRequest' may produce 'java.lang.NullPointerException' less... (Ctrl+F1)
    Inspection info: This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
    Variables, method parameters and return values marked as @Nullable or @NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
    More complex contracts can be defined using @Contract annotation, for example:
    @Contract(", null -> null") — method returns null if its second argument is null @Contract(", null -> null; _, !null -> !null") — method returns null if its second argument is null and not-null otherwise @Contract("true -> fail") — a typical assertFalse method which throws an exception if true is passed to it
    The inspection can be configured to use custom @Nullable
    @NotNull annotations (by default the ones from annotations.jar will be used)

    如此使用可能会造成空指针异常,所以建议添加Objects.requireNonNull,如果为空,抛出异常。

    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    
    

    附Objects.requireNonNull源码

    public static <T> T requireNonNull(T obj) {
            if (obj == null)
                throw new NullPointerException();
            return obj;
        }
    

    1.2 通过参数直接获取

    在参数上添加后,springboot会帮你绑定,之后可以直接使用

    @GetMapping(value = "")
    public String center(HttpServletRequest request,HttpServletResponse response) {
        //...
    }
    

    1.3 自动注入

    通过@Autowired自动注入,这样就不用每个方法都写了

    @Autowired
    private HttpServletRequest request;
     
    @Autowired
    private HttpServletResponse response;
     
    @GetMapping(value = "")
    public String center() {
        //...
    }
    

    2.controller以外部分

    见1.1

  • 相关阅读:
    Create Ubuntu DEB package from a Qt application
    Packaging a Qt application
    Ubuntu下安装Eclipse+QT我尽量让它详细点
    Mosh: the mobile shell
    PySide: Python for Qt 1.0发布 编程语言 ITeye资讯
    ubuntu用qt creator写的程序编译后生成的可执行文件复制到另一个系统中需要哪些文件才能运行
    Qt4小技巧——QTextEdit自动滚屏
    网站地图制作工具 Sitemap Creator 2.1
    Dependency Walker (depends.exe) Home Page
    秀一个PySide做的软件,网站地图制作工具 (Sitemap Creator)
  • 原文地址:https://www.cnblogs.com/rosa-king/p/10136029.html
Copyright © 2011-2022 走看看