ajax+servlet的网站架构
ajax已经成为了一种非常流行的前端提交数据的方法,他相较于jsp最大的优点是能实现页面局部的刷新。
这里讲一个简单的ajax+servlet实现简单登录网站的例子。网站代码结构如下图。
登录页面代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container" style="text-align:center">
<form class="form-horizontal" role="form" onsubmit="return false" id="login_form">
<div class="form-group">
<label for="username" class="col-lg-2 col-md-2 col-lg-offset-3 col-md-offset-4 control-label">Username: </label>
<div class="col-lg-2 col-md-2">
<input type="text" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-lg-2 col-md-2 col-lg-offset-3 col-md-offset-4 control-label">Password: </label>
<div class="col-lg-2 col-md-2">
<input type="password" class="form-control" id="inputPassword" placeholder="password">
</div>
</div>
<div class="container col-lg-12 col-md-12" >
<div id="warning_box" class="col-lg-3 col-md-3 col-lg-offset-4 col-md-offset-5">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-4">
<label><a href="#" id="forget_pwd">忘记密码 </label>
<label><a href="#"> 注册用户</label>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-2">
<button id="login_btn" class="btn btn-default">登录</button>
</div>
</div>
</form>
</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/jquery.reveal.js"></script>
<script type="text/javascript" src="js/method.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "post",
url: "Login_do",
data: {"username": username,"password":password},
dataType: "json",
success: function(data){
if(data.msg == "true"){
$.cookie("user",username);
$.cookie("userteam",data.userteam);
$.cookie("usertype",data.usertype);
window.open("homepage.html", "_self");//进入homepage欢迎页面
}else{
$("#warning_box").text("用户名或密码错误!").show();
}
},
error: function(){
$("#conn_fail_btn").trigger("click");
}
});
});
$("#forget_pwd").click(function(){
$("#forget_pwd_btn").trigger("click");
<span style="white-space:pre"> </span>});
});
</script>
</body>
</html>
在web.xml的文件中配置登录的servlet,代码中的Login_do
在DAO层
package dao;
import java.sql.*;
import db_connection.DB_Connection;
import t_user.T_User;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
/*import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;*/
public class DAO {
private final String db_driver = "com.ibm.db2.jcc.DB2Driver";
private final String db_url = "jdbc:db2://localhost:8000/DBName";
private final String db_user = "username";
private final String db_pwd = "password";
public boolean verifyUser(final String username, final String password){
boolean isVerified = false;
Connection conn = DB_Connection.getConnection(this.db_driver, this.db_url, this.db_user, this.db_pwd);
Statement stm= null;
ResultSet rs =null;
try{
String sql ="select * from T_USER where USERNAME='"+username+"' and PASSWORD='"+password+"'";
stm = conn.createStatement();
rs = stm.executeQuery(sql);
if(rs.next())
{
isVerified = true;
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
rs.close();
stm.close();
conn.close();
}catch(SQLException e){
System.out.println("there is a sql error!");
e.printStackTrace();
}
}
return isVerified;
} }
建一个简单的T_User的javabean
package t_user;
public class T_User {
private String username;
private String password;
public T_User(final String user){
setUserName(username);
}
public String getUserName(){
return this.username;
}
public void setUserName(final String username){
this.username = username;
}
public String getPassword(){
return this.password;
}
public void setPassword(final String password){
this.password = password;
}
}
连接数据库的类
package db_connection;
import java.sql.*;
public class DB_Connection {
public static Connection getConnection(final String db_driver, final String db_url,final String db_user, final String db_pwd) {
// TODO Auto-generated constructor stub
Connection conn = null;
try{
Class.forName(db_driver);
try{
conn = DriverManager.getConnection(db_url,db_user,db_pwd);
} catch (SQLException e){
System.out.println("Fail to connect to the databse!");
e.printStackTrace();
}
} catch (ClassNotFoundException e){
e.printStackTrace();
}
return conn;
}
public void closeConnection(Connection conn){
try{
if( conn != null){
conn.close();
conn=null;
}
} catch (SQLException e){
e.printStackTrace();
System.out.println("Error in close database:"+e.getMessage());
}
}
}
实现查询用户是否存在的servlet
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DAO;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import t_user.T_User;
public class Login_do extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Constructor of the object.
*/
public Login_do() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String name=request.getParameter("username");
String pwd=request.getParameter("password");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
DAO t_user_query = new DAO();
try{
String check_status = t_user_query.verifyUser(name, pwd) ? "true" : "false";
try{
T_User user = t_user_query.queryUserInfo(name);
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("msg", check_status);
jsonObj.put("userteam", user.getUserTeam());
jsonObj.put("usertype", user.getUserType());
PrintWriter out = response.getWriter();
out.write(jsonObj.toString());
out.flush();
out.close();
out = null;
} catch (JSONException e) {
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
这样一个简单的登录页面就做好了