无法使用ajax调用servlet

时间:2017-02-27 12:32:57

标签: java jquery ajax jsp servlets

我正在尝试使用Ajax调用Servlet,但$ .ajax()中的url不会将我重定向到Servlet。
你们都可以看看并告诉我为什么它没有调用servlet。

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="model.MongoDBJDBC" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<!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=ISO-8859-1">
  <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
  	<script src="http://code.jquery.com/jquery-1.10.2.js"
	type="text/javascript"></script>
  	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
	<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
	<script type="text/javascript">
	google.charts.load('current', {
		packages : [ 'corechart' ]
	});
	</script>
<title>Servlets Selection Menu</title>
</head>
<body>
	<div id="Servletssframe" style="width:200px; height:100px; margin-left:5px ;">
		<form method="get" action="ReqFilter" id="myform">
			<input type="radio" value="Servlets1" name="servlet" id="Servlets1"><label>Servlets 1</label><br>
			<input type="radio" value="Servlets2" name="servlet" id="Servlets2"><label>Servlets 2</label><br>
			<input type="radio" value="Servlets3" name="servlet" id="Servlets3"><label>Servlets 3</label><br>
			<input type="radio" value="Servlets4" name="servlet" id="Servlets4"><label>Servlets 4</label><br>
			<input type="radio" value="Servlets5" name="servlet" id="Servlets5"><label>Servlets 5</label><br>
			<input type="button" value="submit" id="button">
		</form>
	</div>
</body>
	
<div id="container" style="width: 700px; height:700px; margin: 0 auto"></div>


 <script type="text/javascript">
 

 
	 $(document).ready(function() { 		
         $('#button').click(function() {         
        	 var servlet=$('input[type=radio][name=servlet]:checked').attr('id');
        	//console.log(servlet);
        	
        	 $.ajax({
                 //url:'/ServletsUsingAjax/RequestFilter?servlet='+servlet,
               	
   				url:'/ServletsUsingAjax3/RequestFilter?servlet='+servlet,
                type:'get',
               /* success:function()
                {
                	alert(this.url);
                },
               */
        	 
              }
         );
         });
     });
	 
</script>

ReqFilter.java

package control;    
import java.io.IOException;    
import java.io.PrintWriter;    

import javax.servlet.RequestDispatcher;    
import javax.servlet.ServletException;    
import javax.servlet.annotation.WebServlet;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;       
//@WebServlet("/RequestFilter")            
public class ReqFilter extends HttpServlet {        

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException        
{    
        response.setContentType("text/html");    
        //response.setContentType("text/plain;charset=UTF-8");    
        RequestDispatcher dispatcher;
        String value=request.getParameter("servlet").trim();    

        PrintWriter out=response.getWriter();
        out.println("This"+value);
        if(value.equals("Servlets1"))
        {
            dispatcher=request.getRequestDispatcher("index.jsp");
            dispatcher.include(request,response);

            out.println("<script type='text/javascript'>");
            out.println("console.log("+value+")");
            out.println("$('#container').load('textfile.jsp')");
            //out.println("google.charts.setOnLoadCallback(drawChart);");
            out.println("</script>");
        }
        if(value.equals("Servlets2"))
        {
            dispatcher=request.getRequestDispatcher("index.jsp");
            dispatcher.include(request,response);
            out.println("<script type='text/javascript'>");
            //out.println("<div id='container2' style='width: 700px; height:700px; margin: 0 auto'></div>");
            out.println("$('#container').load('textfile2.jsp')");
            //out.println("google.charts.setOnLoadCallback(drawChart);");
            out.println("</script>");
        }
        if(value.equals("Servlets3"))     
        {      
            dispatcher=request.getRequestDispatcher("index.jsp");    
            dispatcher.include(request,response);    
            out.println("<script type='text/javascript'>");    

            out.println("Nothing to dipsplay");

            out.println("</script>");
        }



}    
}    

的web.xml

<web-app>  

<servlet>  
<servlet-name>ServletsUsingAjax</servlet-name>  
<servlet-class>control.ReqFilter</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>ServletsUsingAjax</servlet-name>  
<url-pattern>/ReqFilter</url-pattern>  
</servlet-mapping>  

</web-app>  

3 个答案:

答案 0 :(得分:1)

 <script type="text/javascript">
  $(document).ready(function() {        
         $('#button').click(function() {         
         var servlet=$('input[type=radio][name=servlet]:checked').attr('id');
             $.ajax({
                url:'RequestFilter?servlet='+servlet,
                type:'get',
               success:function(data)
                {
                    alert(data);
                }
              });
         });
    });   
</script>

您可以使用上面的代码调用servlet, 感谢。

答案 1 :(得分:0)

只需使用以下代码替换您的ajax网址。

$.ajax({
url : 'ReqFilter?servlet='+ servlet,
type : 'get',
});

servlet映射和url模式url在ajax中传递时存在问题。

答案 2 :(得分:0)

我按照上面的代码发布我的工作代码。试试这个。
index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.List"%>
<!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=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"
    type="text/javascript"></script>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
    src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', {
        packages : [ 'corechart' ]
    });
</script>
<title>Servlets Selection Menu</title>
</head>
<body>
    <div id="Servletssframe"
        style="width: 200px; height: 100px; margin-left: 5px;">
        <form method="get" action="ReqFilter" id="myform">
            <input type="radio" value="Servlets1" name="servlet" id="Servlets1"><label>Servlets
                1</label><br> <input type="radio" value="Servlets2" name="servlet"
                id="Servlets2"><label>Servlets 2</label><br> <input
                type="radio" value="Servlets3" name="servlet" id="Servlets3"><label>Servlets
                3</label><br> <input type="radio" value="Servlets4" name="servlet"
                id="Servlets4"><label>Servlets 4</label><br> <input
                type="radio" value="Servlets5" name="servlet" id="Servlets5"><label>Servlets
                5</label><br> <input type="button" value="submit" id="button">
        </form>
    </div>
</body>

<div id="container" style="width: 700px; height: 700px; margin: 0 auto"></div>


<script type="text/javascript">
    $(document)
            .ready(
                    function() {
                        $('#button')
                                .click(
                                        function() {
                                            var servlet = $(
                                                    'input[type=radio][name=servlet]:checked')
                                                    .attr('id');
                                            //console.log(servlet);

                                            $
                                                    .ajax({
                                                        //url:'/ServletsUsingAjax/RequestFilter?servlet='+servlet,

                                                        url : 'ReqFilter?servlet='+ servlet,
                                                        type : 'get',


                                                    });
                                        });
                    });
</script

>

<强> ReqFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;       
//@WebServlet("/RequestFilter")            
public class ReqFilter extends HttpServlet {        

    private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException        
{    
    System.out.println("HEREEEEEEEEEEEEEE");
        response.setContentType("text/html");    
        //response.setContentType("text/plain;charset=UTF-8");    
        RequestDispatcher dispatcher;
        String value=request.getParameter("servlet").trim();    

        PrintWriter out=response.getWriter();
        out.println("This"+value);
        if(value.equals("Servlets1"))
        {
            dispatcher=request.getRequestDispatcher("index.jsp");
            dispatcher.include(request,response);

            out.println("<script type='text/javascript'>");
            out.println("console.log("+value+")");
            out.println("$('#container').load('textfile.jsp')");
            //out.println("google.charts.setOnLoadCallback(drawChart);");
            out.println("</script>");
        }
        if(value.equals("Servlets2"))
        {
            dispatcher=request.getRequestDispatcher("index.jsp");
            dispatcher.include(request,response);
            out.println("<script type='text/javascript'>");
            //out.println("<div id='container2' style='width: 700px; height:700px; margin: 0 auto'></div>");
            out.println("$('#container').load('textfile2.jsp')");
            //out.println("google.charts.setOnLoadCallback(drawChart);");
            out.println("</script>");
        }
        if(value.equals("Servlets3"))     
        {      
            dispatcher=request.getRequestDispatcher("index.jsp");    
            dispatcher.include(request,response);    
            out.println("<script type='text/javascript'>");    

            out.println("Nothing to dipsplay");

            out.println("</script>");
        }



}    
}    

<强>的web.xml

<web-app>

    <servlet>
        <servlet-name>ServletsUsingAjax</servlet-name>
        <servlet-class>ReqFilter</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletsUsingAjax</servlet-name>
        <url-pattern>/ReqFilter</url-pattern>
    </servlet-mapping>

</web-app>