獲取request Header內容和重定向


1、獲取request和cookie

@RequestMapping("request")
    @ResponseBody
    public String getReequest(HttpServletRequest request,
                              HttpServletResponse response){
        //瀏覽器拿到的內容
        StringBuffer str=new StringBuffer();
        Enumeration<String> headerNames = request.getHeaderNames();//獲取所有元素名字
        while (headerNames.hasMoreElements()){//下一個元素存在
            String name=headerNames.nextElement();//獲取當前元素
            str.append(name+"::: "+request.getHeader(name)+"<br>");//通過當前元素得到具體內容
        }
        //cookie不為空時可用
         for (Cookie cookie:request.getCookies()){
             str.append(cookie.getName()+":"+cookie.getValue());
         }
        return str.toString();
    }

2、301和302

重定向301,一般瀏覽器會進行緩存(下一次再訪問直接去重定向的頁面,因為已經緩存了,302不會),而302是暫時性重定向,就是請求的資源暫時駐留在不同的 URI 下 ,故而除非特別指定了緩存頭部指示,該狀態碼不可緩存。

  

 @RequestMapping("/redirect/{code}") //ModelAndView是重定向301
    public ModelAndView redirect(
            @PathVariable("code") int code,
            HttpSession session
    ){
        session.setAttribute("han","2000113");//存session
        ModelAndView mv=new ModelAndView( new RedirectView("/ftl",true));//modelandview具有model存值傳參和view視圖跳轉的功能
        return mv;
    }

3、錯誤顯示

一般springboot出現錯誤會加載springboot默認的提示模板,我們可以自定義捕獲異常並在頁面顯示

  

 @RequestMapping("admin")
    @ResponseBody
    public String admin(@RequestParam(value = "user",required = true)String user){
        if (user.equals("admin")){
            return "hello admin";
        }
        throw new IllegalArgumentException("user錯誤");
    }


    //錯誤頁面處理,默認是spring捕獲顯示錯誤頁面,通過這個可以顯示自己定義的錯誤
    @ExceptionHandler
    @ResponseBody
    public String getException(Exception e){
        return "錯誤"+e.getMessage();
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM