Struts2 框架总结(六) :ajax+json(注解方式)

使用xml配置文件配置ajax+json

使用ajax请求action

action界面要默认继承的包要是json-default

这里做一个简单的ajax验证登录功能,请求action就不需要返回字符串类型了

ajax的dataType如果是json,那么后台返回的界面一定要是json格式,不然可能不会执行回调函数

前台页面:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>



<% String base=request.getContextPath()+"/"; %>


Insert title here




	

后台:

package sdibt.fly.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;

@Namespace("/ajax")
@ParentPackage("json-default")
public class AjaxAction {
	private String username;
	private String password;
	
	@Action(value="ajaxLogin")
	public void ajaxLogin() throws IOException{
		System.out.println(username);
		System.out.println(password);
		
		HttpServletResponse response = ServletActionContext.getResponse();//获取response
		PrintWriter out = response.getWriter();//获取输出流
		out.print("{\"message\":\"ok\"}");
		out.close();
	}	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

如果后台界面要给前台传一个对象,可以用阿里的fastjson将对象转换成json字符串

User user = new User();
 user.setUsername(username);

user.setPassword(password)

String objJson = JSON.toJSONString(user);//转成json格式{"password":"wqe ","username":"ok"}

如果将集合转成json就是这样的格式

JSON.toJSONString(list)

[{"password":"we ","username":"ok"},{"password":"we ","username":"ww"}]

前台读取集合的json

success:function(data){
    alert(data[0].username)
}


你可能感兴趣的:(Struts2框架)