Struts2如何处理AJAX请求
action
publicclassHandlerActionextendsActionSupport{privateintno;privateStudentstudent;publicintgetNo(){returnno;}publicvoidsetNo(intno){this.no=no;}publicStudentgetStudent(){returnstudent;}publicvoidsetStudent(Studentstudent){this.student=student;}@OverridepublicStringexecute()throwsException{//此处缺省连接数据库查询得到学生信息student=newStudent(1,"张三",20,100);returnSUCCESS;}}
需要设置同名的成员变量,并提供getter、setter方法,来接收前端传来的数据。
此种方式是由JSON插件把action对象序列化为一个JSON格式的字符串,传给浏览器。浏览器可以直接访问action的所有成员变量(实质是调用对应的getter方法)。
我们只需要把ajax要请求的数据封装为action的成员变量,并提供对应的getter、setter方法。需要在主调方法(execute)的return语句之前对请求的数据赋值。
success:function(data){$("#show").append("姓名:"+data.student.name+",");$("#show").append("年龄:"+data.student.age+",");$("#show").append("成绩:"+data.student.score+"。");}
浏览器接受到的数据data本身就是action实例,可通过.访问成员变量。
struts.xml
说明
需要手动添加JSON插件 struts2-json-plugin.jar 。
上面的压缩包含有struts的所有jar包,其中就包括了struts2-json-plugin.jar。
下面的压缩包只有struts核心的8个jar包。
读到这里,这篇“Struts2如何处理AJAX请求”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注恰卡编程网行业资讯频道。