springMVC中跳轉問題


 

  

在使用SpringMVC時遇到了這個跳轉的問題很頭疼。現在總結出來,對以后的開發有所幫助。

1、可以采用ModelAndView:

@RequestMapping("test1")
public ModelAndView test(){
    ModelAndView view = new ModelAndView();
    view.addAllObjects(map);
    view.setViewName("redirect:http://localhost:8080/springMVC1/test2");		
    return view;
}

如果需要在Controller之間傳遞參數的時候,這種方式只能通過在訪問路徑后面加上參數以及將參數放到session域中的方式傳遞參數。

這種方式也可用於實現Controller到頁面之間的跳轉。並且可以傳參數

public ModelAndView handleRequest(HttpServletRequest arg0,
            HttpServletResponse arg1) throws Exception {
        System.out.println("hello springMVC");
        Map<String,String> map = new HashMap<String,String>();
        map.put("msg", "你好Springmvc");
        return new ModelAndView("/welcome","map",map);
    }

ModelAndView構造方法中第一個參數是頁面的訪問路徑(前面加上一個“/”表示從根路徑開始。)后面兩個參數就相當於鍵值對。在頁面中通過el表達式取出鍵為map的值(map)${map}

ModelAndView跳轉頁面和跳轉Controller的差距在於地址上跳轉Controller有一個redirect:表示。跳轉頁面則沒有

2、通過request.getRequestDispatch的方式跳轉

public ModelAndView test(HttpServletRequest request,HttpServletResponse response){
    try {
        request.getRequestDispatcher("/test2").forward(request, response);
    } catch (ServletException e) {
        e.printStackTrace(); 
    } catch (IOException e) {
    e.printStackTrace();
    }

}

這種方式跳轉到另一個頁面時可以通過request.setAttribute(key,value)的方式將參數傳到另一個Controller中。並且如果執行這個跳轉以后,程序后面的代碼就不會再執行了。
如果是想從Controller跳轉到頁面則只需要將地址改為頁面的地址就可以了。

注意:

因為在項目里我需要從一個頁面的Ajax請求到一個Controller進行處理該Ajax的請求,然后根據處理的結果跳轉到不同的頁面。我之前的做法是在處理Ajax請求的Controller里進行下一個頁面的跳轉。試了從處理該Ajax請求的Controller里直接跳轉到下個頁面,或是跳到下一個Controller在跳轉到需要的頁面中。使用了ModelAndView的方法和Request.getRequestDispatch 的方法都沒有用,最終的目的都不會跳轉到目的頁面,出現兩種問題:

1、使用Request的方法時,跳轉一直跳到本頁面

2、使用ModelAndView時,響應到了目的頁面的內容,但是界面沒有跳轉

最后得出結論。使用這兩中方方式都不會跳轉,具體原因不知道。我想可能是使用Ajax請求一定會有一個放回的數據,所以SpringMVC不知道怎么處理放回數據和跳轉頁面的關系?

得出的一個解決辦法是:

 

function test(){
        $.ajax({
            url:'testSkip/test3.do',
            type:'post',
            dataType:'json',
            success:function(data){
                console.info(data);
                var url = data.url ;
                alert(url);
                window.location.href=url ;
            },
            error:function(){
                alert("error");
            }            
        });
    }

 

@RequestMapping("test3")
    @ResponseBody
    public Object test3(){
        Result result = new Result();
        result.setUrl("testSkip2/test3.do");
        return result ;
    }
}
@Controller
@RequestMapping("testSkip2")
public class TestController2 {

@RequestMapping("test3") public ModelAndView test2(){ System.out.println("跳轉頁面2.2"); return new ModelAndView("/company/company_on_line","result","數據"); }
}

在Ajax請求在兩個Controller或是Controller與頁面之間跳轉之前插入一步回到原來的Ajax請求頁面通過  window.location.href=url ; 再次發送請求。這是該請求的地址可以使一個Controller地址和頁面地址。這是跳轉就沒問題。


免責聲明!

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



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