如何使用window.open正确调用servlet?

时间:2017-08-02 19:00:17

标签: javascript java jsp servlets

我有url pattern / servlet的servlet。我是通过

来调用它的
function func(id){window.open ("../servlet?fileId="+id, "hiddenFrame");}

通过jsp中的href,它不起作用。但是通过URL / servlet访问它?fileId = 2有效。我认为这是一个servlet映射问题。请帮助。

更新:我已添加以下代码

index.jsp只有声明:

<%request.getRequestDispatcher("newjsp.jsp").forward(request,response);%>

newjsp.jsp有代码:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script language="JavaScript">
function func (id)
{
    window.open ("/servlet?fileId="+id, "hiddenFrame");
    }
    </script>
</head>
<body>
    <h1>Hello World!</h1>
   <% 
       out.println("<a href='javascript:func(2)'>Link</a>");
   %>
</body>
<iframe src="about:blank" name="hiddenFrame" width=0 height=0 frameborder=0>
</iframe>
</html>

servlet.java有代码:

package newpackage;
import java.io.IOException;
import java.io.PrintWriter;
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(name = "servlet", urlPatterns = {"/servlet"})
public class servlet extends HttpServlet {

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 servlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet servlet at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

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

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

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

1 个答案:

答案 0 :(得分:0)

相当有趣的问题。您使用了&#34; / servlet&#34;作为window.open()方法中的URL。这会绕过应用程序根文件夹并将URL格式化为http://localhost/servet,而实际URL应该类似于http://localhost/ / servlet。

在您的情况下,解决方案的任何方式都只是删除&#34; /&#34;来自网址。因此使用:

window.open ("servlet?fileId="+id, "hiddenFrame")