Struts2+JSON+JQuery实现简单验证

刚学的东东,搞了很久的一个小成果,在此与大家分享。。。

 

1.创建struts_JSON项目,加入struts2所需的六个包,分别为:commons-fileupload-1.2.1.jar, commons-io-1.3.2.jar, freemarker-2.3.15.jar , ognl-2.7.3.jar,  struts2-core-2.1.8.1.jar , xwork-core-2.1.6.jar 。

 

2.创建web.xml 和 struts.xml 代码分别如下:

   web.xml

   

Java代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <web-app version="2.5"    
  3.     xmlns="http://java.sun.com/xml/ns/javaee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee    
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">   
  7.        
  8.     <display-name>Struts JSON</display-name>   
  9.   
  10.     <filter>   
  11.         <filter-name>struts2</filter-name>   
  12.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>   
  13.     </filter>   
  14.   
  15.     <filter-mapping>   
  16.         <filter-name>struts2</filter-name>   
  17.         <url-pattern>/*</url-pattern>   
  18.     </filter-mapping>   
  19.   
  20.     <welcome-file-list>   
  21.       <welcome-file>index.jsp</welcome-file>   
  22.     </welcome-file-list>   
  23. </web-app>  
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="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/javaee 

	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	

    <display-name>Struts JSON</display-name>



    <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>/*</url-pattern>

    </filter-mapping>



	<welcome-file-list>

	  <welcome-file>index.jsp</welcome-file>

	</welcome-file-list>

</web-app>

 

 

    struts.xml

   

Java代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">   
  5.   
  6. <struts>   
  7. <!--   
  8.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />   
  9.     <constant name="struts.devMode" value="false" />   
  10.   
  11.     <include file="example.xml"/>   
  12.   
  13.     <package name="default" namespace="/" extends="struts-default">   
  14.         <default-action-ref name="index" />   
  15.         <action name="index">   
  16.             <result type="redirectAction">   
  17.                 <param name="actionName">HelloWorld</param>   
  18.                 <param name="namespace">/example</param>   
  19.             </result>   
  20.         </action>   
  21.     </package>   
  22. -->   
  23.     <!-- Add packages here -->   
  24.     <constant name="struts.enable.DynamicMethodInvocation" value="true" />   
  25.     <constant name="struts.devMode" value="true" />   
  26.     <constant name="struts.i18n.encoding" value="UTF-8"></constant>   
  27.        
  28.     <package name="json test" namespace="/" extends="json-default">   
  29.         <default-action-ref name="login"></default-action-ref>   
  30.         <action name="login" class="com.action.LoginAction">   
  31.             <result type="json">   
  32.                 <param name="root">tip</param>   
  33.             </result>   
  34.         </action>   
  35.     </package>   
  36.        
  37. </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="false" />

    <constant name="struts.devMode" value="false" />



    <include file="example.xml"/>



    <package name="default" namespace="/" extends="struts-default">

        <default-action-ref name="index" />

        <action name="index">

            <result type="redirectAction">

                <param name="actionName">HelloWorld</param>

                <param name="namespace">/example</param>

            </result>

        </action>

    </package>

-->

	<!-- Add packages here -->

    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <constant name="struts.devMode" value="true" />

    <constant name="struts.i18n.encoding" value="UTF-8"></constant>

    

    <package name="json test" namespace="/" extends="json-default">

    	<default-action-ref name="login"></default-action-ref>

    	<action name="login" class="com.action.LoginAction">

    		<result type="json">

    			<param name="root">tip</param>

    		</result>

    	</action>

    </package>

    

</struts>

 

 

3.加入JSON 所需的包共七个包,都是可以在struts-2.1.8.1\lib 目录下可以找得到的,他们分别为:json-lib-2.1.jar, struts2-json-plugin-2.1.8.1.jar,(这两个是JSON所必须的包) ezmorph-1.0.3.jar, commons-collections-3.2.jar, commons-beanutils-1.7.0.jar, commons-logging-1.0.4.jar, commons-lang-2.3.jar 。(因为json大量引用了Apache commons的包,所以需要引入commons的四个包。)

 

4.创建model :User.java

  

Java代码 复制代码  收藏代码
  1. package com.model;   
  2.   
  3. public class User {   
  4.   
  5.     private String username="";   
  6.     private String password="";   
  7.        
  8.     public String getUsername() {   
  9.         return username;   
  10.     }   
  11.     public void setUsername(String username) {   
  12.         this.username = username;   
  13.     }   
  14.     public String getPassword() {   
  15.         return password;   
  16.     }   
  17.     public void setPassword(String password) {   
  18.         this.password = password;   
  19.     }   
  20. }  
package com.model;



public class User {



	private String username="";

	private String password="";

	

	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;

	}

}

 

 

5.创建action: LoginAction.java:

  

Java代码 复制代码  收藏代码
  1. package com.action;   
  2.   
  3. import java.net.URLDecoder;   
  4. import java.util.HashMap;   
  5. import java.util.Map;   
  6.   
  7. import net.sf.json.JSONObject;   
  8.   
  9. import com.model.User;   
  10. import com.opensymphony.xwork2.ActionSupport;   
  11.   
  12. @SuppressWarnings("serial")   
  13. public class LoginAction extends ActionSupport {   
  14.   
  15.     User user;   
  16.     private String tip="";   
  17.        
  18.     public String execute() throws Exception {   
  19.         String username=user.getUsername();   
  20.         String password=user.getPassword();   
  21.         username=URLDecoder.decode(username, "utf-8");    //中文传参处理   
  22.         System.out.println("Username:"+username+" , Password:"+password);  //测试运行进度        
  23.                
  24.         Map<String,String> map=new HashMap<String,String>();   
  25.         map.put("username", username);   
  26.         JSONObject jo=JSONObject.fromObject(map);   
  27.         tip=jo.toString();   
  28.         System.out.println("Get Tips:"+tip);   
  29.   
  30.         return SUCCESS;   
  31.     }    
  32.        
  33.     public User getUser() {   
  34.         return user;   
  35.     }   
  36.   
  37.     public void setUser(User user) {   
  38.         this.user = user;   
  39.     }   
  40.   
  41.     public String getTip() {   
  42.         return tip;   
  43.     }   
  44.     public void setTip(String tip) {   
  45.         this.tip = tip;   
  46.     }   
  47.        
  48. }  
package com.action;



import java.net.URLDecoder;

import java.util.HashMap;

import java.util.Map;



import net.sf.json.JSONObject;



import com.model.User;

import com.opensymphony.xwork2.ActionSupport;



@SuppressWarnings("serial")

public class LoginAction extends ActionSupport {



	User user;

	private String tip="";

	

	public String execute() throws Exception {

		String username=user.getUsername();

		String password=user.getPassword();

		username=URLDecoder.decode(username, "utf-8");    //中文传参处理

		System.out.println("Username:"+username+" , Password:"+password);  //测试运行进度		

			

		Map<String,String> map=new HashMap<String,String>();

		map.put("username", username);

		JSONObject jo=JSONObject.fromObject(map);

		tip=jo.toString();

		System.out.println("Get Tips:"+tip);



		return SUCCESS;

	} 

	

	public User getUser() {

		return user;

	}



	public void setUser(User user) {

		this.user = user;

	}



	public String getTip() {

		return tip;

	}

	public void setTip(String tip) {

		this.tip = tip;

	}

	

}

 

6.创建View login.jsp:

Java代码 复制代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>   
  2. <%   
  3. String path = request.getContextPath();   
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";   
  5. %>   
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">   
  8. <html>   
  9.   <head>   
  10.     <base href="<%=basePath%>">   
  11.        
  12.     <title>Struts2+jQuery+JSON 登陆验证</title>   
  13.     <meta http-equiv="pragma" content="no-cache">   
  14.     <meta http-equiv="cache-control" content="no-cache">   
  15.     <meta http-equiv="expires" content="0">       
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   
  17.     <meta http-equiv="description" content="This is my page">   
  18.     <!--   
  19.     <link rel="stylesheet" type="text/css" href="styles.css">   
  20.     -->   
  21.     <style type="text/css">   
  22.         .decorate{               /*控制文本框样式*/  
  23.             border:1px solid #F00;   
  24.             background:url(images/text_bg.gif) repeat-x;;   
  25.             background-position:bottom;    
  26.         }   
  27.     </style>   
  28.     <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>   
  29.     <script type="text/javascript">   
  30.         $(function(){   
  31.             //var username=$("#username"); //抓取对象   
  32.             //var password=$("#password");   
  33.             $("#validate").click(function(){   
  34.                 var username=$("#username").val();  //只能使用在jQuery 函数的里面   
  35.                 var password=$("#password").val();     
  36.                 if(username==""||password==""){   
  37.                     alert("用户名或密码不能为空!");   
  38.                 }else{   
  39.                     var url="login?user.username="+encodeURI(encodeURI(username))+"&user.password="+encodeURI(encodeURI(password));   
  40.                     $.getJSON(url,null,function(data){   
  41.                          // convert to json object    
  42.                         //alert(data);   
  43.                         var message=eval("("+data+")");   
  44.                         $("#tip").html("欢迎您!"+message.username);       
  45.                     });   
  46.                 }   
  47.             });   
  48.   
  49.             $("#username").keyup(function(){   
  50.                 var username=$("#username").val();   
  51.                 if(username==""){   
  52.                     $("#username").addClass("decorate");   
  53.                 }else{   
  54.                     $("#username").removeClass("decorate");   
  55.                 }   
  56.             });   
  57.             $("#password").keyup(function(){   
  58.                 var password=$("#password").val();   
  59.                 if(password==""){   
  60.                     $("#password").addClass("decorate");   
  61.                 }else{   
  62.                     $("#password").removeClass("decorate");   
  63.                 }   
  64.             });   
  65.         });   
  66.     </script>   
  67.   </head>   
  68.      
  69.   <body>   
  70.     <div id="tip" style="color:#F00; font-weight:bold; "></div>   
  71.         <fieldset style="width:600px; ">   
  72.             <legend>用户登录</legend>   
  73.             <p align="center">账号:<input type="text" name="user.username" id="username" class="decorate" /></p>   
  74.             <p align="center">密码:<input type="password" name="user.password" id="password" class="decorate" /></p>   
  75.             <p align="center"><input type="submit" id="validate" name="validate" value="确定" /></p>   
  76.         </fieldset>   
  77.   </body>   
  78. </html>  
<%@ 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">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>Struts2+jQuery+JSON 登陆验证</title>

	<meta http-equiv="pragma" content="no-cache">

	<meta http-equiv="cache-control" content="no-cache">

	<meta http-equiv="expires" content="0">    

	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

	<meta http-equiv="description" content="This is my page">

	<!--

	<link rel="stylesheet" type="text/css" href="styles.css">

	-->

	<style type="text/css">

		.decorate{               /*控制文本框样式*/

			border:1px solid #F00;

			background:url(images/text_bg.gif) repeat-x;;

			background-position:bottom;	

		}

	</style>

	<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

	<script type="text/javascript">

		$(function(){

			//var username=$("#username"); //抓取对象

			//var password=$("#password");

			$("#validate").click(function(){

				var username=$("#username").val();  //只能使用在jQuery 函数的里面

				var password=$("#password").val();  

				if(username==""||password==""){

					alert("用户名或密码不能为空!");

				}else{

					var url="login?user.username="+encodeURI(encodeURI(username))+"&user.password="+encodeURI(encodeURI(password));

					$.getJSON(url,null,function(data){

						 // convert to json object 

						//alert(data);

						var message=eval("("+data+")");

						$("#tip").html("欢迎您!"+message.username);	

					});

				}

			});



			$("#username").keyup(function(){

				var username=$("#username").val();

				if(username==""){

					$("#username").addClass("decorate");

				}else{

					$("#username").removeClass("decorate");

				}

			});

			$("#password").keyup(function(){

				var password=$("#password").val();

				if(password==""){

					$("#password").addClass("decorate");

				}else{

					$("#password").removeClass("decorate");

				}

			});

		});

	</script>

  </head>

  

  <body>

	<div id="tip" style="color:#F00; font-weight:bold; "></div>

		<fieldset style="width:600px; ">

			<legend>用户登录</legend>

			<p align="center">账号:<input type="text" name="user.username" id="username" class="decorate" /></p>

			<p align="center">密码:<input type="password" name="user.password" id="password" class="decorate" /></p>

			<p align="center"><input type="submit" id="validate" name="validate" value="确定" /></p>

		</fieldset>

  </body>

</html>

你可能感兴趣的:(struts2)