2017-08-02 174 views
-4

我有servlet与url模式/ servlet。我叫它如何用window.open正确调用servlet?

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

通过href在jsp中哪些不起作用。但是通过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> 
} 
+0

首先,您在上面的window.open方法中使用的url包含两个dots.Check首先。其次,请尽量提供确切的错误跟踪。 – ramasCoder

+0

@ professionallyme86我已经删除了点,但仍然无法使用。我没有收到任何错误。点击返回只是悬停在链接显示'javascript:func(2)' –

+0

你能分享代码吗? – ramasCoder

回答

0

非常有趣的问题。您在window.open()方法中使用了“/ servlet”作为URL。这将绕过应用程序根文件夹并将URL形成为http://localhost/servet,而实际URL应该与http://localhost//servlet类似。

在你的情况下解决方案的任何方式只是从URL中删除该“/”。因此使用:

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