简体   繁体   English

将Java文件的输出获取到JSP页面

[英]Get output of java file into jsp page

I was trying to write a JSP page. 我试图编写一个JSP页面。 But i have read many times that source code within JSP page is a bad practice. 但是我已经读过很多遍了,JSP页面中的源代码是一种不好的做法。 So then I tried to write a different class in the same package and call it within that JSP page. 因此,我尝试在同一包中编写一个不同的类,并在该JSP页面中调用它。

Here's the JSP code: 这是JSP代码:

<jsp:useBean id="link" scope="application" class = "tms.TestJava" />
<%

TestJava t=new TestJava();
t.test();

%>

and here's the class code: 这是课程代码:

public class TestJava {

public void test() throws IOException
{
    System.out.println("sdds");
}
}

I have imported the class into JSP page. 我已经将该类导入到JSP页面中。

Now the problem is that when I use System.out.println in the class (test method), it gets printed onto the console and I want it to print it to the JSP page. 现在的问题是,当我在类(测试方法)中使用System.out.println时,它将被打印到控制台上,并且我希望它将其打印到JSP页面上。 How can I achieve this? 我该如何实现? Is there a seperate method? 有单独的方法吗? Do I have to make the class a servlet? 我必须使该类成为servlet吗?

Thanks! 谢谢!

Try using a tag library: JSTL 尝试使用标签库: JSTL

Specifically: 特别:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:out> Tag Example</title>
</head>
<body>
<c:out value="${'<tag> , &'}"/>
</body>
</html>

Or better yet, since you are using JavaBeans already, refactor so that you aren't using System.out() anymore. 或更妙的是,由于您已经在使用JavaBeans,因此请进行重构,以使您不再使用System.out() The idea is that you want to display properties of your bean in your page. 这个想法是您想在页面中显示bean的属性。 Consider: JavaBeans So Do something like this: 考虑: JavaBeans因此请执行以下操作:

Java 爪哇

public class Course{
   private String code = "Math";
   public String getCode(){
      return code;
   }
}

Jsp Jsp

<jsp:useBean id="course" class="com.javaBeans.Course" />
<jsp:getProperty name="course" property="code"/>

Chiefly, you don't want to just System.out() to a page. 首先,您不想仅将System.out()移至页面。 The page should be a view of the data of components on the sever which in this case is the bean. 该页面应该是服务器上组件数据的view ,在本例中为服务器。

I think you're going about this the wrong way, but here is a possible solution... 我认为您正在以错误的方式进行操作,但这是一个可能的解决方案...

<head>
    <%@ page language="java" import="tms.TestJava"%>
</head>

<body>
    <%=TestJava.getAString()%>
    <%=TestJava.getAString()%>
    <%=TestJava.getAString()%>
    <%=TestJava.getAString()%>
    <%=TestJava.getAString()%>
</body>


public String getAString(){
    return "<li></li>";
}

If your goal is to build dynamic JSPs, you will probably want to look into JSTL as someone above mentioned, look into defining your own tags, etc. I don't think very much new dev is using scriplet code. 如果您的目标是构建动态JSP,则您可能希望像上面提到的那样研究JSTL,研究定义自己的标记等。我认为没有太多新开发人员正在使用scriplet代码。

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

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