We often encounter this requirement in projects-page partial refresh. For example, when a user is added and transferred to the add user page, all departments are automatically loaded on the page.
Complete process: select the Department, enter the user name and password, and click "register"
After entering the user name, you need to immediately check whether the database has this user name. How can this effect be achieved without refreshing the page?
However, it is not difficult to look at the questions raised above. It is common to know That Ajax is used, but how to customize the result set in struts to implement Ajax is the focus of this blog.
(Note:Servlet either forwards or redirects, struts2 can customize the result set)
Forwarding, redirection, and action2action will refresh the page, which cannot meet the requirement of refreshing the page. Therefore, you can define a result set by yourself (using this result set to set the server side (Action) ).
Tools: myeclipse8.5 and tomcat6.0.39
1. steps:
1. Create a web project named STRUTS + ajaxresult
2. Import Struts-related packages
3. Configure the Web. xml file
4. Create a pojo class -- user. Java
5. Create an action base class and a sub-action class-baseaction and useraction. Java
6. Create a custom result set-ajaxresult. Java
7. Configure the Struts. xml file
8. Create a page -- add. jsp
9. Create a JS file named user_add.js.
(Note:You also need to introduce the jquery. js file)
---- Web. xml: configuration file (Note: configure the core filter of struts2)
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> <? Xmlversion = "1.0" encoding = "UTF-8"?> <Web-appversion = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <! -- Configure the core filter of struts2 --> <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>/* </url-Pattern> </filter-mapping> <welcome-file-List> <welcome-File> index. JSP </welcome-File> </welcome-file-List> </Web-app> </span>
---- User. Java: user entity class
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> importjava. io. serializable; public class userimplements serializable {private long UID; // user idprivate string username; // user name private string password; // password // ********** get/Set Method ********************** * ********************** publiclong getuid () {returnuid;} publicvoid setuid (Long UID) {This. uid = uid;} publicstring GetUserName () {returnusername;} publicvoid setusername (string username) {This. username = username;} publicstring GetPassword () {returnpassword;} publicvoid setpassword (string password) {This. password = PASSWORD ;}</span>
---- Baseaction. Java: Abstract action class, encapsulating public content
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> importjava. lang. reflect. parameterizedtype; importcom. opensymphony. xwork2.actionsupport; importcom. opensymphony. xwork2.modeldriven;/*** encapsulate some shared content here * @ author administrator **/Public classbaseaction <t> extends actionsupport implements modeldriven <t> {PrivateClass classt; privatet T; publicstatic final string addui = "addui"; publicstring addui = addui; publicbaseaction () {try {parameterizedtypetype = (parameterizedtype) This. getclass (). getgenericsuperclass (); this. classt = (class) type. getactualtypearguments () [0]; this. t = (t) This. classt. newinstance ();} catch (effectione) {e. printstacktrace () ;}} publict GetModel () {// todo auto-generated method stubreturnthis. t ;}}</span>
---- Useraction. Java: the user module processes the action
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> <span style = "color: #333333;"> importcn. itcast. oa0909.domain. user; importcn. itcast. oa0909.struts2. action. base. baseaction; importcom. opensymphony. xwork2.actioncontext; publicclass useraction extendsbaseaction <user >{/ *** jump to the add user page * @ return */publicstring addui () {returnaddui ;} /*** check whether the user name exists * @ return */publicstring checkusername () {If (" min ". equals (this. getModel (). getUserName () {// If the input username is "Xue min" actioncontext. getcontext (). getvaluestack (). push ("this user name already exists"); // press data to the top of the stack} else {// if the user name entered is not "Xue min" actioncontext. getcontext (). getvaluestack (). push ("this user name can be used"); // press data to the top of the stack} returnsuccess; }}</span> </span>
---- Ajaxresult. Java: Custom result set (Note: This result set calls back the server-side (Action) data to the client)
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> importjavax. servlet. HTTP. httpservletresponse; importorg. apache. struts2.servletactioncontext; importcom. opensymphony. xwork2.actioncontext; importcom. opensymphony. xwork2.actioninvocation; importcom. opensymphony. xwork2.result; Public classajaxresult implements result {publicvoid execute (actioninvocation Invocation) throws exception {httpservletresponseresponse = servletactioncontext. getresponse (); response. setcharacterencoding ("UTF-8"); // handle Chinese garbled characters. String message = actioncontext. getcontext (). getvaluestack (). peek (). tostring (); // obtain the top-stack element response. getwriter (). print (Message); // return the top element of the stack to the client. }}</span>
---- Struts. xml: struts configuration file
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> <? Xmlversion = "1.0" encoding = "UTF-8"?> <! Doctype strutspublic "-// apachesoftware Foundation // DTD struts configuration 2.1.7 // en" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <! -- Do not restart after the configuration file is changed --> <constant name = "struts. devmode "value =" true "/> <constantname =" struts. UI. theme "value =" simple "/> <shortdefile =" struts/struts-user.xml "> </include> <! -- Configure a custom result set --> <packagename = "Ajax-Default" extends = "struts-Default"> <result-types> <result-typename = "ajax" class =" CN. itcast. oa0909.result. ajaxresult "> </result-type> </result-types> </package> </struts> </span>
---- Struts-user.xml
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> <? Xmlversion = "1.0" encoding = "UTF-8"?> <! Doctype strutspublic "-// apachesoftware Foundation // DTD struts configuration 2.1.7 // en" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <! -- Inherit from Struts-default result set --> <package name = "user" namespace = "/" extends = "struts-Default"> <actionname = "useraction _ *" method =" {1} "class =" CN. itcast. oa0909.struts2. action. useraction "> <resultname =" addui "> WEB-INF/JSP/user/Add. JSP </result> </Action> </package> <! -- Inherit the custom result set -- Ajax-default (in struts. configured in the XML file) --> <package name = "userjson" namespace = "/" extends = "Ajax-Default"> <actionname = "userjsonaction _ *" method = "{1}" class =" CN. itcast. oa0909.struts2. action. useraction "> <resulttype =" ajax "> </result> </Action> </package> </struts> </span>
---- Add. jsp: add user page
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> <% @ pagelanguage = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <scriptlanguage =" JavaScript "src =" $ {pagecontext. request. contextpath}/JS/jquery-1.4.2.js "> </SCRIPT> <scriptlanguage =" JavaScript "src =" $ {pagecontext. request. contextpath}/JS/user_add.js "> </SCRIPT> <HTML>
(Note:Assume that the data in the Department is read from the database when the page is loaded, rather than written as shown above)
Page effect:
The Department drop-down list is displayed as follows:
----- User_add.js: JS required for adding user pages
<Span style = "font-family: kaiti_gb2312; font-size: 18px;"> var user = {// initialization event inintevent: function () {$ ("input [name = 'username']"). unbind ("Blur"); $ ("input [name = 'username']"). BIND ("Blur", function () {// user of the function triggered by the loss of focus in the text box whose name is "username. checkuser ($ (this ). val (); // call to check the User Function (check whether the user name exists)});},/*** check whether the user name exists */checkuser: function (username) {var A = "A"; VaR parameter = {// parameter: Username: username};/*** userjsonaction_checkusername.action: request address * parameter: parameter * function (data) {}: callback function */$. post ("userjsonaction_checkusername.action", parameter, function (data) {$ ("# message "). text (data); // assign the value returned by the server to the label prompt box of ID = "message", and display if (Data = "this user name can be used ") {$ ("# message" ).css ("color", "blue"); // set the color of the prompt text} else {$ ("# message" ..css ("color ", "Red"); // set the color of the prompt text}) ;}; // run when the page is loaded $ (). ready (function () {user. inintevent (); // call the initialization event when loading the page </span>
Ii. Run
Input address: http: // localhost: 8080/struts2 + ajaxresult/useraction_addui.action. The following page is displayed:
Enter "Xue min" as the user name. This user name already exists in the Database. When the mouse leaves the User Name text box (that is, the user name text box loses focus (Note:Here is the Ajax request, its processing process, and the technical points of the application are the focus of this blog), the prompt "this user already exists" will be displayed, and the user name is entered "Zhang Sanna ", if the database does not exist, the system prompts "this user name can be used"
Iii. Summary
Disadvantages of custom result set:
.... To be continued...
Struts2-custom result set implementation Ajax