In this example, the POST method in the jquery framework is used to transmit data between JSP page data at the front end and actions at the background of struts2.
First, compile the JSP page
JSPCode
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" S "uri ="/Struts-tags "%> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
The interface is a simulated logon interface.
2 ...... Write JS scripts
// Encrypt the password $ (document ). ready (function () {$ ("# submit "). click (function () {var psw = $ ("# password"); var username = $ ("# username "). val (); var Password = hex_md5 (psw. val (); alert (psw. val () + ":" + password); $. post ("login. action ", {" username ": username," password ": Password}, function (data) {alert (data) ;}," text "); alert ("123 ");});})
3 ........ Write background actions
Package COM. action; import Java. io. ioexception; import Java. io. printwriter; import javax. servlet. HTTP. httpservletresponse; import Org. apache. struts2.servletactioncontext; import COM. opensymphony. xwork2.actionsupport; public class login extends actionsupport {private string username; private string password; Public String execute () throws exception {system. out. println (password); httpservletresponse response = servletactioncontext. getresponse (); response. getwriter (). write (username); system. out. println (username); return NULL;} Public String GetUserName () {return username;} public void setusername (string username) {This. username = username;} Public String GetPassword () {return password;} public void setpassword (string password) {This. password = password ;}}
4 ........ Configure struts
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts. enable. dynamicmethodinvocation "value =" true "/> <constant name =" struts. devmode "value =" true "/> <package name =" default "extends =" struts-Default "> <action name =" login "class =" com. action. login "> <result> pages/admin. JSP </result> </Action > </Package> <! -- Add packages here --> </struts>
5 ........... Test
The test result is that the username and encrypted password of the front-end are obtained in the background and printed on the console.
The front-end directly returns alert with the input username popped up.
6 ...... Configuration complete