(1)取得服务端当前时间
jquery对象.load(url,sendData,function(backData,textStatus,xhr){... ...}) load():如果无参的话,就以GET方式发送 如果有参的话,就以POST方式发送 (2)检查注册用户名是否存在 $.get(url,sendData,function(backData,textStatus,xhr){... ...}) $.post(url,sendData,function(backData,textStatus,xhr){... ...})getTime.jsp
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 3 4 5 6 7 8 9
10 11 27 28
TimeServlet.java
1 package cn.itcast.web.servlet; 2 3 import java.io.IOException; 4 import java.text.DateFormat; 5 import java.util.Date; 6 import java.util.Locale; 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 12 public class TimeServlet extends HttpServlet {13 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {14 DateFormat df = DateFormat.getDateTimeInstance(15 DateFormat.FULL,16 DateFormat.DEFAULT, 17 Locale.CHINA);18 String now = df.format(new Date());19 response.setContentType("text/html;charset=UTF-8");20 response.getWriter().write(now);21 }22 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {23 request.setCharacterEncoding("UTF-8");24 response.setContentType("text/html;charset=UTF-8");25 String ip = request.getRemoteAddr();26 if(ip.equals("127.0.0.1")){27 String username = request.getParameter("username");28 String password = request.getParameter("password");29 response.getWriter().write(username+":"+password);30 }31 }32 }
ajax_2.jsp 调用$.get()方法
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 3 4 5 6 7 8 用户名[GET]: 9 40 41
ajax_3.jsp调用 $.post()方法
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 3 4 5 6 7 8 用户名[POST]: 9 10 42 43
UserServlet.java
1 package cn.itcast.web.servlet; 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 public class UserServlet extends HttpServlet {10 public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {11 String username = request.getParameter("username");12 byte[] buf = username.getBytes("ISO8859-1");13 username = new String(buf,"UTF-8");14 String imagePath = "images/MsgSent.gif";15 if("哈哈".equals(username)){16 imagePath = "images/MsgError.gif";17 }18 response.setContentType("text/html;charset=UTF-8");19 response.getWriter().write(imagePath);20 }21 public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {22 request.setCharacterEncoding("UTF-8");23 String username = request.getParameter("username");24 String imagePath = "images/MsgSent.gif";25 if("哈哈".equals(username)){26 imagePath = "images/MsgError.gif";27 }28 response.setContentType("text/html;charset=UTF-8");29 response.getWriter().write(imagePath);30 }31 }