Javascript 从Servlet调用特定方法

Javascript 从Servlet调用特定方法,javascript,java,jquery,servlets,Javascript,Java,Jquery,Servlets,经过大量学习,我能够完成一个基本的中间层架构,并从javascript调用servlet中的Java方法,从javascript\jquery向该方法传递一个变量,然后从Java方法返回数据到客户端。我还有(我希望的是)最后一件事要做,那就是调用一个特定的方法。目前,我只能在javaclass中调用doGet()和doPost()方法,因此如果我想添加一个新函数,我必须添加一个全新的servlet。如果我想添加一个新函数,我将如何以类似于调用doGet()的方式调用它?我的意思是,我确信我可以使

经过大量学习,我能够完成一个基本的中间层架构,并从javascript调用servlet中的Java方法,从javascript\jquery向该方法传递一个变量,然后从Java方法返回数据到客户端。我还有(我希望的是)最后一件事要做,那就是调用一个特定的方法。目前,我只能在javaclass中调用doGet()和doPost()方法,因此如果我想添加一个新函数,我必须添加一个全新的servlet。如果我想添加一个新函数,我将如何以类似于调用doGet()的方式调用它?我的意思是,我确信我可以使doGet()方法仅仅是一个基于其中一个参数调用其他方法的解析器,但我怀疑这是最佳实践

这是我的密码:

index.jsp:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
       function init(){
            $.get("http://localhost:8080/Test/SomeServlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                $("#someselect").html(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
            });
        }

        function getSS(){
            var s = $("#someselect").val();
             $.get("http://localhost:8080/Test/SS?name=" + s, function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                $("#SS").html(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
            });
        }
    </script>
</head>
<body onload="init()">

        <select id="someselect" onchange="getSS()"></select>
        <div>
        The SS of this person is: <span id="SS"></span>
        </div>
    </body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.ws.rs.client.Entity.text;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    private static Statement stmt = null;
    private static ResultSet rs = null;
    private static Connection con = null;


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet SomeServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet SomeServlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String s22;
try {
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

      String connectionUrl = "jdbc:sqlserver://myHost:1433;databaseName=myDB;user=username;password=password";
      con = DriverManager.getConnection(connectionUrl);
        stmt = con.createStatement();
        Statement stmt = null;
        ResultSet rs = null;
        //this is where my sql statement would go, but stack overflow won't accept it for some reason, I keep getting an error and it's this line that causes it when submitting the question.
        stmt = con.createStatement();
        rs = stmt.executeQuery(SQL);
        s22 = "<select>";
        while (rs.next()) {
           s22 = s22 + "<option>"+ rs.getString("first_name") + "</option>";
        }
        s22 = s22 + "</select>";
     } catch (Exception e) {
         s22 =  "Got an exception! " + e.getMessage();
      }


 response.setContentType("text/plain");  
response.setCharacterEncoding("UTF-8"); 
response.getWriter().write(s22);

}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

试验
函数init(){
$.get(”http://localhost:8080/Test/SomeServlet,函数(responseText){//在“someservlet”的URL上执行Ajax GET请求,并使用Ajax响应文本执行以下函数。。。
$(“#someselect”).html(responseText);//查找ID为“somediv”的html DOM元素,并使用响应文本设置其文本内容。
});
}
函数getSS(){
var s=$(“#someselect”).val();
$.get(”http://localhost:8080/Test/SS?name=“+s,函数(responseText){//在“someservlet”的URL上执行Ajax GET请求,并使用Ajax响应文本执行以下函数。。。
$(“#SS”).html(responseText);//找到ID为“somediv”的html DOM元素,并使用响应文本设置其文本内容。
});
}
此人的SS为:
SomeServlet.java:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
       function init(){
            $.get("http://localhost:8080/Test/SomeServlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                $("#someselect").html(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
            });
        }

        function getSS(){
            var s = $("#someselect").val();
             $.get("http://localhost:8080/Test/SS?name=" + s, function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                $("#SS").html(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
            });
        }
    </script>
</head>
<body onload="init()">

        <select id="someselect" onchange="getSS()"></select>
        <div>
        The SS of this person is: <span id="SS"></span>
        </div>
    </body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.ws.rs.client.Entity.text;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    private static Statement stmt = null;
    private static ResultSet rs = null;
    private static Connection con = null;


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet SomeServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet SomeServlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String s22;
try {
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

      String connectionUrl = "jdbc:sqlserver://myHost:1433;databaseName=myDB;user=username;password=password";
      con = DriverManager.getConnection(connectionUrl);
        stmt = con.createStatement();
        Statement stmt = null;
        ResultSet rs = null;
        //this is where my sql statement would go, but stack overflow won't accept it for some reason, I keep getting an error and it's this line that causes it when submitting the question.
        stmt = con.createStatement();
        rs = stmt.executeQuery(SQL);
        s22 = "<select>";
        while (rs.next()) {
           s22 = s22 + "<option>"+ rs.getString("first_name") + "</option>";
        }
        s22 = s22 + "</select>";
     } catch (Exception e) {
         s22 =  "Got an exception! " + e.getMessage();
      }


 response.setContentType("text/plain");  
response.setCharacterEncoding("UTF-8"); 
response.getWriter().write(s22);

}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}
import java.io.IOException;
导入java.io.PrintWriter;
导入java.sql.Connection;
导入java.sql.DriverManager;
导入java.sql.ResultSet;
导入java.sql.Statement;
导入javax.servlet.ServletException;
导入javax.servlet.annotation.WebServlet;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入静态javax.ws.rs.client.Entity.text;
@WebServlet(“/someservlet/*”)
公共类SomeServlet扩展了HttpServlet{
私有静态语句stmt=null;
私有静态结果集rs=null;
私有静态连接con=null;
受保护的void processRequest(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
setContentType(“text/html;charset=UTF-8”);
尝试(PrintWriter out=response.getWriter()){
/*TODO在此处输出您的页面。您可以使用以下示例代码*/
out.println(“”);
out.println(“”);
out.println(“”);
out.println(“Servlet SomeServlet”);
out.println(“”);
out.println(“”);
println(“Servlet SomeServlet at”+request.getContextPath()+”;
out.println(“”);
out.println(“”);
}
}
@凌驾
受保护的void doGet(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException{
串s22;
试一试{
Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
字符串connectionUrl=“jdbc:sqlserver://myHost:1433;databaseName=myDB;user=username;password=password”;
con=DriverManager.getConnection(connectionUrl);
stmt=con.createStatement();
语句stmt=null;
结果集rs=null;
//这就是我的sql语句将要去的地方,但是堆栈溢出不会接受它,因为某些原因,我不断得到一个错误,这是这一行在提交问题时导致它的原因。
stmt=con.createStatement();
rs=stmt.executeQuery(SQL);
s22=“”;
while(rs.next()){
s22=s22+“”+rs.getString(“名字”)+“”;
}
s22=s22+“”;
}捕获(例外e){
s22=“出现异常!”+e.getMessage();
}
response.setContentType(“文本/普通”);
响应。setCharacterEncoding(“UTF-8”);
response.getWriter().write(s22);
}
@凌驾
受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)
抛出ServletException、IOException{
processRequest(请求、响应);
}
@凌驾
公共字符串getServletInfo(){
返回“简短描述”;
}// 
}

您可以向doPost方法发送方法名称和参数,并使用反射调用该方法。您可以尝试使用JSON-RPC,因为您可以将方法名称和参数发送到doPost方法,并使用反射来调用该方法。您可以尝试使用JSON-RPC,如下所示