开发者

How to get JSP Application Context inside a java class

I'm not very familiar with JSP, so, let's make this question an example:

suppose I have a JSP file (index.jsp) which contain those statement:

<% 
MyObject mO = new MyObject();
mO.sayHelloWorld();
%>

and in the MyObject.java:

public class MyObject(){
    public void sayHelloWorld(){
        //something like getJSPApplicationContext.getOut.println("<p>Hello World</p>");
    }
}

is there a simple way to reach this goal (without passing the JSPApplic开发者_StackOverflowationContext to my class?)

Maybe I'm doing something really wrong, anyway, thanks for yout help :)


Let me use this opportunity to introduce you to the V (View) in MVC (Model View Controller).

You should generally put data into the view by putting a view bean into the session on your controller. You can think of your class MyObject as a view bean as it contains information you want to display in the view. The controller in this case is your servlet (you do have a servlet, right?) and would contain the following in its doGet or doPost method;

MyObject myObject = new MyObject("Hello world");
request.setAttribute("myObject", myObject);

The next step is to have your JSP display the data from the view bean. You are strongly encouraged to use JSTL for this, rather than by putting code snippets in. The JSTL tag <c:out> can be used for displaying data in a JSP. Your JSP might contain the following;

<p>
<c:out value="${myObject.message}"/>
</p>

This will call the getMessage() method on the session object 'myObject' and output it on the page.

Just for completeness, your MyObject view bean might look like this;

public class MyObject
{
  String message;

  public MyObject(String message)
  {
    this.message = message;
  }

  public String getMessage()
  {
    return message;
  }
}


This isn't how it is used.

For the purpose you have demonstrated.

You should include a Servlet or jsp or static HTML just to print Hello World like

<jsp:include page="/staticfile/helloworld.html" />

in helloworld.html

just

hello world

or include servlet

<jsp:include page="/helloworldServlet" />

and in HelloWorld Servlet doGet()

out.println("hello world");

Also See

  • how-to-avoid-java-code-in-jsp-files
  • about jsp


Without passing the context to the class method, and without storing it in a ThreadLocal variable (which I think would be a bad idea), I don't see how you could do that.

If your class needs access to the JSP context it probably means that the class should be a JSP fragment or a custom JSP tag (<custom:sayHello/>).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜