简体   繁体   中英

Get output of java file into jsp page

I was trying to write a JSP page. But i have read many times that source code within JSP page is a bad practice. So then I tried to write a different class in the same package and call it within that JSP page.

Here's the JSP code:

<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.

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. How can I achieve this? Is there a seperate method? Do I have to make the class a servlet?

Thanks!

Try using a tag library: 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. The idea is that you want to display properties of your bean in your page. Consider: JavaBeans So Do something like this:

Java

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

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. The page should be a view of the data of components on the sever which in this case is the bean.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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