java PrintWriter 输出到 body 标签内的 jsp 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16361628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:45:17  来源:igfitidea点击:

PrintWriter output to jsp page inside body tag

javajspweb-applicationshttpresponse

提问by Vlad Otrocol

This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.

这是打印到我的 jsp 页面的代码。但是我在页面中有其他代码。当我调用这个函数时,我希望它在调用它之后立即打印消息。我无法确定,因为我使用的是 xhtml 协商,但我怀疑它打印在 /html 标签之后。

This is my function

这是我的功能

public Print(HttpServletRequest request,HttpServletResponse response){
        try{
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.print("<p>haha</p>");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
};

This is where I call it

这就是我所说的

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Register</title>
</head>

<body>
<%@ page import="com.otrocol.app.*" %>
<%
    Print(request, response);
%>
</body>
</html>

This is what I think the result is:

这就是我认为的结果:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Register</title>
</head>

<body>
</body>
</html>
"haha"

This is what I want the response to be:

这就是我想要的响应:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Register</title>
    </head>  
    <body>
     "haha"
    </body>
    </html>

This is the error I get:

这是我得到的错误:

enter image description here

在此处输入图片说明

回答by Joop Eggen

The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function. Otherwise you are taking a second writer, and with buffering everything goes haywire.

JSP 使用它自己的 PrintWriter,即 JspWriter out。所以把它传递给(静态)函数。否则,您将使用第二个编写器,并且缓冲一切都会变得混乱。

Also as output already did happen do not set the content type in the function.

此外,由于输出已经发生,请不要在函数中设置内容类型。

At the top of the JSP is a nice location, also for the imports.

JSP 的顶部是一个不错的位置,也用于导入。

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

When having onewriter the function would print at the correct spot in the body.

当有一个writer 时,该函数会在 body 的正确位置打印。

Nice intuition about the cause. BTW begin a function name with a small letter.

关于原因的好直觉。顺便说一句,函数名以小写字母开头。

回答by kryger

It's not a directanswer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSPfrom Java code.

这不是对您问题的直接回答,但我相信即使您开始工作,您所做的只会给您带来痛苦。你没有使用正确的工具来完成这项工作;创建自定义 JSP 标记是JSP从 Java 代码写入的更好选择。



Code example:

代码示例:

register.jsp

注册.jsp

<%@ taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Register</title>
</head>
<body>
    <p>
      <c:out value="${custom:printHaha()}" />
    </p>
</body>
</html>

custom-tags.tld

自定义标签.tld

<?xml version="1.0" encoding="UTF-8"?>

<taglib version="2.0" 
        xmlns="http://java.sun.com/xml/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
    <tlibversion>1.0</tlibversion>
    <jspversion>2.0</jspversion>
    <shortname>custom-taglib</shortname>

    <uri>CustomTags</uri>

    <function>
        <name>printHaha</name>
        <function-class>com.yourpackage.Tags</function-class>
        <function-signature>
           java.lang.String print()
        </function-signature>
    </function>

    (...)

Tags.class

标签.class

public class Tags {
    public static String print() {
        return "haha";
    }
}


More info on Tags: official docs

有关标签的更多信息:官方文档

回答by CA Martin

There are two pages. The first one is the Main Page. This one performs some pseudo calcs.

有两页。第一个是主页。这个执行一些伪计算。

Based on those calcs, either Success.jsp or Failure.jsp is returned.

根据这些计算,返回 Success.jsp 或 Failure.jsp。

This code will do what you wanted to have achieved.....

此代码将完成您想要实现的目标.....

Even though as the others pointed out, there are more advanced techniques as of late, still in order to dance, first you have to know the moves....

尽管正如其他人指出的那样,最近有更先进的技术,但为了跳舞,首先你必须知道动作......

a busy cat

一只忙碌的猫

Primarily look at this cObj.Print(request, response); in the 2nd jsp page.

主要看这个 cObj.Print(request, response); 在第二个jsp页面中。

JSP Page

JSP页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<%@ page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>JSP and JavaBean</title>

        <%-- create an instance of Customer class --%>
        <jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">

        <%-- Set the value of attribute such as CustID --%>
        <jsp:setProperty name="cObj" property="*" />
        </jsp:useBean>

    </head>
<body>

<%
            int x=cObj.setStoreCust();

            if(x>=1)
            {
        %>
                <jsp:forward page="Success.jsp" />
        <%

            }
            else
            {
        %>
                <jsp:forward page="Failure.jsp" />
        <%

            }

        %>

</body>
</html>

JSP Page

JSP页面

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

<%@ page import="java.util.*" %>
<%@ page import="rustler.Beans.Beany" %>
<%@ page import="javax.servlet.http.HttpServletRequest" %>
<%@ page import="javax.servlet.http.HttpServletResponse" %>



<!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">
<title>Failure!</title>

<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">

<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />


</jsp:useBean>

</head>
<body>


<%cObj.Print(request, response);%>
</body>
</html>

Java Bean

Java Bean

package rustler.Beans;

import java.io.*;
import java.util.*;
import java.sql.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Beany implements Serializable
{

    public Beany()
    {

    }
        /**
     * 
     */
    private static final long serialVersionUID = 1L;
        private String custID;
        private String custName;
        private int qty;
        private float price;
        private float total;
        private int storeCust;

        public String getCustID() {
            return custID;
        }

        public void setJunk(String sStr)
        {
            //System.out.println("What a punk!");
            custName = sStr;//"What a punk!";           
        }       

        public void Print(HttpServletRequest request,HttpServletResponse response)
        {
            try{
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.print("<p>haha</p>");
            }catch(IOException e){
                e.printStackTrace();
            }
        }


        public String prntJunk()
        {
            //System.out.println("What a punk!");
            return custName;//"What a punk!";           
        }

        public void setCustID(String custID) {
            this.custID = custID;
        }

        public String getCustName() {
            return custName;
        }

        public void setCustName(String custName) {
            this.custName = custName;
        }

        public int getQty() {
            return qty;
        }

        public void setQty(int qty) {
            this.qty = qty;
        }

        public float getPrice() {
            return price;
        }

        public void setPrice(float price) {
            this.price = price;
        }

        public float getTotal() {
            return total;
        }

        public void setTotal(float total) {
            this.total = total;
        }

        public int setStoreCust() 
        {
            try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
            PreparedStatement pstmt=null;
            String query=null;
            query="insert into customer values(?,?,?,?,?)";
            pstmt=con.prepareStatement(query);
            pstmt.setString(1,custID);
            pstmt.setString(2,custName);
            pstmt.setInt(3,qty);
            pstmt.setFloat(4,price);
            pstmt.setFloat(5,total);
            int i=pstmt.executeUpdate();

            this.storeCust=i;
            }
            catch(Exception e)
            {

            }
            return storeCust;
        }
}

回答by DarthCoder

I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp

我不检查你的代码......你不能在一个jsp页面中使用get writer再次做一个out.print......因为这个请求的响应已经通过渲染jsp提交了

now to print something on asp you can do this any number of ways

现在要在 asp 上打印一些东西,您可以通过多种方式执行此操作

  1. print by expression tag
  1. 按表达式标签打印
  1. use out (which is an object the server creates)

    out.print("Blah...");

  1. use out(这是服务器创建的对象)

    out.print("废话...");

and more

和更多

to understand what happens to a jsp look into /work/catalina/blah.../

要了解 jsp 会发生什么,请查看 /work/catalina/blah .../