今天折腾了一个小例子,jsp代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title>jQuery测试</title> <script type="text/javascript" src="js/jquery-1.5.1.js"></script> </head> <script type="text/javascript"> $(function(){ $("#sub").click(function(){ var name=$("#userName").val(); $.ajax({ type:"post",url:"jQueryServlet",data:"name="+name,success:function(msg){ alert(msg); } }); }); }); </script> <body> 用户名: <input type="text" name="name" id="userName"><br> 密 码: <input type="password" id="pwd" name="pwd"><br> <input type="submit" value="提交" id="sub"> </body> </html>web.xml配置如下:
<servlet> <servlet-name>jQuery</servlet-name> <servlet-class>Servlet.jQueryServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>jQuery</servlet-name> <url-pattern>/jQueryServlet</url-pattern> </servlet-mapping>
java类如下:
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; public class jQueryServlet extends HttpServlet{ private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); String name=request.getParameter("name"); PrintWriter write=response.getWriter(); if(name.equals("itzcn")) write.println("恭喜您,"+name+"登录成功"); else write.println("真的非常抱歉!"); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException { this.doPost(request,response); } }
需要注意以下几点:
1、ajax中的url可以使用web.xml中配置好的映射的java类,也可以用其他html页面,js页面
2、java类一定要记得extends HttpServlet
3、如果firebug中提示返回的msg未组织好,并且alert中不能正确打印信息,这表示你应该再java类中添加这一行:response.setContentType("text/plain");,因为servlet的默认返回类型是“text/xml”或者"text/html"
4、需要在/webRoot/js目录下导入jquery-1.5.1.js文件
<script type="text/javascript" src="js/jquery-1.5.1.js"></script>