Last active
August 29, 2015 14:15
-
-
Save bobbyjam99-zz/838e86ceb52f0bcb3f7e to your computer and use it in GitHub Desktop.
Spring MVCでforwardするとModelが初期化されちゃうパターン
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import javax.servlet.http.HttpServletRequest; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
/** | |
* http://localhost:8080/forward/first でアクセス | |
*/ | |
@Controller | |
public class FirstController { | |
@RequestMapping("/forward/first") | |
public String hoge(HttpServletRequest req) { | |
MessageForm form1 = new MessageForm(); | |
form1.setName("Ayaka"); | |
// ModelAttributeのキーと同じでセット | |
req.setAttribute("messageForm", form1); | |
return "forward:/forward/second"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import javax.servlet.http.HttpServletRequest; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
@Controller | |
public class SecondController { | |
@RequestMapping("/forward/second") | |
public String foo(MessageForm form, HttpServletRequest req) { | |
MessageForm form1 = (MessageForm) req.getAttribute("messageForm"); | |
System.out.println("second req:" + form1.getName()); // second req:Ayaka | |
System.out.println("second form:" + form.getName()); // second form:null | |
return "forward:/forward/third"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import javax.servlet.http.HttpServletRequest; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
@Controller | |
public class ThirdController { | |
/** | |
* SecondController処理後にModelAttributeがリクエスト情報を元に初期化しちゃってる | |
*/ | |
@RequestMapping("/forward/third") | |
public void bar(MessageForm form, HttpServletRequest req) { | |
MessageForm form1 = (MessageForm) req.getAttribute("messageForm"); | |
System.out.println("third req:" + form1.getName()); // third req:null | |
System.out.println("third form:" + form1.getName()); // third form:null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment