This answer is to just confirm that the answer by axtavt works. It took me a minute to realize what he was suggesting, so I thought I'd post a code-snippet to help out anyone coming along behind me. Kudos go to him, though! :)
MyController.java
@Controller
public class MyController {
@RequestMapping( method=RequestMethod.GET, value="/mainView" )
public ModelAndView getMainView( ... ) {
/* do all your normal stuff here to build your primary NON-ajax view
* in the same way you always do
*/
}
/* this is the conroller's part of the magic; I'm just using a simple GET but you
* could just as easily do a POST here, obviously
*/
@RequestMapping( method=RequestMethod.GET, value="/subView" )
public ModelAndView getSubView( Model model ) {
model.addAttribute( "user", "Joe Dirt" );
model.addAttribute( "time", new Date() );
return new ModelAndView( "subView" );
}
}
mainView.jsp
(...)
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
function doAjaxPost() {
$.ajax({
type: "GET",
url: "subView",
success: function(response) {
$("#subViewDiv").html( response );
}
});
}
</script>
<input type="button" value="GO!" onclick="doAjaxPost();" />
<div id="subViewDiv"></div>
(...)
subView.jsp
(...)
<h3>
User Access Details
</h3>
<p>
${user} accessed the system on ${time}
</p>
(...)
And that's it! A thing of beauty; up to now, doing AJAX in Spring has been a huge pain... parsing big @ResponseBody's, building huge sets of HTML by concatenating stuff in JS... ugh... I can't believe how simple and awesome this approach is -- and wasn't aware of it until just now! :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…