Jquery + ajax + struts2, jquerystruts2
AJAX is the art of data exchange with the server. It updates some webpages without reloading all pages.
Writing regular AJAX code is not easy, because different browsers have different AJAX implementations.
This means that you must write additional code to test your browser. However, the jQuery team solved this problem for us. We only need a line of simple code to implement AJAX.
Now let's take a look at three common ajax methods.
$ (Selector). load (URL, data, callback );
The required URL parameters specify the URL you want to load.
The optional data parameter specifies the set of query string key/value pairs sent together with the request. Is a data in json format.
The optional callback parameter is the name of the function executed after the load () method is complete.
Let's look at an example of getting the server time.
Jsp:
<Script type = "text/javascript" src = "$ {basePath}/javascript/jquery-1.8.3.min.js"> </script> <script type = "text/javascript"> $ (function () {$ (": button "). click (function () {var url = "$ {basePath}/timeServlet"; // The simplest ajax method, which is submitted in get mode by default, the returned value is automatically filled in the tag $ ("# time "). load (url) ;};}); </script>
The page is as follows:
The basePath is as follows:
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%pageContext.setAttribute("basePath", path);%>
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); String formatTime = sdf.format(new Date()); PrintWriter pw = response.getWriter(); pw.println(formatTime); pw.flush(); pw.close(); }
In this way, the simplest ajax is completed. If there are 2nd parameters of data, the submission method is post, otherwise it is get.
Let's take a look at the effect. Click "get time" to get the server time:
Do not worry about how to use the last two parameters. The following explains in $. post.
Definition and usage
The post () method loads data from the server through an http post request.
Syntax
JQuery. post (url, data, success (data, textStatus, jqXHR), dataType)
| Parameters |
Description |
| Url |
Required. Specifies the URL to which the request is sent. |
Data
|
Optional. Ing or string value. Specifies the data sent to the server together with the request. |
| Success (data, textStatus, jqXHR) |
Optional. The callback function executed when the request is successful. |
| DataType |
Optional. Specifies the expected server response data type. Intelligent judgment (xml, json, script, or html) is performed by default ). |
Let's take a look at the login judgment example to understand its usage. This example verifies the login and then returns the path of an image. If the input is correct, if the input is correct, a check mark is displayed in the image, otherwise, a cross is displayed:
Jsp:
<Script type = "text/javascript"> $ (function () {$ (": button "). click (function () {var url = "$ {basePath}/userServlet"; // use servlet first. // var url = "$ {basePath}/user_login.action "; // use struts2 for var username =$ (": text "). val (); var password = $ (": password "). val (); var data_servlet = {"username": username, "password": password}; var data_struts2 = {"user. username ": username," user. password ": password}; // test the servlet first. Change the 2nd data parameters to data_struts2 during the struts2 test. post (url, data_servlet, function (data, statusTxt, jqXHR) {alert ("data-=-" + data); alert ("data. src-= "+ data. src); alert ("statusTxt-=-" + statusTxt); alert ("jqXHR. status-=-"+ jqXHR. status); // status code, such as 200 alert ("jqXHR. readyState-=-"+ jqXHR. readyState); // The status of the request execution, such as 4 alert ("jqXHR. statusText-=-"+ jqXHR. statusText); // status string, such as OK alert ("jqXHR. responseText-=-"+ jqXHR. responseText); // The returned string value alert ("jqXHR. responseXML-=-"+ jqXHR. responseXML); // The returned XML data $ ("img "). attr ("src", '$ {basePath}' + data); // The returned string // $ ("img "). attr ("src", '$ {basePath}' + data. src); // The returned json data });});}); </script>
The page is as follows:
First, let's look at the servlet:
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); String username = request. getParameter ("username"); String password = request. getParameter ("password"); // query User user User = userDao from the database. findByUsernameAndPassword (username, password); System. out. println (user); PrintWriter pw = response. getWriter (); I F (user! = Null) pw. println ("/images/icon/Button_ OK _64px_1070400_easyicon.net.ico"); else pw. println ("/images/icon/button_delete_64px_10701__easyicon.net.ico"); pw. flush (); pw. close ();}
Let's take a look at the effect:
If the input is correct, the following information is displayed:
If the input is incorrect, the following information is displayed:
JqXHR. responseText shows that the returned string does not need to be parsed. Next let's take a look at struts2's ajax
Configure the struts2 filter in web. xml first:
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>
Put struts. xml in the struts2 configuration file and put it under src:
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.3 // EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name = "struts. action. extension "value =" action "/> <! -- Set the struts access suffix to action --> <constant name = "struts. enable. DynamicMethodInvocation" value = "false"/> <! -- Disable dynamic access --> <package name = "user-action" namespace = "/" extends = "json-default"> <! -- Json-default is inherited from struts-default --> <action name = "user_login" class = "top. bwcx. ajax. user. userAction "> <result type =" json "/> <! -- You do not need to jump to the page --> </action> </package> </struts>
Struts2 ajax requires support for struts2-json-plugin.jar plug-in packages
Here we use c3p0 to connect to the database and dbutils to operate the database. For more information, see my previous three methods for connecting c3p0 to the database and the basic usage of dbutils.
Configuration in action:
Public class UserAction extends ActionSupport {// For simplicity, A dao is directly written here, and the service does not write private UserDao userDao = new UserDao (); // User entity class, it is used to receive values transmitted from the page. The get and set methods are required. It is very important to use the private User user; // return values using the get method, and then retrieve the values on the page, this requires the get method private String src; @ Override public String execute () throws Exception {System. out. println (user. getUsername (); System. out. println (user. getPassword (); user = userDao. findByUsernameAndPassword (user. getUsername (), user. getPassword (); System. out. println (user); if (user = null) {src = "/images/icon/button_delete_64px_10701__easyicon.net.ico";} else src = "/images/icon/images "; return SUCCESS ;}
Public void setUser (User user) {this. user = user;} public User getUser () {return user;} public String getSrc () {return src ;}}
The ajax request struts transmits the response through the get method on the action page. In this case, the image path can be returned by adding the get Method to the src attribute. The returned format is a json string.
When receiving a message on the page, change the passed parameter to data_struts2, and change the url to parse the json directly like this: data. src
The effect is the same as that of servlet. You can also check the printed attribute values, for example:
In fact, there is a simple way to collect the values of form items, such
Var params = $ ("form"). serialize ();
However, the name attribute value must be provided.
$. Get () and $. post () are similar. Next let's take a look at $. ajax ()
$. Ajax () has many parameters, which are commonly used:
Type: submission method, get or post
Url: Request Path
Data: Request Parameters
Success: The function called after successful execution
Use this method for login verification:
Change jsp:
<Form> username <input type = "text" name = "user. username "> <br> password <input type =" password "name =" user. password "> <br> <input type =" button "value =" click my verification "> </form>
The js Code is changed:
<Script type = "text/javascript"> $ (function () {$ (": button "). click (function () {var params = $ ("form "). serialize (); // directly serialize the form $. ajax ({type: "post", url: "$ {basePath}/user_login.action", data: params, success: function (result) {$ ("img "). attr ("src", '$ {basePath}' + result. src); // The returned json data}); </script>
Others remain unchanged, so that the same effect can be achieved. Of course, you can also use the response object in struts2 to respond to ajax requests, just like in servlet.