1. 程式人生 > >JSP使用AJAX與Servlet互相傳值

JSP使用AJAX與Servlet互相傳值

工程結構:
這裡寫圖片描述

WebContent資料夾存放我們的html、CSS、js、JPS等檔案。程式執行的就指向該資料夾。即程式的根目錄
src檔案存放我們的servlet javaClass等檔案。程式執行之後會自動將這些檔案編譯存放在WebContent/WEB-INF/classes資料夾中。
WebContent/WEB-INF/lib存放一些我們引用的外部包等檔案
web.xml檔案存放在WebContent/WEB-INF資料夾中。該檔案可有可無,需要時自己手動建立。

1、index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>第一個頁面</title> <script type="text/javascript" src="jquery-1.11.3/jquery.min.js"
>
</script> <script type="text/javascript" src="index.js"></script> <body> <div id="show"></div> </html>

2、index.js

$(function() {
    $.ajax({
        cache : false,
        async : false,
        type : "post",
        url : "index?action=1",
        contentType : "application/text; charset=utf-8"
, dataType : "text", success : function(data) { $("#show").append(data) }, error : function() { alert("error"); ` } }); })

3、index.java(Servlet)


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

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

/**
 * Servlet implementation class index
 */
@WebServlet("/index")
public class index extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public index() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     * 使用get方式傳遞資料時呼叫
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     * 使用post方式傳遞資料時呼叫
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
        String str = request.getParameter("action");
        if (str.equals("1")) {
            connectSql sql = new connectSql();
            try {
                String string = sql.connect();
                out.print(string);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            out.print(str);
        }
    }
}

4、connectSql.java(JDBC連線資料庫)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class connectSql {
    static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static final String URL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=CE_DQ";
    static final String USER = "sa";
    static final String PWD = "zaz3413887..*";

    public String connect() throws ClassNotFoundException, SQLException {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        String retuen = "";
        Class.forName(DRIVER);
        con = DriverManager.getConnection(URL, USER, PWD);
        String SQL = "select * from people";
        stmt = con.createStatement();
        rs = stmt.executeQuery(SQL);
        while (rs.next()) {
            retuen += rs.getString("id") + " " + rs.getString("name") + " " + rs.getString("age") + "\n";
        }
        return retuen;
    };
}

5、web.xml

配置servlet的名稱,地址和URL.我們js在向servlet傳值的地址就是使用這裡定義的地址。
welcome-file-list配置歡迎頁,一般我們預設首頁。即配置預設首頁
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>index</servlet-name>
        <servlet-class>index</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>index</servlet-name>
        <url-pattern>/index</url-pattern>
    </servlet-mapping>
</web-app>

這裡寫圖片描述