spring3.2 ajax :
@RequestMapping(value = "/fct/ajax_addUser.do", method = RequestMethod.POST)
@ResponseBody
public String ajax_addUser(
@RequestParam(value = "name", required = false) String name,
@RequestParam(value = "age", required = false) String age,
@RequestParam(value = "sex", required = false) String sex) {
String sql = "INSERT INTO user(name,age,sex) VALUES(?,?,?)";
Object[] params = new Object[] { name, age, sex };
int rows = udao.exec(sql, params); // 插入到数据库表
return "增加了" + rows + "条用户信息!"; // 返回提示信息
}
struts2.1 ajax:
在action类名上写注解:
@Action(value = "/user", results = {
@Result(name = "add", location = "user/add_user.jsp"),
@Result(name = "error", location = "sysError.jsp") })
ajax调用的方法:
public String add() {
String result = "1";
try {
if (PubMethod.isEmpty(username) || PubMethod.isEmpty(password)) {
result = "用户名和密码都不能为空!";
} else {
List<User> list = userDAO.findByUsername("" + username);
if (list != null && list.size() != 0) {
result = "该用户名已被使用,请输入其他用户名!";
} else {
User user = new User();
user.setIsadmin(isadmin);
user.setPassword(password);
user.setUsername(username);
userDAO.save(user); // 保存数据
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "0";
}
ulog.info(result);
writeData(result); // 返回信息
return null;
}
/**
* @category ajax回写数据
* @param data
*/
public void writeData(String data) {
// 获取原始的PrintWriter对象,以便输出响应结果,而不用跳转到某个试图
HttpServletResponse response = ServletActionContext.getResponse();
// 设置字符集
response.setContentType("text/plain");// 设置输出为文字流
response.setCharacterEncoding("UTF-8");
PrintWriter out;
try {
out = response.getWriter();
// 直接输出响应的内容
out.println(data);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}