1. 程式人生 > >基本的JSP中呼叫Ajax與Servlet進行資料互動

基本的JSP中呼叫Ajax與Servlet進行資料互動

首先建立jsp頁面中  然後在頁面中寫入js程式碼!
<span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=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 'index.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" src="<%=path%>/js/jquery-2.1.1.min.js" ></script>
    <script type="text/javascript">
     function  sub(){
       $.ajax({
       type:"GET",
       url:"/Ajaxex/testServlet",
       data:{username:$("#name").val()},
       statusCode: {404: function() {
            alert('page not found'); }
         },    
       success:function(data,textStatus){
       $("#sp").html(data);
       }
       });
     }
    </script>
  </head>
  <body>
    This is my JSP page. <br>
       <input type="text" name="username" id="name">
       <br>
       <input type="submit" id="btn" onclick="sub()">
    <br>
    result : <span id="sp"></span>
  </body>
</html>

寫一個Servlet類 

package com.hal.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;
import javax.xml.ws.Dispatch;

public class testServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Constructor of the object.
     */
    public testServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text");
        String   username = request.getParameter("username");
        System.out.println(username);
        PrintWriter out = response.getWriter();
        out.write(username);
        request.getRequestDispatcher("index.jsp").forward(request, response);
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text");
        PrintWriter out = response.getWriter();
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

配置web.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Ajaxex</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>AjaxexServlet</servlet-name>
    <servlet-class>com.hal.servlet.AjaxexServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>testServlet</servlet-name>
    <servlet-class>com.hal.servlet.testServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>AjaxexServlet</servlet-name>
    <url-pattern>/AjaxexServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>testServlet</servlet-name>
    <url-pattern>/testServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
</span>

相關推薦

基本JSP呼叫AjaxServlet進行資料互動

首先建立jsp頁面中  然後在頁面中寫入js程式碼!<span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8" conte

java後臺頁面進行資料互動時產生亂碼

     亂碼問題相信每一個開發人員都遇到過,而且解決的方法也不盡相同,這裡我只對我最近遇到的亂碼問題的解決方法進行一下描述: 1.問題描述   最近在海南做一個專案,當時出現了在java後臺中文資料是正常的,但在頁面展示時卻是亂碼。我在頁面中也設定了資料型別“utf-8”

struts2 使用jsonextjs進行資料互動

在預設時,<result>標籤的type屬性值是“dispatcher”(實際上就是轉發,forward)。開發人員可以根據自己的需要指定不同的型別,如redirect、stream等。如下面程式碼所示: <result name="save" ty

JSP使用AJAXServlet互相傳值

工程結構: WebContent資料夾存放我們的html、CSS、js、JPS等檔案。程式執行的就指向該資料夾。即程式的根目錄 src檔案存放我們的servlet javaClass等檔案。程式執

jsp呼叫servlet路徑問題

      今天除錯servlet,從最簡單的doget方法做起,用一個jsp表單呼叫servlet,在action中用絕對地址來訪問servlet,最初是用servlet儲存在工程中的地址,除錯後頁面出現404,提示找不到相應的檔案,後來想到是否沒有加入包的地址,加入包後仍然提示不存在,回想到昨天在web.

ajaxServlet

jsp round public 用戶名 gets json格式 list words tco 1.後臺返回text類型的數據 <%@ page language="java" import="java.util.*" pageEncoding="utf-8

web---JSP動態include靜態include的區別?

1. 動態include <jsp:include page="目標jsp"> 它的原理是使用了 request.getRequestDispatcher(目標jsp).include(request,response) 來實現頁面包含,其本質是將 源jsp 和 目標

JSPEL表示式JSTL標籤庫

EL表示式格式:${} u s e

JSPout.println()response.getWriter().println()輸出的區別

首先說明兩者的主要區別(加*為重點) *1.兩者的類不同,out的類是JspWriter,response.getWriter()的類是PrintWriter。 *2.out是JSP的內建物件,直接就可以呼叫裡面的方法,而PrintWriter呼叫之前需要response.getWrit

前臺 jsp 後臺 servlet資料互動問題

前沿:現在通常前後臺互動的做法是 前端在jsp中 通過js 生成 div input 等 標籤, 包括 裡面的屬性 class id value 等 , 然後 通過 Ajax 進入 servlet中 進行資料 查詢 或者是走mysql 或者是走索引查詢, 然後 通過json

ajaxservlet--驗證使用者名稱是否存在

            驗證使用者名稱是否存在--使用jQuery 一、資料庫mysql               資料庫中已經存在使用者名稱。 二、html頁面      <body> <h1>使用者登入</h1>

jsp動態include靜態include的區別-面試題

     JSP中動態INCLUDE與靜態INCLUDE的區別 動態INCLUDE用jsp:include動作實現 <jsp:include page="included.jsp" flush="true">它總是會檢查所含檔案中的變化,適合用於包含動態頁面,並

jsp使用jstlEL標籤建立九九乘法表

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://

AJAX後臺進行互動

傳統的form表單提交會導致頁面重新整理,在我們現在這種情況下,不希望頁面被重新整理,這種時候我們都是使用Ajax的方式進行請求的:我們在這裡使用AJAX來進行檔案的批量上傳,以下是檔案上傳程式碼function upload() { $('#fileinput').ajaxSubmit({ url

JSP呼叫Java Class的方法

在JSP中呼叫Java Class分為以下幾種情況。 一、內部類 內部類實際上包含在JSPServlet類中,可以直接呼叫。但要注意的是,如果要通過內部類的方法向頁面中輸出資訊,則應為該方法宣告一個javax.servlet.jsp.JspWriter型別的引數,而且還要在

JSP運用 Ajax

首先編寫JS部分程式碼JavaScript方式..已經忘記了。。jQuery方式其實有JQuery方式完全沒人用javaScript方式演示程式碼:點選一個 按鈕,傳遞過去一個 age=25 ,再返回回來兩個。JS部分<%@ page language="java" i

jsp呼叫java靜態常量

1. 在普通的jsp程式碼中嵌入java靜態常量 1.1 在頁面開頭引入該靜態常量所在的類: <%@page import="com.XXX.XXXX"%> 1.2 在HTML片段中使用該靜態常量:  <option value="<%=Code.

Spring框架context-paramservletinit-param的contextConfigLocation的區別

積累,小白也可成為大神 最近在使用spring這一個框架做定時任務的時候,發現一個問題。當我們不在瀏覽器中呼叫一下我們的介面,是不會自動執行定時檔案的,這個原因是什麼呢?剛開始的時候,使我費解了很長事件,不知道問題出現再哪裡。但是當冷靜下來思考一下的時

運用PycharmAnaconda進行資料分析

先挖個坑= =具體配置以後再補充啊,先說說配置裡的坑 到底是用conda維護包還是用pip維護包 我之前一直在用conda維護包,感覺甚是好用,但是conda和pycharm的相容性並不很好,比如: 1、用conda安裝了一個python3.7環境,給pycharm用是沒問題的,但

SpringBoot入門07-Thymeleaf顯示ajax請求到的資料

Thymeleaf中顯示ajax請求所需依賴 <!--所需依賴--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boo