http://www.myexception.cn/ajax/770130.html


登陆页面login.jsp

$.ajax( {
			    url :"<%=basePath%>euser/euser_login.action",
			    type :"post",
			    dataType :"json",
			    data :"username=" + $("#username").val()
			      + "&password=" + $("#password").val() + "&vercode=" + $("#vercode").val(),
			 //   timeout :20000,// 设置请求超时时间(毫秒)。
			    error : function() {// 请求失败时调用函数。
			     $("#loginResult").html("请求失败!");
			    },
			    success :function (data){
				    //alert(data);
				    if(1 == data){
							//alert("登陆成功");
						location.href = "<%=basePath%>euser/euser_indexUI.action" ;
					}else if(2 == data){
						$("#username_Info").html("用户名或者密码错误!");
						$("#username").val("");
						$("#password").val("");
						$("#vercode").val("");
						reloadImg();
					    }else if(4 == data){
							$("#vercode_Info").html("验证码错误!");
							reloadImg();
					}
			    }
			   });


Action处理函数

public String login() throws Exception {
		String user_name = (String) getRequest().getParameter("username");
		String pass_word = (String) getRequest().getParameter("password");
		String ver_code = (String) getRequest().getParameter("vercode");
		username = user_name;
		password = pass_word;
		vercode = ver_code;

		Euser EuserForm = new Euser();
		EuserForm.setUsername(username);
		EuserForm.setPassword(password);
		String ver = (String) super.getSession().getAttribute("rand");
		vercode = vercode.trim().toLowerCase();
		super.getSession().setAttribute("rand", null);

		if (null != this.username && !"".equals(this.username.trim())
				&& null != this.password && !"".equals(this.password.trim())) {
			if (null != vercode && !"".equals(vercode) && vercode.equals(ver)) {

				Euser loginEuser = euserService.login(EuserForm);

				if (loginEuser != null) {
					WebUtil.putLoginEuser(super.getRequest(), loginEuser);

					response.setContentType("text/html;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
					PrintWriter out = response.getWriter();
					out.print(LOGIN_SUCCESS);
					out.flush();
					out.close();
					return null;
				} else {
					response.setContentType("text/html;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
					PrintWriter out = response.getWriter();
					out.print(LOGIN_USERNAME_ERROR);
					out.flush();
					out.close();
					return null;
				}

			} else {
				response.setContentType("text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
				PrintWriter out = response.getWriter();
				out.print(LOGIN_VERCODE_ERROR);
				out.flush();
				out.close();
				return null;
			}

		} else {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
			PrintWriter out = response.getWriter();
			out.print(LOGIN_USERNAME_ERROR);
			out.flush();
			out.close();
			return null;
		}
	}

http://www.myexception.cn/ajax/1046465.html


使用jQuery ajax + Struts 一个登陆的例子.

下面是一个Jsp页面的代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<script type="text/javascript" src="/jQuery/jQuery/jquery-1.2.6.pack.js"></script>
<%
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">
   
    /*** 
    jQuery(function(){
		$("#user_name").blur(function(){
			var name= $.trim($("#user_name").val());
			$.ajax({
				url:"/jQuery/myServlet",
				data:{username:name},
				cache:false,
				success:function(data){
					if(data=="true"){
						alert("姓名可以使用!");
					}else{
						alert("姓名不能使用!");
					}	
				}
			})
		})
	});	
***/
	
	//提交;
	function checkSubmit(){
		var bol = true;
		var username = $.trim($("#user_name").val());
		var password = $.trim($("#password").val());
		if(username==null || username==""){
			$("#userDivId").show();
			$("#userDivId").html("用户名不能为空!");
			$("#msgDIVID").hide();
			$("#user_name").focus();
			bol= false;
		}else{
			$("#userDivId").hide();
		}
		
		if(password==null || password==""){
			$("#passDivId").show();
			$("#passDivId").html("密码不能为空!");
			$("#msgDIVID").hide();
			$("#password").focus();
			bol=false;
			
		}else{
			$("#passDivId").hide();
		}
		if(bol!=false){
			$.ajax({
				url:"/jQuery/login.do?p=loginCheck",
				data:{uname:username,upass:password},
				success:function(data){
					if(data=="1"){
						$("#msgDIVID").show();
						$("#msgDIVID").html("恭喜您,登录成功!");
					}else if(data=="2"){
						$("#msgDIVID").show();	
						$("#msgDIVID").html("抱歉,由于你的账号或密码登录失败!");
					}
				}
			});
		}
	}
    </script>
  </head>
  
  <body >
  		<form name="myform">
  		<table>
  		<tr>
  			<td>UserName:</td>
  			<td><input type="text" id="user_name"></td>
  			<td><div id="userDivId" style="border: 0px solid red;width:200px;height:10px;color: red"></div></td>
  		</tr>
  		
  		<tr>
  			<td>PassWord:</td>
  			<td><input type="password" id="password" size="22" name="password" /></td>
  			<td><div id="passDivId" style="border: 0px solid red;width:200px;height:10px;color: red;"></div></td>
  		</tr>
    	
    	<tr>
    		<Td><input type="reset"/ value="重置"></Td>
    		<Td><button name="btnSubmit"     	</tr>
    	
    	</table>
    	
    	<Br>
    	<!-- 显示登陆信息的div层. -->
    	<div id="msgDIVID" style="border:0px solid blue;color: blue;width:400px;height:30;font-weight: bold;font-size: 20px"></div>
    	</form>
  </body>
</html>




下面一个是Struts Action里面的代码:

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package pack.java.demo.struts.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

/** 
 * MyEclipse Struts
 * Creation date: 11-04-2010
 * 
 * XDoclet definition:
 * @struts.action parameter="p" validate="true"
 */
public class LoginAction extends DispatchAction {
	/**
	 * 分发Action;验证登陆方法;
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward loginCheck(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		//根据用户名请求;
		String username=request.getParameter("uname");
		//根据密码请求;
		String password=request.getParameter("upass");
		//因为没有连接数据库,就直接用用户名和密码;
		if(username.equals("zhouhaitao") && password.equals("123456")){
			try {
				response.getWriter().print("1");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				response.getWriter().print("2");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}


http://www.myexception.cn/javascript/627136.html

struts2返回JSON,jquery解析JSON(返回的可能是LIST,MAP,对象,单个值)
//初始加载页面时
$(document).ready(function(){
 //为获取单个值的按钮注册鼠标单击事件
 $("#getMessage").click(function(){
  $.getJSON("jsontest!returnMessage.action",function(data){
   //通过.操作符可以从data.message中获得Action中message的值
   $("#message").html("<font color='red'>"+data.message+"</font>");
  });
 });
 //为获取UserInfo对象按钮添加鼠标单击事件
 $("#getUserInfo").click(function(){
  $.getJSON("jsontest!returnUserInfo.action",function(data){
   //清空显示层中的数据
   $("#message").html("");
   //为显示层添加获取到的数据
   //获取对象的数据用data.userInfo.属性
   $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
          .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
          .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
  });
 });
 //为获取List对象按钮添加鼠标单击事件
 $("#getList").click(function(){
  $.getJSON("jsontest!returnList.action",function(data){
   //清空显示层中的数据
   $("#message").html("");
   //使用jQuery中的each(data,function(){});函数
   //从data.userInfosList获取UserInfo对象放入value之中
   $.each(data.userInfosList,function(i,value){
    $("#message").append("<div>第"+(i+1)+"个用户:</div>")
       .append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
          .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
          .append("<div><font color='red'>密码:"+value.password+"</font></div>");
   });
  });
 });
 //为获取Map对象按钮添加鼠标单击事件
 $("#getMap").click(function(){
  $.getJSON("jsontest!returnMap.action",function(data){
   //清空显示层中的数据
   $("#message").html("");
   //使用jQuery中的each(data,function(){});函数
   //从data.userInfosList获取UserInfo对象放入value之中
   //key值为Map的键值
   $.each(data.userInfosMap,function(key,value){
    $("#message").append("<div><font color='red'>用户ID:"+value.userId+"</font></div>")
          .append("<div><font color='red'>用户名:"+value.userName+"</font></div>")
          .append("<div><font color='red'>密码:"+value.password+"</font></div>");
   });
  });
 });
 //向服务器发送表达数据
 $("#regRe").click(function(){
  //把表单的数据进行序列化
  var params = $("form").serialize();
  //使用jQuery中的$.ajax({});Ajax方法
  $.ajax({
   url:"jsontest!gainUserInfo.action",
   type:"POST",
   data:params,
   dataType:"json",
   success:function(data){
    //清空显示层中的数据
   $("#message").html("");
   //为显示层添加获取到的数据
   //获取对象的数据用data.userInfo.属性
   $("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>")
          .append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>")
          .append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")
   }
  });
 });
});
-