JSON转化
Action部分的代码
import
java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSON;
import com.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.service.dao.UserServiceDao;
.........
public void login() {
User u = userServiceDao.login(user);
System.out.println(u);
Map<String, Object> m = new HashMap<String, Object>();
if (u != null) {
m.put("success", true);
m.put("message", "登陆成功");
String json = JSON.toJSONString(m);
try {
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (
IOException e) {
e.printStackTrace();
}
} else {
m.put("message", "登陆失败");
String json = JSON.toJSONString(m);
try {
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
ServletActionContext.getResponse().getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
script代码
<script type="text/javascript">
$(function() {
$('#login').bind('click',function() {
$.ajax({
type : "post",
url : "${pageContext.request.contextPath}/userAction!login.action",
dataType : "json",
data : $("input").serialize(),
success