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>

这里写图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值