spring3.2 ajax :ajax
@RequestMapping(value = "/fct/ajax_addUser.do", method = RequestMethod.POST)spring
@ResponseBodysql
public String ajax_addUser(數據庫
@RequestParam(value = "name", required = false) String name,app
@RequestParam(value = "age", required = false) String age,jsp
@RequestParam(value = "sex", required = false) String sex) {ide
String sql = "INSERT INTO user(name,age,sex) VALUES(?,?,?)";ui
Object[] params = new Object[] { name, age, sex };spa
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();
}
}