Struts2+JQuery+Json登陆实例

在搭建之前.. 首先,需要准备struts2.0框架的5个核心包, 以及jsonplugin-0.32.jar

以及json-lib-2.2.2-jdk15.jar ,用来转换JSON对象的.,ojdbc14.jar oracle驱动包. jquery-1.2.6.js文件。

 

 

开始建立WebProject ,取名为Struts2AjaxDemo

把包分别复制到WEB-INF/lib包下面。

 

建立struts.xml文件 和 web.xml文件。 这个功能,还对数据库进行了操作..数据库代码,贴出来见表的sql语句:

建立表的SQL语句如下:

 

 

 

后台DAO连接Oracle数据库代码:

package pack.java.basedao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import pack.java.vo.User;

public class BaseConnection {
	private static final String USERNAME ="scott";
	private static final String PASSWORD ="tiger";
	private static final String DRIVER ="oracle.jdbc.driver.OracleDriver";
	private static final String URL  = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
	private Connection connection = null;
	private PreparedStatement preparedStatement= null;
	private ResultSet resultSet = null;
	
	
	private Connection getConnection(){
		try {
			Class.forName(DRIVER);
			try {
				 connection =  DriverManager.getConnection(URL, USERNAME, PASSWORD);
				 connection.setAutoCommit(true);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("连接失败!");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("驱动没有找到!");
		}
		return connection;
	}
	
	private PreparedStatement getPreparedStatement(String sql){
		getConnection();
		try {
			preparedStatement =  connection.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		return preparedStatement;
	}
	
	public User getUserByName(String name){
		User user = null;
		String sql = "select userId,username,password,faicount,to_char(lastlogintime,'yyyy-MM-dd hh:mi:ss')tdate from user_info U where U.username = '"+name+"'";
		try {
			resultSet = getPreparedStatement(sql).executeQuery();
			while (resultSet.next()) {
				user = new User();
				user.setId(resultSet.getInt("USERID"));
				user.setName(resultSet.getString("USERNAME"));
				user.setPassword(resultSet.getString("PASSWORD"));
				user.setFaiCount(resultSet.getInt("FAICOUNT"));
				try {
					user.setLastLoginDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(resultSet.getString("tdate")));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeConnection();
		}
		return user;
	}
	
	public Date getDBCurrentTime(){
		String sql = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')as tdate from dual";
		Date date = null;
		try {
			resultSet = getPreparedStatement(sql).executeQuery();
			try {
				while (resultSet.next()) {
					date =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(resultSet.getString("tdate"));
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			closeConnection();
		}
		return date;
	}
	
	public boolean updateFailureCountToUserInfo(int totalNumber,String username){
		String sql = "update User_Info set  FAICOUNT="+totalNumber +" where User_INFO.username =  '"+username+"'";
		
		System.out.println(sql);
		try {
			int i = getPreparedStatement(sql).executeUpdate();
			connection.commit();
			
			return i>0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally{
			closeConnection();
		}
	}
	
	public boolean updateLastLoginTimeToUserInfo(Date lastLogindate,String username){
		String sql = "update USER_INFO set LASTLOGINTIME = to_date('"+new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(lastLogindate)+"','yyyy-MM-dd hh:mi:ss') where username = '"+username+"'";
		System.out.println(sql);
		try {
			int i = getPreparedStatement(sql).executeUpdate();
			return i>0;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally{
			closeConnection();
		}
	}
	
	
	private void closeConnection(){
		if(resultSet!=null){
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(preparedStatement!=null){
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			if(connection!=null && !connection.isClosed()){
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 

 

 

struts.xml配置文件如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "//struts.apache.org/dtds/struts-2.0.dtd" >
<struts>

	<!-- 配置Ajax請求的包; -->
	<package name="pack.java.struts2" extends="json-default">
        <action name="ajaxRequest" class="pack.java.struts2.UserAction">
       		<result type="json" name="ajaxSuccess">   
	                <param name="root">result</param>   
	        </result>
	        <result type="dispatcher" name="success">/main.jsp</result>   
       		<result type="dispatcher" name="failure">/login.jsp</result>
        </action>
    </package>
</struts>

 

 

web.xml配置文件如下:建立strtus2的过滤器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Struts2AjaxDemo</display-name>
  
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>login.jsp</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

建立UserAction文件.与Jquery中的Ajax交互..以及判断用户名和密码, 登陆的方法.等等..

具体代码如下:

改Action中,还具备,输入三次错误.锁定2分钟..功能。

 

package pack.java.struts2;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import pack.java.service.UserService;
import pack.java.service.UserServiceImpl;
import pack.java.vo.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 
 * @author ZhouHaiTao;
 *
 */
public class UserAction extends ActionSupport {

	private static final long serialVersionUID = 5088292503353625986L;
	private UserService userService = new UserServiceImpl();
	private static final int FAILOGINCOUNT = 3;
	private String result;

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	//注入User VO实体;
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}


	/**
	 * 检查用户名是否存在!
	 * @return
	 */
	public String checkUserName(){
		User userInfo = userService.checkUserNameExists(user.getName());
		//判断用户名是否存在!
		if(userInfo!=null){
			result ="User Name okay!";
		}else{
			result = "User Name Not exists!";
		}
		return "ajaxSuccess";
	}

	/**
	 * User Login 
	 * @return string;
	 */
	@SuppressWarnings("unchecked")
	public String userLogin(){
		Map map =new HashMap();
		map.put("name", user.getName());
		map.put("password", user.getPassword());
		boolean bol = true;
		//把map转成json对象;
		JSONObject object =  JSONObject.fromObject(map);
		result = object.toString();

		User userObj = userService.checkUserNameExists(user.getName());
		if(userObj!=null){
			System.out.println("最后登陆日期:"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(userObj.getLastLoginDate()));
			System.out.println("当前数据日期:"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(userService.getDBCurrentTime()));
			
			long mi = countTime(userObj.getLastLoginDate(),userService.getDBCurrentTime());
			System.out.println("时间差分钟:"+mi);
			long i = (2-mi);
			if(i>0){
				ActionContext.getContext().put("timeInfo", "你还需要等待:"+i+"分钟,才能登陆!");
			}
			
			if(userObj.getFaiCount()>=2 && mi<2){
				System.out.println("登陆失败!");
				ActionContext.getContext().put("invaliPassworError", "对不起,你的账户已被系统锁定2分钟,请稍后登陆!");
				return "failure";
			}else{
				if(mi>=2 && userObj.getFaiCount()>=3){
					System.out.println("统一都恢复成0!");
					if(userService.updateFailureCountToUserInfo(0, user.getName())){
						System.out.println("失败总数恢复为0,成功!");
					}else{
						System.out.println("失败总数恢复为0,失败!");
					}
					userService.updateLastLoginTimeToUserInfo(userService.getDBCurrentTime(),user.getName());
					bol = false;
				}
			}
			if(user.getPassword().equals(userObj.getPassword())&& user.getFaiCount()< FAILOGINCOUNT){
				ActionContext.getContext().getSession().put("user", userObj);
				result ="User Name okay!";
				System.out.println("登陆成功!");
				userService.updateFailureCountToUserInfo(0, user.getName());
				if(userService.updateLastLoginTimeToUserInfo(userService.getDBCurrentTime(),user.getName())){
					System.out.println("成功修改数据库最后登陆时间!");
				}else{
					System.out.println("失败修改数据库最后登陆时间!");
				}
				return "success";
			}else{
				System.out.println("登陆失败!");
				if(bol){
					userService.updateFailureCountToUserInfo(userObj.getFaiCount()+1, user.getName());
					ActionContext.getContext().put("invaliPassworError", "Invalid login or password!");
				}
				
				return "failure";
			}
		}else{
			ActionContext.getContext().put("invaliPassworError", "Invalid login or password!");
			return "failure";
		}
	}
	



    /**
     * 计算时间差
     * 
     * @param begin  
     * @param end  
     * @return
     */
	public static long countTime(Date begin,Date end){
		int hour = 0;
		int minute = 0;
		long total_minute = 0;
		StringBuffer sb = new StringBuffer();
		
		Date begin_date = begin;
		Date end_date = end;

		total_minute = (end_date.getTime() - begin_date.getTime())/(1000*60);

		hour = (int) total_minute/60;
		minute = (int) total_minute%60;

		//sb.append("工作时间为:").append(hour).append("小时").append(minute).append("分钟");

		return minute;
	}

public static void main(String[] args) {
	System.out.println(countTime(new Date(),new Date()));
}

}

 

 

JSP页面Login登陆的代码如下:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="scripts/jquery-1.2.6.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax效果</title>

<script type="text/javascript">
    //检查用户名是否存在!
	function onCheckUserName(){
		var url = "ajaxRequest!checkUserName.action";
		
		 var params = {
			 "user.name":jQuery("#name").attr("value"),
			 "user.password":jQuery("#password").attr("value")
		 };  
		 
		 jQuery.getJSON(url,params,function callback(data){
			 jQuery("#divUserName").css("color","red");   
			 jQuery("#divUserName").html(data);
 	        });   
   }
</script>
</head>
<body>
<center>
<form method="post" action="ajaxRequest!userLogin.action" name="myform" id="myform">
<table cellpadding="1" width="40%" cellspacing="0" bordercolor="00FFFF"
	style="text-align: left" border="1px">
	<tr>
		<td width="10%">用户名:</td>
		<td width="10%"><input id="name" name="user.name" type="text" onkeyup="onCheckUserName()"></td>
		<td width="20%">
		<div id="divUserName" style="height: 10px">请输入用户名!</div>
		</td>
	</tr>
	<tr>
		<td width="10%">密码:</td>
		<td width="10%"><input id="password" name="user.password"
			type="password"></td>
		<td>请输入密码![密码必须大于6位]</td>
	</tr>
	<tr>
		<td colspan="2" align="center"><input type="reset" value="重置">&nbsp;&nbsp;&nbsp;&nbsp;
		<input type="submit" value="登陆"></td>
	</tr>
	<tr>
		<Td colspan="3"><div id="loginResultId" style="color:red">${invaliPassworError==null?"":invaliPassworError}</div></Td>
	</tr>
	<tr>
		<Td colspan="3"><div id="timeInfo" style="color:red">${timeInfo==null?"":timeInfo}</div></Td>
	</tr>
	
</table>

<div id="result">

</div>
</form>
</center>
</body>
</html>

 

你可能感兴趣的:(struts2)