Struts 2 + JQuery + JSon 로그 인 실례
17717 단어 struts2
그리고 json - lib - 2.2.2 - jdk 15. jar, JSON 대상 을 바 꾸 는 데 사용 되 는... ojdbc 14. jar Oacle 드라이버 패키지. jquery - 1.2.6. js 파일.
웹 프로젝트 를 만 들 기 시 작 했 습 니 다. Struts2AjaxDemo 라 는 이름 을 지 었 습 니 다.
가방 을 각각 WEB - INF / lib 가방 아래로 복사 합 니 다.
struts. xml 파일 과 웹. 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>
웹. xml 설정 파일 은 다음 과 같 습 니 다. strtus 2 필 터 를 만 듭 니 다.
<?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 와 상호작용 을 합 니 다. 그리고 사용자 이름과 비밀 번 호 를 판단 하고 로그 인 하 는 방법 등 이 있 습 니 다.
구체 적 인 코드 는 다음 과 같다.
액 션 변경 중, 세 번 의 오 류 를 입력 할 수 있 습 니 다. 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 페이지 로그 인 로그 인 코드 는 다음 과 같 습 니 다.
<%@ 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=" ">
<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>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
한 편의 문장으로 Struts2의 유형 전환을 해결하다우리는 HTTP를 통해 백그라운드에 제출된 데이터가 모두 문자열의 형식이라는 것을 알고 있으며, 우리가 필요로 하는 데이터 형식은 당연히 문자열 형식 하나만 있는 것이 아니다.그래서 우리는 유형 전환이 필요하다!다음...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.