ajax+servlet实例

<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"\@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:612.0pt 792.0pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:36.0pt; mso-footer-margin:36.0pt; mso-paper-source:0;} div.Section1 {page:Section1;} -->

页面javascript代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    <title>My JSP 'test.jsp' starting page</title>   
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
    function findreporter(callno){
        alert("@@@@@");
        var url = "<%=request.getContextPath()%>/findreporterservlet?callno=121540076812308vsevyn4ns0wedzaof";
        if (window.XMLHttpRequest) {
          req = new XMLHttpRequest();
        }else if (window.ActiveXObject) {
          req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if(req){
          req.open("GET",url, true);
          req.onreadystatechange = checkcontent;
          req.send(null);
        }
    }
    function checkcontent(){
    if (req.readyState == 4) { // 判断对象状态
     if (req.status == 200) { // 信息已经成功返回,开始处理信息
          if(req.responseText != ""){
            if(req.responseText!=""){
              var returnValue=req.responseText.split("$");
              alert(req.responseText);
              document.getElementById('reporterUserName').value="";
              document.getElementById('reporterUserTel').value="";
              if(returnValue[0] && returnValue[0]!="_")
                document.getElementById('reporterUserName').value=returnValue[0];
              if(returnValue[1] && returnValue[1] != "null" ){

                document.getElementById('reporterUserTel').value=returnValue[1];
              }
            }
          }else{
            document.getElementById('reporterUserName').value="";
            document.getElementById('reporterUserTel').value="";
          }
     } else {//页面不正常
         alert("您所请求的页面有异常。");
     }
    }
    } //都是套路似的,可根据需要灵活运用
    </script>
  </head>
  <body>
    name:<input id="reporterUserName"/><br>
    pwd:<input id="reporterUserTel"/>
    <button value="点击" onclick="findreporter();">点击</button>
  </body>
</html>

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

servlet类   本人用jdbc链接数据库  数据库参数最好写在配置文件中 方便修改


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {
    /**
       * 构造函数
       */
      public TestServlet() {
        super();
      }
      /**
       * destroy
       */
      public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
      }
      /**
       * 获取消息
       * @param request HttpServletRequest
       * @param response HttpServletResponse
       * @throws ServletException
       * @throws IOException
       */
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
          response.setContentType("text/xml; charset=GBK");
            String callno = request.getParameter("callno");
            String returnValue = "";
            //导入新的数据
            String sDBDriver = "oracle.jdbc.driver.OracleDriver";
            String sConnStr = "jdbc:oracle:thin:@192.168.8.127:1521:cityinfo";
            Connection conn = null;
            ResultSet resultSet=null;
            try {
              Class.forName(sDBDriver);
              try {
                conn = DriverManager.getConnection(sConnStr, "cispkuerle", "cispkuerle");
                Statement st = conn.createStatement();
                resultSet = st.executeQuery("select * from t_urp_unit where id = '"+callno+"'");
                while (resultSet.next()) {
                    String name = resultSet.getString("C_NAME");
                    String password = resultSet.getString("PASSWORD");
                    returnValue =name + "$" + password;//返回值设置  此处设置可自由设置
                }
                st.close();
                conn.close();
              } catch (SQLException sqlexception) {
                sqlexception.printStackTrace();
              }
            } catch (ClassNotFoundException classnotfoundexception) {
              classnotfoundexception.printStackTrace();
            }
            response.getWriter().write(returnValue);//返回值
          }
      /**
       * 初始化
       * @param config ServletConfig
       * @throws ServletException gg
       */
      public void init(ServletConfig config) throws ServletException {
      }
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

web.xml文件添加内容

<servlet>
    <servlet-name>findreporterservlet</servlet-name>
    <servlet-class>com.gpzhang.TestServlet</servlet-class> //servlet类
</servlet>

<servlet-mapping>
    <servlet-name>findreporterservlet</servlet-name>
    <url-pattern>/findreporterservlet</url-pattern>  //url访问路径相对应 参看url红色字体部分
</servlet-mapping>

 

你可能感兴趣的:(Ajax,servlet)