简体   繁体   English

servlet对jsp页面的响应

[英]servlet's response to a jsp page

Lets say a servlet text.java returns an html content to a jsp page index.jsp. 假设servlet text.java将html内容返回到jsp页面index.jsp。

IN index.jsp index.jsp

<button onclick="location.href='text'">CLICK</button>

IN text.java text.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
     out.println("<b>HELLO</b>");
    } finally { 
        out.close();
    }
} 

Now we say that servlet responds to the web browser's request, then after clicking on the button why in the url instead of the jsp page the name of the servlet is there and the control is not returned to the jsp page. 现在我们说servlet响应Web浏览器的请求,然后单击按钮后,为什么在url而不是jsp页面中有servlet的名称,并且控件没有返回到jsp页面。

Is that only possible with ajax (formelement.innerHTML= ob.responseText()) ? 只有使用ajax(formelement.innerHTML = ob.responseText())才可能吗? //where var ob = new XMLHttpRequest(); //其中var ob = new XMLHttpRequest();

you can proceed like this... 你可以这样...

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String str = "<b>heloo</b>";
    request.setAttribute("result", str);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

and in jsp just get the result by : 并在jsp中通过以下方式获得结果:

request.getAttribute("result");

A JSP is a servlet written as a template. JSP是作为模板编写的servlet。 Servlets are server-side, and typically do not call each other. Servlet是服务器端的,通常不会相互调用。 This is your web page (wether it was generated through a jsp or not) that exposes a link to a URL, not a java file . 这是您的网页(无论它是通过jsp生成的)还是公开指向URL的链接,而不是java文件的链接 When the link is clicked, your browser sends a request to your server for the URL of the link. 单击链接后,浏览器将向您的服务器发送请求以获取链接的URL。 So on your server this URL (which is up to you to define) has to be mapped to a Servlet class that will handle the request and produce a response. 因此,必须在您的服务器上将此URL(由您自己定义)映射到一个Servlet类,该Servlet类将处理请求并产生响应。 This URL-to-servlet mapping being configured in the web.xml file of your WAR. URL到servlet的映射在WAR的web.xml文件中配置。

you should see how to map servlet in web.xml, search for a basic servlet tutorial. 您应该了解如何在web.xml中映射servlet,并搜索基本的servlet教程。

you cannot give a link like text.java and expect it will fire the text.java servlet. 您不能提供像text.java这样的链接,并且期望它会触发text.java servlet。 you need to map a url to servlet class 您需要将网址映射到servlet类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM