========================Web 2.0==========================
特点:
1.用户贡献内容
2.内容聚合
3.更丰富的"用户体验"
不刷新窗口
1.自动补全
2.每个"窗口"可以关闭、最小化和进行个性化设置
3.内容聚合
========================Ajax==========================
无刷新:不刷新整个页面,只刷新局部
典型:登录
优势:
提供连续的用户体验
提供类似C/S的交互,操作更方便
Ajax(Asynchronous JavaScript And Xml):只刷新局部页面的技术
Asynchronous : 发送请求后不等返回结果,由回调函数处理结果
JavaScript :更新局部的网页
Xml :请求数据和响应数据的封装
XMLHttpRequest对象 :发送请求到服务器并获得返回结果
=========================★★★JavaScript对象XMLHttpRequest★★★===================
1.核心
2.提供异步发送请求的能力
方法
a.open(method,URL,async)
1)建立与服务器的连接
2)method参数指定请求的HTTP方法,典型的值是GET或POST
3)URL参数指定请求的地址
4)async参数指定是否使用异步请求,其值为true或false
b.send(content)
1)发送请求
2)content参数指定请求的参数 2
c.setRequestHeader(header,value)
设置请求的头信息
属性
1.onreadystatechange:指定回调函数
2.readystate: XMLHttpRequest的状态信息
0 : XMLHttpRequest对象没有完成初始化
1 : XMLHttpRequest对象开始发送请求
2 : XMLHttpRequest对象的请求发送完成
3 : XMLHttpRequest对象开始读取响应,还没有结束
4 : XMLHttpRequest对象读取响应结束
3.status:HTTP的状态码
200 : 服务器响应正常
400 : 无法找到请求的资源
403 : 没有访问权限
404 : 访问的资源不存在
500 : 服务器内部错误
4.responseText:获得响应的文本内容
5.responseXML:获得响应的XML文档对象
===================================$.ajax()================================
jQuery常用Ajax方法
1)$.ajax()
2)$.get()
3)$.post()
4)$.getJSON()
5)$(选择器).load()
$.ajax()
1.语法:$.ajax([setting]);
2.常用函数参数
String url : 发送请求的地址,默认为当前页地址
String type : 请求方式(POST或GET,默认为GET)
Number timeout : 设置请求超时时间
Object data : 或
String data : 发送到服务器的数据
String dataType : 预期服务器返回的数据类型,包括:XML、HTML、Script、JSON、JSONP、text
boolean global : 表示是否触发全局Ajax事件,默认为true
function beforeSend(XMLHttpRequest xhr) : 发送请求前调用的函数
参数xhr:可选
function complete(XMLHttpRequest xhr,String ts) : 请求完成后调用的函数
参数xhr:可选
参数ts:可选,描述请求类型的字符串
function success(Object result,String ts) : 请求成功后调用的函数
参数result:可选,由服务器返回的数据
参数ts:可选,描述请求类型的字符串
function error(XMLHttpRequest xhr,String em,Exception e) : 请求失败时被调用的函数
参数xhr:可选
参数em:可选,错误信息
参数e:可选,捕获的异常对象
=======================使用Ajax验证用户名=======================
一、传统Ajax实现
缺点:方法、属性、常用值太多 ; 步骤繁琐 ; 浏览器兼容
1.实现无刷新用户名验证
a.当用户名文本框失去焦点时,发送请求到服务器,判断用户名是否存在
b.如果已经存在则提示:“用户名已被可用”
c.如果不存在则提示:“用户名可以可用”
2.使用文本框的onBlur事件
3.使用Ajax技术实现异步交互
a.创建XMLHttpRequest对象
b.通过 XMLHttpRequest对象设置请求信息
c.创建回调函数,根据响应状态动态更新页面( xhr.onreadystatechange = function(){};)
d.向服务器发送请求
范例:
//1.checkname.jsp
1 <form name="form1" action="" method="post"> 2 <lable for="username">用户名</lable> 3 <input type="text" id="username" name="username" onblur="checkUserExists()" /> 5 <div id="mess" style="display: inline"/> 6 </form>
//2.使用JavaScript验证用户名- checkname.jsp
1 function checkUserExists() { 2 var f = document.form1; 3 var username = f.username.value; 4 if (username == "") { 5 alert("用户名不能为空"); 6 return false; 7 } else { 8 doAjax("CheckUserServlet?username=" + username); 9 } 10 }
//3.使用Ajax进行处理-checkname.jsp
1 function doAjax(url) { 2 var xhr; 3 //1. 创建XMLHttpRequest对象 4 if (window.ActiveXObject) { 5 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 6 } else if (window.XMLHttpRequest) { 7 xhr = new XMLHttpRequest(); 8 } 9 10 //2. 设置需要打开的方式 11 xhr.open("post", url, true); 12 //如果以post方式请求,必须要添加 13 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 14 15 //3. 设置回调函数 16 if (xhr.readyState == 4) { 17 var messdiv = document.getElementById("mess"); 18 if (xhr.status == 200) { 19 if (xmlhttp.responseText == "false") { 20 messdiv.innerHTML = "用户名可以使用"; 21 } else { 22 messdiv.innerHTML = "用户名已被使用"; 23 } 24 } else { 25 alert("请求处理返回的数据有错误"); 26 } 27 } 28 29 //4. 发送消息 30 xhr.send(null); 31 }
二、jQuery实现Ajax(即,$.ajax()实现)
1.实现无刷新用户名验证(同上)
2.使用$.ajax() 实现异步交互
1 $.ajax({ 2 url : url, //要提交的URL路径 3 type : "get", //发送请求的方式 4 data : data, //要发送到服务器的数据 5 dataType : "text", //指定传输的数据格式 6 success : function(result) { //请求成功后要执行的代码 7 }, 8 error : function() { //请求失败后要执行的代码 9 } 10 });
jQuery的ajax方法获取json数据
1 $.ajax({ 2 url : url, //要提交的URL路径 3 type : "get", //发送请求的方式 4 data : data, //要发送到服务器的数据 5 dataType : "json", //指定传输的数据格式为json 6 success : function(result) { //请求成功后要执行的代码 7 }, 8 error : function() { //请求失败后要执行的代码 9 } 10 });
范例:
1.index.jsp
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> --%> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title>网页标题</title> 15 <!-- 引用bootstrap样式 --> 16 <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"> 17 </head> 18 <body> 19 <div class="container-fluid"> 20 <!-- Nav tabs --> 21 <ul class="nav nav-tabs" role="tablist"> 22 <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li> 23 <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li> 24 <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li> 25 <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li> 26 </ul> 27 28 <!-- Tab panes --> 29 <div class="tab-content"> 30 <div role="tabpanel" class="tab-pane fade in active" id="home" data-url="reg.jsp"> 31 主页内容 32 </div> 33 <div role="tabpanel" class="tab-pane fade" id="profile"> 34 个人页面 35 </div> 36 <div role="tabpanel" class="tab-pane fade" id="messages"> 37 消息页面 38 </div> 39 <div role="tabpanel" class="tab-pane fade" id="settings"> 40 设置页面 41 </div> 42 </div> 43 </div> 44 45 <!-- 引用外部JS文件 --> 46 <script type="text/javascript" src="../js/jquery-2.2.4.js"></script> 47 <script type="text/javascript" src="../js/bootstrap.min.js"></script> 48 49 <script type="text/javascript"> 50 $(function() { 51 $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) { 52 //e.target // newly activated tab 53 //e.relatedTarget // previous active tab 54 //console.log(e.relatedTarget); 55 var $tab = $($(e.target).attr('href')); 56 $tab.load($tab.data('url')); 57 }); 58 }); 59 </script> 60 </body> 61 </html>
2.ValidNameServlet.java
1 package com.Elastic.AjaxDemo.ivy.controller; 2 import java.io.IOException; 3 import java.io.PrintWriter; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 /** 10 * Servlet implementation class ValidNameServlet 11 */ 12 public class ValidNameServlet extends HttpServlet { 13 private static final long serialVersionUID = 1L; 14 15 /** 16 * @see HttpServlet#HttpServlet() 17 */ 18 public ValidNameServlet() { 19 super(); 20 // TODO Auto-generated constructor stub 21 } 22 23 /** 24 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 25 */ 26 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 27 //获得客户端发来的用户名和密码 28 String userName = request.getParameter("userName"); 29 String passWord = request.getParameter("password"); 30 System.out.println(userName); 31 System.out.println(passWord); 32 33 PrintWriter out = response.getWriter(); 34 out.print(true); 35 out.flush(); 36 } 37 38 /** 39 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 40 */ 41 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 42 // TODO Auto-generated method stub 43 doGet(request, response); 44 } 46 }
3.reg.jsp
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> --%> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title>网页标题</title> 15 <!-- 引用bootstrap样式 --> 16 <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"> 17 </head> 18 <body> 19 <div class="container-fluid"> 20 <h1 class="text-center">注册</h1> 21 <form class="form-horizontal" role="form" action="" name="regForm"> 22 <div class="form-group"> 23 <label for="userName" class="col-sm-2 control-label">用户名:</label> 24 <div class="col-sm-10"> 25 <input type="text" class="form-control" id="userName" name="userName" placeholder="QQ/邮箱/手机号" autocomplete="off" onblur="checkUserExists()"> 26 <span id="msg"></span> 27 </div> 28 </div> 29 <div class="form-group"> 30 <label for="password" class="col-sm-2 control-label">密码:</label> 31 <div class="col-sm-10"> 32 <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码" autocomplete="off" onblur="checkUserExists1()"> 33 <span id="msg1"></span> 34 </div> 35 </div> 36 </form> 37 </div> 38 39 <!-- 引用外部JS文件 --> 40 <script type="text/javascript" src="../js/jquery-2.2.4.js"></script> 41 <script type="text/javascript" src="../js/bootstrap.min.js"></script> 42 <!-- <script type="text/javascript"> 43 44 function checkUserExists() { 45 var form = document.regForm; 46 var value = form.userName.value; 47 if ("" == value) { 48 document.getElementById("msg").innerHTML = "用户名不能为空!"; 49 } else { 50 //进行ajax验证 51 doAjax("../validName?userName=" + value); 52 } 53 } 54 55 function checkUserExists1() { 56 var form = document.regForm; 57 var value = form.password.value; 58 if ("" == value) { 59 // ★id唯一★ 60 document.getElementById("msg1").innerHTML = "密码不能为空!"; 61 } else { 62 //进行ajax验证 63 doAjax("../validName?password=" + value); 64 } 65 } 66 67 function doAjax(url) { 68 //1.创建XMLHttpRequest对象 69 alert(); 70 var xhr = null; 71 if (window.ActiveXObject) {// 判断是否是IE浏览器 72 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 73 } else if (window.XMLHttpRequest){ 74 xhr = new XMLHttpRequest(); 75 } 76 if (null == xhr) { 77 alert("浏览器不支持Ajax操作"); 78 } 79 console.log(xhr); 80 81 //2.设置请求的信息 82 xhr.open("get", url, true); 83 84 //3.设置回调函数 85 xhr.onreadystatechange = function() { 86 if (xhr.readyState == 4) { 87 if (xhr.status == 200) { 88 //响应服务器的内容 89 console.log("输出服务器发回的内容"); 90 console.log(xhr.responseText); 91 } else { 92 console.log("服务器响应错误!"); 93 } 94 } 95 }; 96 97 //4.发送请求 98 xhr.send(null); 99 } 100 </script> --> 101 102 <script type="text/javascript"> 103 //使用jQuery的Ajax方式 104 $(function() { 105 $('#userName').blur(function() { 106 var value = $(this).val(); 107 $.ajax({ 108 url : 'validName', 109 type : 'post', 110 data : {userName : value}, 111 dataType : 'json', 112 beforeSend : function() { 113 if ('' == value) { 114 $('#msg').html('用户名不能为空!'); 115 return false; 116 } 117 if (value.length < 6) { 118 $('#msg').html('用户名长度不能小于6位!'); 119 return false; 120 } 121 return true; 122 }, 123 success : function(result) { 124 console.log(result); 125 }, 126 error : function() { 127 alert('服务器错误'); 128 } 129 }); 130 }); 131 132 $('#password').blur(function() { 133 var value = $(this).val(); 134 $.ajax({ 135 url : 'validName', 136 type : 'post', 137 data : {password : value}, 138 dataType : 'json', 139 beforeSend : function() { 140 if ('' == value) { 141 // ★id唯一★ 142 $('#msg1').html('密码不能为空!'); 143 return false; 144 } 145 if (value.length > 12 || value.length < 6 ) { 146 $('#msg1').html('密码长度6-12位!'); 147 return false; 148 } 149 return true; 150 }, 151 success : function(result) { 152 console.log(result); 153 }, 154 error : function() { 155 alert('服务器错误'); 156 } 157 }); 158 }); 159 }); 160 </script> 161 </body> 162 </html>
=============================范例:无刷新技术===========================
1.dao包
a.BaseDao 类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.dao; 5 6 import java.sql.Connection; 7 import java.sql.DriverManager; 8 import java.sql.PreparedStatement; 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 import java.util.List; 12 13 import com.mysql.jdbc.Statement; 14 15 /** 16 * 描述类的基本功能<br/> 17 * <p> 18 * <h3>具体功能发布描述</h3> 19 * </p> 20 * @author Ivy 21 * @version 1.0 22 * @date 2016年6月12日 上午11:00:00 23 * @copyright Elastic 24 */ 25 public class BaseDao { 26 27 28 private static String url = "jdbc:mysql://localhost:3306/systemdemo"; 29 private static String user = "root"; 30 private static String password = "root"; 31 32 /** 33 * 获取数据库连接对象 34 * 35 * @return 36 */ 37 public static Connection getConnection() { 38 39 try { 40 Class.forName("com.mysql.jdbc.Driver"); 41 return DriverManager.getConnection(url, user, password); 42 } catch (ClassNotFoundException e) { 43 e.printStackTrace(); 44 } catch (SQLException e) { 45 e.printStackTrace(); 46 } 47 return null; 48 } 49 50 public static int executeUpdate(String sql, List<?> params) { 51 52 // 准备变量,用来保存数据库连接对象,执行命令的对象和结果 53 Connection conn = null; 54 PreparedStatement pstmt = null; 55 int rows; 56 try { 57 // 获取数据连接对象 58 conn = getConnection(); 59 pstmt = conn.prepareStatement(sql); 60 // 设置参数 61 if (params != null && params.size() > 0) { 62 63 for (int i = 0; i < params.size(); i++) { 64 pstmt.setObject(i + 1, params.get(i)); 65 } 66 } 67 rows = pstmt.executeUpdate(); 68 } catch (SQLException e) { 69 e.printStackTrace(); 70 rows = -1; 71 } finally { 72 closeAll(null, pstmt, conn); 73 } 74 return rows; 75 76 } 77 78 /** 79 * 释放资源 80 * 81 * @param rs 82 * 结果集对象,如果没有填写null 83 * @param pstmt 84 * 执行SQL语句的对象,如果没有填写null 85 * @param conn 86 * 数据库连接对象,如果没有填写null 87 */ 88 public static void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) { 89 90 try { 91 if (rs != null) { 92 rs.close(); 93 } 94 if (pstmt != null) { 95 pstmt.close(); 96 } 97 if (conn != null) { 98 conn.close(); 99 } 100 } catch (SQLException e) { 101 e.printStackTrace(); 102 } 103 104 } 105 106 }
b.UserDao 类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.dao; 5 6 import java.io.Serializable; 7 8 import com.Elastic.SystemDemo.ivy.entity.User; 9 10 /** 11 * 描述类的基本功能<br/> 12 * <p> 13 * <h3>具体功能发布描述</h3> 14 * </p> 15 * @author Ivy 16 * @version 1.0 17 * @date 2016年6月12日 下午3:38:15 18 * @copyright Elastic 19 */ 20 public interface UserDao { 21 User find(Serializable id); 22 }
2.dao.impl包
a.UserDaoImpl 类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.dao.impl; 5 6 import java.io.Serializable; 7 import java.sql.Connection; 8 import java.sql.PreparedStatement; 9 import java.sql.ResultSet; 10 import java.sql.SQLException; 11 12 import com.Elastic.SystemDemo.ivy.dao.BaseDao; 13 import com.Elastic.SystemDemo.ivy.dao.UserDao; 14 import com.Elastic.SystemDemo.ivy.entity.User; 15 import com.mysql.jdbc.Statement; 16 17 18 /** 19 * 描述类的基本功能<br/> 20 * <p> 21 * <h3>具体功能发布描述</h3> 22 * </p> 23 * @author Ivy 24 * @version 1.0 25 * @date 2016年6月12日 下午3:37:36 26 * @copyright Elastic 27 */ 28 public class UserDaoImpl implements UserDao{ 29 30 /* (non-Javadoc) 31 * @see com.Elastic.SystemDemo.ivy.dao.UserDao#find(java.io.Serializable) 32 */ 33 @Override 34 public User find(Serializable id) { 35 User user = null; 36 String sql = "select * from user where userName = ?"; 37 // 定义查询需要使用的SQL对象 38 Connection conn = null; 39 PreparedStatement pstmt = null; 40 ResultSet rs = null; 41 42 try { 43 conn = BaseDao.getConnection(); 44 pstmt = conn.prepareStatement(sql); 45 pstmt.setObject(1, id); 46 47 rs = pstmt.executeQuery(); 48 49 if (rs.next()) { 50 user = new User(); 51 user.setUserName(rs.getString("userName")); 52 user.setPassWord(rs.getString("passWord")); 53 user.setNickName(rs.getString("nickName")); 54 } 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 user = null; 58 } finally { 59 BaseDao.closeAll(rs, pstmt, conn); 60 } 61 62 return user; 63 } 64 65 }
3.entity包
a.User类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.entity; 5 6 import java.io.Serializable; 7 8 /** 9 * 描述类的基本功能<br/> 10 * <p> 11 * <h3>具体功能发布描述</h3> 12 * </p> 13 * @author Ivy 14 * @version 1.0 15 * @date 2016年6月12日 下午3:39:14 16 * @copyright Elastic 17 */ 18 public class User implements Serializable{ 19 private String userName; 20 private String passWord; 21 private String nickName; 22 public String getUserName() { 23 return userName; 24 } 25 public void setUserName(String userName) { 26 this.userName = userName; 27 } 28 public String getPassWord() { 29 return passWord; 30 } 31 public void setPassWord(String passWord) { 32 this.passWord = passWord; 33 } 34 public String getNickName() { 35 return nickName; 36 } 37 public void setNickName(String nickName) { 38 this.nickName = nickName; 39 } 40 41 }
4.control包
a.UserServlet 类
1 package com.Elastic.SystemDemo.ivy.control; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import javax.servlet.http.HttpSession; 11 12 import com.Elastic.SystemDemo.ivy.entity.User; 13 import com.Elastic.SystemDemo.ivy.service.UserService; 14 import com.Elastic.SystemDemo.ivy.service.impl.UserServiceImpl; 15 16 /** 17 * Servlet implementation class UserServlet 18 */ 19 public class UserServlet extends HttpServlet { 20 private static final long serialVersionUID = 1L; 21 22 /** 23 * @see HttpServlet#HttpServlet() 24 */ 25 public UserServlet() { 26 super(); 27 // TODO Auto-generated constructor stub 28 } 29 30 /** 31 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 32 */ 33 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 34 //获取表单提交的内容 35 String userName = request.getParameter("userName"); 36 String passWord = request.getParameter("passWord"); 37 38 //创建业务对象 39 UserService userService = new UserServiceImpl(); 40 User user = userService.login(userName, passWord); 41 String msg = ""; 42 boolean success; 43 String data = ""; 44 45 if (null == user) { 46 success = false; 47 msg = "登录失败!"; 48 } else { 49 success = true; 50 51 //保存登录信息到session中 52 HttpSession session = request.getSession(); 53 session.setAttribute("loginUser", user); 54 msg = "登录成功!"; 55 56 //键值对 57 data = "{"userName" : " " + user.getUserName() + " "}"; 58 } 59 60 //响应Ajax请求的信息 61 PrintWriter out = response.getWriter(); 62 //json对象 63 out.write("{"success" : " + success + ","msg":"" + msg + "","data" : " + data + "}"); 64 //刷新 65 out.flush(); 66 //关闭资源 67 out.close(); 68 } 69 70 /** 71 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 72 */ 73 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 74 // TODO Auto-generated method stub 75 doGet(request, response); 76 } 77 78 }
b.SystemServlet 类
1 package com.Elastic.SystemDemo.ivy.control; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 /** 10 * Servlet implementation class SystemServlet 11 */ 12 public class SystemServlet extends HttpServlet { 13 private static final long serialVersionUID = 1L; 14 15 /** 16 * @see HttpServlet#HttpServlet() 17 */ 18 public SystemServlet() { 19 super(); 20 // TODO Auto-generated constructor stub 21 } 22 23 /** 24 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 25 */ 26 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 27 // TODO Auto-generated method stub 28 this.doPost(request, response); 29 } 30 31 /** 32 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 request.getSession().invalidate(); 36 } 37 38 }
5.filter包
a.EncodingFilter 类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.filter; 5 6 import java.io.IOException; 7 8 import javax.servlet.Filter; 9 import javax.servlet.FilterChain; 10 import javax.servlet.FilterConfig; 11 import javax.servlet.ServletException; 12 import javax.servlet.ServletRequest; 13 import javax.servlet.ServletResponse; 14 15 /** 16 * 描述类的基本功能<br/> 17 * <p> 18 * <h3>具体功能发布描述</h3> 19 * </p> 20 * @author Ivy 21 * @version 1.0 22 * @date 2016年6月12日 下午4:14:39 23 * @copyright Elastic 24 */ 25 public class EncodingFilter implements Filter{ 26 27 /* (non-Javadoc) 28 * @see javax.servlet.Filter#destroy() 29 */ 30 @Override 31 public void destroy() { 32 // TODO Auto-generated method stub 33 34 } 35 36 /* (non-Javadoc) 37 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 38 */ 39 @Override 40 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 41 throws IOException, ServletException { 42 request.setCharacterEncoding("utf-8"); 43 response.setCharacterEncoding("utf-8"); 44 chain.doFilter(request, response); 45 } 46 47 /* (non-Javadoc) 48 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 49 */ 50 @Override 51 public void init(FilterConfig arg0) throws ServletException { 52 // TODO Auto-generated method stub 53 54 } 55 56 }
6.service包
a.UserService类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.service; 5 6 import com.Elastic.SystemDemo.ivy.entity.User; 7 8 /** 9 * 描述类的基本功能<br/> 10 * <p> 11 * <h3>具体功能发布描述</h3> 12 * </p> 13 * @author Ivy 14 * @version 1.0 15 * @date 2016年6月12日 下午3:47:32 16 * @copyright Elastic 17 */ 18 public interface UserService { 19 User login(String userName, String passWord); 20 }
7.service.impl包
a.UserServiceImpl 类
1 /** 2 * 3 */ 4 package com.Elastic.SystemDemo.ivy.service.impl; 5 6 import com.Elastic.SystemDemo.ivy.dao.UserDao; 7 import com.Elastic.SystemDemo.ivy.dao.impl.UserDaoImpl; 8 import com.Elastic.SystemDemo.ivy.entity.User; 9 import com.Elastic.SystemDemo.ivy.service.UserService; 10 11 /** 12 * 描述类的基本功能<br/> 13 * <p> 14 * <h3>具体功能发布描述</h3> 15 * </p> 16 * @author Ivy 17 * @version 1.0 18 * @date 2016年6月12日 下午3:49:21 19 * @copyright Elastic 20 */ 21 public class UserServiceImpl implements UserService { 22 private UserDao userDao = new UserDaoImpl(); 23 24 /* (non-Javadoc) 25 * @see com.Elastic.SystemDemo.ivy.service.UserService#login(java.lang.String, java.lang.String) 26 */ 27 @Override 28 public User login(String userName, String passWord) { 29 User user = userDao.find(userName); 30 if (null != user && user.getPassWord().equals(passWord)) { 31 // 密码设为null,不记录passWord 32 user.setPassWord(null); 33 return user; 34 } 35 return null; 36 } 37 38 }
8.jsp文件
a.nav-top.jsp
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 6 7 <c:if test="${empty sessionScope.loginUser }"> 8 <ul class="list-inline pull-right"> 9 <li><a href="javascript:;" data-toggle="show-login">登录</a></li> 10 <li><a href="javascript:;" data-toggle="reg">注册</a></li> 11 </ul> 12 </c:if> 13 14 <c:if test="${not empty sessionScope.loginUser }"> 15 <ul class="list-inline pull-right"> 16 <li><a href="javascript:;" >${sessionScope.loginUser.nickName}</a></li> 17 <li><a href="javascript:;" data-toggle="logout">退出</a></li> 18 </ul> 19 </c:if>
b.login.jsp
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 6 7 <!-- 局部页面 --> 8 <div class="panel panel-default" style="300px;"> 9 <div class="panel panel-heading">登录</div> 10 <div class="panel panel-body"> 11 <form action="" class="form-horizontal" id="login-form"> 12 <div class="form-group"> 13 <label for="userName" class="col-md-3 control-label">账号:</label> 14 <div class="col-md-9"> 15 <input class="form-control" id="userName" name="userName" type="text" autocomplete="off"/> 16 </div> 17 <div class="col-md-12"></div> 18 </div> 19 <div class="form-group"> 20 <label for="passWord" class="col-md-3 control-label">密码:</label> 21 <div class="col-md-9"> 22 <input class="form-control" id="passWord" name="passWord" type="password" autocomplete="off"/> 23 </div> 24 <div class="col-md-12"></div> 25 </div> 26 <div class="form-group"> 27 <a class="btn btn-primary btn-block" data-toggle="login">登录</a> 28 </div> 29 <div class="form-group" class="text-center"> 30 31 </div> 32 </form> 33 </div> 34 35 </div> 36 37 <script type="text/javascript"> 38 $(function() { 39 $('a[data-toggle="login"]').on('click',function(){ 40 $.ajax({ 41 url : '<%=request.getContextPath() %>/user/login', 42 type : 'post', 43 dataType : 'json', 44 data : $('#login-form').serialize(), 45 beforeSend : function () { 46 //return false; 47 var userName = $('#userName').val(); 48 if ('' == userName) { 49 //alert('用户名不为空'); 50 $('#userName').parent().next().html('账户不能为空'); 51 return false; 52 } else { 53 $('#userName').parent().next().html(''); 54 } 55 56 var passWord = $('#passWord').val(); 57 if ('' == passWord) { 58 //alert('密码不为空'); 59 $('#passWord').parent().next().html('密码不能为空'); 60 return false; 61 } else { 62 $('#passWord').parent().next().html(''); 63 } 64 }, 65 success : function (result) { 66 console.log(result); 67 if (result.success) { 68 $('a[data-toggle="show-login"]').trigger('click'); 69 //$('#nav-top').html(result.data.userName); 70 $('#nav-top').load('nav-top.jsp'); 71 } 72 }, 73 error : function() { 74 //alert('服务器异常!'); 75 $('#login-form').children().last().html('服务器异常!'); 76 } 77 }); 78 }); 79 }); 80 </script> 81 82
c.index.jsp
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title></title> 15 <!-- 引用bootstrap样式 --> 16 <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/bootstrap.min.css"> 17 </head> 18 <body> 19 <div class="container-fluid"> 20 <div class="container" id="nav-top"> 21 <!-- <ul class="list-unstyle pull-right"> 22 <li><a href="javascript:;" data-toggle="show-login">登录</a></li> 23 <li><a href="javascript:;" data-toggle="reg">注册</a></li> 24 </ul> --> 25 <jsp:include page="nav-top.jsp" flush="true"></jsp:include> 26 </div> 27 </div> 28 29 <!-- 引用外部JS文件 --> 30 <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-2.2.4.js"></script> 31 <script type="text/javascript" src="<%=request.getContextPath() %>/js/bootstrap.min.js"></script> 32 <script type="text/javascript"> 33 $(function(){ 34 /* nav-top.jsp里面的登录,注册,退出 */ 35 $('#nav-top').on('click','a[data-toggle="logout"]',function(){ 36 $.ajax({ 37 /* Servlet虚拟路径 */ 38 url : '<%=request.getContextPath() %>/user/logout', 39 success : function(result) { 40 $('#nav-top').load('nav-top.jsp'); 41 } 42 }); 43 }); 44 45 $('#nav-top').on('click','a[data-toggle="show-login"]',function(){ 46 47 var isShow = $(this).data('show'); 48 if(isShow){ 49 $(this).data('showContent').remove(); 50 $(this).data('show',false); 51 return; 52 } 53 54 //创建一个浮动的登录层 55 var $div = $('<div id="ajax-login" class=""></div>'); 56 $(this).data('show',true); 57 $(this).data('showContent',$div); 58 59 $div.css({ 60 'position' : 'absolute', 61 'z-index' : '99', 62 'width' : '300px', 63 'height' : '300px', 64 65 'top' : ($(document).width - 300) / 2 + 'px', 66 'left' : ($(document).height - 300) / 2 + 'px' 67 }); 68 69 $div.load('login.jsp'); 70 $('body').append($div); 71 72 }); 73 }); 74 </script> 75 </body> 76 </html>