日期:2014-05-16  浏览次数:20302 次

Struts2+json+jQuery(用户名验证)

1、添加struts-2.2.3 jar包

???? commons-fileupload-1.2.2.jar

???? commons-io-2.0.1.jar

???? commons-lang-2.5.jar

???? commons-logging-1.1.1.jar

???? freemarker-2.3.16.jar

???? javassist-3.7.ga.jar

???? ognl-3.0.1.jar

???? struts2-core-2.2.3.jar

???? struts2-json-plugin-2.2.3.jar

???? xwork-core-2.2.3.jar

?

2、在web.xml中添加struts2配置

<!-- struts2在web.xml中的配置 -->
	<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>

?

3、struts.xml配置

<?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.devMode" value="fasle" />
	<constant name="struts.i18n.encoding" value="utf-8" />

	<package name="default" extends="json-default" namespace="/test">
		<action name="json" class="com.yjw.action.jsonAction" method="checkLogin">
			<result name="success" type="json">/index.jsp</result>
		</action>
	</package>

</struts>

?

4、添加jQuery js包

??? WebRoot/scripts/jquery-1.6.1.js

?

5、src/com/yjw/action/jsonAction.java

package com.yjw.action;

import java.io.Serializable;

import com.opensymphony.xwork2.ActionSupport;

public class jsonAction extends ActionSupport implements Serializable {
	private String userName;
	private int isExist;
	
	public int getIsExist() {
		return isExist;
	}

	public void setIsExist(int isExist) {
		this.isExist = isExist;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String checkLogin() {
		if(this.userName.equals("admin")){
			this.userName = "yjw";
			this.isExist = 1;
		}else{
			this.setIsExist(0);
		}
		return SUCCESS;
	}
}

?

6、WebRoot/index.jsp

<%@ 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>用户名验证</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="Content-Type" content="text/html;charset=UTF-8">

		<script type="text/javascript" src="scripts/jquery-1.6.1.js"></script>
		<style t