Spring MVCとAjax


Spring Json ViewプロジェクトはSpring MVCのためにAjax機能を拡張しました.
1.spring-json.jarとsojo.jarファイルをクラスパスに入れる;
2.spring mvcのためにAjaxをサポートするビュー解像器を設定します.

<!-- View Resolver -->
<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
</bean>

<bean  name="xmlViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver" >
		<property name="order" value="1"/>
</bean>
なぜ二つですか?一つはjsp用で、もう一つは帰りのmodelをJson文字列に変換するAjaxビュー用です.
3.Jspのためにコントローラを作るように、どうやって書くべきですか?

public class SimpleJsonGetController implements Controller {
	
	private ProfileService profileService;
	public void setProfileService(ProfileService profileService) {
		this.profileService = profileService;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		String roleId=(arg0.getParameter("roleId")!= null)?arg0.getParameter("roleId"):"1";
		List select2=profileService.getRemainedTopicsByRole(Integer.parseInt(roleId));
		List select3=profileService.getTopicsByRole(Integer.parseInt(roleId));
		HashMap map=new HashMap();
		map.put("select2", select2);
		map.put("select3", select3);
//map->json       
		return new ModelAndView("hello",map);
	}

4.jspファイルで参照しているjsファイルは以下の通りです.

$(document).ready(function(){
    //jQuery test   
	$("a").click(function(event){
         alert("as you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
	//button test
	   $('#getName').click(function(){	
		$.getJSON('hello.htm', function(data) {
		$('#username').html( data.username );		
		$('#selectfrom').empty();
		var users = data.users;
		$.each(users,function(index,value){
			$("#selectfrom")[0].options.add(new Option(value.username,value.userId,false,false));
		});
		
		});
     });
  
$('#select1').change(function() {
	var rid=$('#select1').val();
  $.getJSON('hello.htm?roleId='+rid, function(data) {
  $('#select2').empty();
  $('#select3').empty();
	var select2 = data.select2;
	var select3 = data.select3;
	$.each(select2,function(index,value){
			$("#select2")[0].options.add(new Option(value.topicName,value.topicId,false,false));
		});
	$.each(select3,function(index,value){
			$("#select3")[0].options.add(new Option(value.topicName,value.topicId,false,false));
		});
  });
});
//button click event
$('#authorize').click(function(){
$.post("profile.htm", $("#form1").serialize());
alert("OK");
});

});
Jsプログラムがhello.htmを呼び出して返した結果、以下の通りです.
{username}:「張三」、「users」:「{username]」:「root」、「password」:「spk 321」、「userId」:「43」、「roleId」:「33」、{username】:「Spongebob」、「password」:「Imber 33」