本執行個體通過利用Jquery架構中的post方法實現了前台jsp頁面的資料和以struts2為背景action之間資料的傳遞
首先編寫jsp頁面
JSP代碼
<%@ 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><head><script type="text/javascript" src="<%=path %>/js/jquery-1.7.2.js"></script><script type="text/javascript" src="<%=path %>/js/md5.js"></script><script type="text/javascript" src="<%=path %>/js/login.js"></script></head><body><div align="center">user login<br /><br />username:<s:textfield name="username"></s:textfield><br /><br />password:<s:password name="password"></s:password><br /><br /><s:submit value="提交" id="submit"></s:submit></div></body></html>
介面很簡單 就是一個類比登入的介面
2。。。。。。進行JS指令碼編寫
//對密碼進行加密$(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。。。。。。。。進行後台action的編寫
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。。。。。。。。進行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。。。。。。。。。。。進行測試
測試結果為後台得到前台的username和加密後的password並在控制台進行了列印
前台直接返回alert彈出了輸入的username
6。。。。。。配置完畢