Simple and practical example code of Ajax, simple and practical example of ajax
I will implement a simple Ajax page without refreshing the new user verification case:
The effect is as follows:
Implementation process:
The checkUser method in the UsersAction class receives and verifies the form data at the front end. In different cases, a status code is returned to the jsp page, and then passed $ in ajax1.jsp. the post method accepts the status code passed by the background.
Make different responses.
The Code is as follows:
1. entity class
package com.bean;import java.io.Serializable;public class Users implements Serializable { private String uname; private String passwd; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public Users(String uname, String passwd) { super(); this.uname = uname; this.passwd = passwd; } public Users() { super(); }}
2. action class
package com.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 com.bean.Users;public class UsersAction { private Users us; public Users getUs() { return us; } public void setUs(Users us) { this.us = us; } @Action(value="checkUser") public String checkUser() { System.out.println("aaaaaaaaa"); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); try { PrintWriter out = response.getWriter(); int code = 0; if (us == null) { out.print(0); return null; } else { if (us.getUname() == null || us.getUname().trim().equals("")) { code = 1; out.print(code); return null; } else { if (us.getPasswd() == null || us.getPasswd().trim().equals("")) { code = 2; out.print(code); return null; } else { code = 200; out.print(code); } } } out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }}
3. ajax1.jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
The above is a simple and practical example code of Ajax introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in time. Thank you very much for your support for the help House website!