北大青鳥北京ACCP學(xué)術(shù)部提供:
用Ajax可以在不刷新整個頁面的情況下與服務(wù)器動態(tài)連接
首先創(chuàng)建一個web項目 AjaxLogin
1.首先寫個servlet,用戶輸入的登陸信息被提交到這里servlet中,對用戶輸入的信息判斷
Loginservlet.java
在web.xml中的配置如下(北大青鳥北京)
——————————————————————
package com.login;
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;
public class Loginservlet extends HttpServlet {
public Loginservlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gbk");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass = request.getParameter("pass");
//這里為了方便就硬性的給了兩個值,當(dāng)然你可以從數(shù)據(jù)庫中得到(北大青鳥北京)
if(name.equals("luofang")&&pass.equals("123")){
out.print("suc");//用戶名密碼正確就返回字符suc
} else {
out.print("fail");//失敗就返回字符fail
}
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
}
}
2.現(xiàn)在來寫jsp頁面,其中主要就是寫javascript(北大青鳥北京)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
這樣一個簡單的登陸驗證的小例子就寫好了。其他服務(wù)器端腳本類似。(北大青鳥北京)