现在的位置: 首页 > 综合 > 正文

基于tomcat的Ajax + servlet的实现

2014年02月18日 ⁄ 综合 ⁄ 共 5272字 ⁄ 字号 评论关闭
<!--  
  @@  
  @@ <step1>
  @@ 文件: E:\work\Tomcat\conf\server.xml   
  @@ 描述: 添加用户的应用, 并且设置其为默认加载,即在浏览器地址栏输入localhost:8080,   
  @@       则跳入用户应用.用户工程根目录位于:E:\work\Tomcat\webapps\myapp, 需要在  
  @@       server.xml文件的<Host></Host>标签中,加入用户应用. ../webapps/myapp实质上  
  @@       相对于server.xml文件来说,就是E:\work\Tomcat\webapps\myapp  
  @@  
 -->      
<Host name="localhost"  appBase="webapps"  
            unpackWARs="true" autoDeploy="true">  
  
        <!-- SingleSignOn valve, share authentication between web applications  
             Documentation at: /docs/config/valve.html -->  
        <!-- 
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
        -->  
  
        <!-- Access log processes all example.  
             Documentation at: /docs/config/valve.html  
             Note: The pattern used is equivalent to using pattern="common" -->  
          
        <!--(begin) user application-->  
        <Context path="" docBase="../webapps/myapp" debug="0" reloadable="true"/>   
        <!--(end) user application-->  
               
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt"  
               pattern="%h %l %u %t "%r" %s %b" />  
  
</Host>  
<!--  
  @@  
  @@ <step2>
  @@ 文件: E:\work\Tomcat\webapps\myapp\index.jsp
  @@ 描述: 用户应用的欢迎界面,即在浏览器地址栏输入localhost:8080,则跳入直接跳入该页面.  
  @@  
 -->   
<html>
<head>
<TITLE>hello world</TITLE>
</head>

<!-- (begin)用于测试Ajax -->
<script type="text/javascript">  
	var xmlHttpRequest = null; //声明一个空的对象以接受XMLHttpRequest对象  
	function ajaxRequest() {  
		if(window.ActiveXObject) {              //IE的  
			xmlHttpRequest = new ActionXObject("Microsoft.XMLHTTP");  
		}  
		else if(window.XMLHttpRequest) {        //除IE外的  
			xmlHttpRequest = new XMLHttpRequest();  
		}  
		if(xmlHttpRequest != null) {  
			xmlHttpRequest.open("GET", "AjaxServlet", true);  
			//关联好ajax的回调函数  
			xmlHttpRequest.onreadystatechange = ajaxCall;  
			
			// 设置参数, 把"mode"加入http请求头, 其值为"CONFIG"
			xmlHttpRequest.setRequestHeader("mode", "CONFIG");
			
			//真正向服务器发送请求  
			xmlHttpRequest.send();  
		}  
	}   
	function ajaxCall() {  
		if(xmlHttpRequest.readyState == 4 ) {       //完全得到服务器的响应  
			if(xmlHttpRequest.status == 200) {      //没有异常  
				var text = xmlHttpRequest.responseText;  
				document.getElementById("id1").value = text;  
			}  
		}  
	}  
</script>  
<!-- (end)用于测试Ajax -->

<body>

<!-- (begin)用于测试欢迎界面 -->
<!--
  -- 进入欢迎界面后, 系统当前时间显示,如:Now time is: Mon Oct 21 18:00:06 CST 2013 
 -->
<center>
Now time is: <%=new java.util.Date()%>
</center>
<!-- (end)用于测试欢迎界面 -->

<!-- (begin)用于测试Ajax -->
<!-- 
  --点击按钮"button"之后, 页面向后台发送Ajax请求, 后台回应信息后, 在id1输入框中显示
 -->
<input type="button" value="button" onclick="ajaxRequest();">
<input type="text" id="id1">
<!-- (end)用于测试Ajax -->

</body>
</html>
/*
 * Description: 
 * Servlet for ajax, This servlet will parse the input string for web browser(http exchange),
 * get the input parameters, and then execute the related function with the parsed parameter.
 * Finally, sent the executed result to the web browser.
 *
 * Author: lihan@mtncn.com
 * 	
 * Attention:
 * 1) when the parameter carried by the url such as:
 *	$(document).ready(function() {
 *       $("#_submit").click(function() {
 *           var user_name = $("#_user_name").val();
 *           var user_pwd = $("#_user_pwd").val();
 *           $.ajax({
 *               url: "login/validate",
 *               data: { userName: user_name, password: user_pwd },
 *               type: "GET",
 *               datatype: "html",
 *               success: function(data){
 *                   alert(data.length);
 *               }
 *           });
 *       });
 *   })
 * 
 * in the servlet, we get userName and password by : req.getParameter("mode");
 * 
 * 2) when the parameter carried by the http request header such as:
 *	function ajaxRequest() {  
 *		if(window.ActiveXObject) {              //IE
 *			xmlHttpRequest = new ActionXObject("Microsoft.XMLHTTP");  
 *		}  
 *		else if(window.XMLHttpRequest) {        //others
 *			xmlHttpRequest = new XMLHttpRequest();  
 *		}  
 *		if(xmlHttpRequest != null) {  
 *			xmlHttpRequest.open("GET", "AjaxServlet", true);  
 *
 *			xmlHttpRequest.onreadystatechange = ajaxCall;  
 *			
 *			xmlHttpRequest.setRequestHeader("mode", "CONFIG");
 *			
 *			xmlHttpRequest.send();  
 *		}  
 *	} 
 *
 * in the servlet, we get mode by : req.getHeader("mode");
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet extends HttpServlet {  

	@Override  
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
			throws ServletException, IOException { 
		
		String mode = req.getHeader("mode");
		parsePara(req);
		
		PrintWriter out = resp.getWriter();  
		
		out.println(mode);  
		out.flush(); 
		
	}  
	
	private void parsePara(HttpServletRequest req) {
		Enumeration<String> e = req.getHeaderNames();
		 for (; e.hasMoreElements();) {
		       System.out.println(e.nextElement());
		 }
	}
	
}  

<!--
  @@  
  @@ 文件: E:\work\Tomcat\webapps\myapp\WEB-INF\web.xml
  @@ 描述: 
  @@    1) <url-pattern>/AjaxServlet</url-pattern>  -- 以url中含有字符串"/AjaxServlet"
  @@       则认定为Ajax请求
  @@    2) <servlet-class>AjaxServlet</servlet-class>  -- Ajax服务端的servlet为:
  @@       AjaxServlet.class, 由AjaxServlet.java编译得到
  @@  
-->

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

  <display-name>Hello World</display-name>
  <description>
     Welcome to myapp
  </description>

<!--  
<servlet>
	<servlet-name>Test</servlet-name>
	<display-name>Test</display-name>
	<description>A test Servlet</description>
	<servlet-class>com.main.MainLoopService</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>Test</servlet-name>
	<url-pattern>/Test</url-pattern>
</servlet-mapping>
-->

<!--(begin) sevelet for ajax-->
<!--
  -- /AjaxServlet对应于E:\work\Tomcat\webapps\myapp\index.jsp文件中
  -- xmlHttpRequest.open("GET", "AjaxServlet", true); 
 -->

<!--
   <servlet-class>AjaxServlet</servlet-class> 类名对应servlet文件
   AjaxServlet.java
 --> 
<servlet>    
    <servlet-name>AjaxServlet</servlet-name>    
	<display-name>AjaxServlet</display-name>
    <servlet-class>AjaxServlet</servlet-class>    
</servlet>

<!--
  -- /AjaxServlet对应于E:\work\Tomcat\webapps\myapp\index.jsp文件中
  -- xmlHttpRequest.open("GET", "AjaxServlet", true); 
 -->    
<servlet-mapping>    
    <servlet-name>AjaxServlet</servlet-name>    
    <url-pattern>/AjaxServlet</url-pattern>    
</servlet-mapping> 
<!--(end) sevelet for ajax-->

</web-app>
【上篇】
【下篇】

抱歉!评论已关闭.