Hello, this is Take.
This time, we will finish the Java grammar and create code that works only on the terminal. This article is for Java beginners (including myself) who have become able to develop simple "Web applications" that use servers and browsers.
What is often used when you want to pass an instance written in a Servlet to JSP is called "request scope".
As many of you may have seen, these are "request.setAttribute ()" and "request.getAttribute ()".
Regarding this "request scope", I used to recognize it as something similar to "variable scope". However, it's actually similar.
Isn't it easier to understand the request scope if you change the image a little? I decided to write this article.
First of all, the scope of variables is, for example.
public class Example { public static void main(String[] args) {
//from here int i = 1;
// The range up to this point is called the scope of the variable "i"
} }
As mentioned above, it was "a valid value in the block from here to here in a certain code".
Similarly, for "request scope"
public class ExampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ~~~~ try {
//from here ~~~~ ~~~~ ~~~~ request.setAttribute("Hoge", hoge);
~~~~
~~~~
~~~~
// Is this the scope of the request scope? ??
} } } }
With the above recognition (totally different), why can I get it from another source code called JSP even though it is within the above scope? Some people may think that.
So, I will tell you the image of the request scope that I thought of.
Request scope is a new "box" separate from JSPs and Servlets.
You can set and get the new "box" using the getAttribute () and setAttribute () methods.
From "Servlet" into request scope
Stored with the code request.setAttribute ("Hoge", hoge);
↓ In the request scope
I was able to store a hoge instance with the attribute name "Hoge"
↓ From "JSP" request.getAttribute ("Hoge"); Get with code
I think the text is complicated and difficult to understand,
"Using the setAttribute () method from the Servlet,
Store the instance in a new "box" called Request Scope,
Use the getAttribute () method from JSP to retrieve an instance from that "box" "
Isn't it okay with the image?
This time is over.
Recommended Posts