ArticleDirectory
- 2.1 Basic Knowledge
- 2.2 create
- 2.3 use JavaBeans in JSP
- 2.4 Alibaba Cloud and Alibaba Cloud
- 3.1 create render Servlet
- 3.2 Create JSP
- 3.3 Alibaba Cloud and Alibaba Cloud
- 4.1 create
- 4.2 create render Servlet
- 4.3 create JSP
- 4.4 Alibaba Cloud and Alibaba Cloud
Http://sun.cis.scu.edu.tw /~ Nms9115/articles/Java/webapptutor/jspservletbean/jspservletbean.htm JSP, Servlet and JavaBean combination
Author: Cai Yulin
Date: Jan-22-2003
Update: Feb-4-2003
1.0 Introduction
In the previous discussion, the last example is the JSP program that judges the quality. This program embeds many Java codes in JSP, we have also said that this is a bad design method. This time we will look at how to extract these Java code from JSP, similar to the ans, and shows how to call these JavaBeans in JSP. In addition, the servlet call JSP method will also be introduced. Previously, the workflow routine, workflow, and information are all stored in JSP, this design method refers to the page-centric architecture, or the model-1 architecture (rack 1 ), the example created now grants control rights to servlet, Servlet as the control center, control program processes, and dispatch html/JSP web pages, this is a servlet-centric architecture, also known as model-2 architecture (architecture 2). In fact, it is MVC (Model-View-Controller) the infrastructure of the architecture.
Partition 1. Page-centric Architecture |
Protocol 2. servlet-centric Architecture |
This course highlights:
- Learn how to design JavaBeans.
- Learn how to use JavaBeans in JSP ).
- Learn how servlet distributes JSP web pages.
2.0 example: JSPs call javabeans2.1 basic knowledge
The JavaBeans mentioned here are only Java differences. They are two different things from EJB (Enterprise JavaBeans). Do not confuse them. So what is the difference between Servlet and JavaBeans?
JavaBeans are just common
The Java class of servlet is not built from javax. servlet. httpservlet, therefore, has the basic functions of receiving HTTP requests and sending HTTP Response and other website applications, while JavaBeans are just a simple distinction, and can inherit from any difference, however, HTTP messages cannot be processed. The role of HTTP messages in Web applications is usually used as a data object (shared information is used between JSP and Servlet) or when a tool is used as a numeric object, it usually represents a kind of data. Therefore, it is regarded as a value bean. When a tool is used as a type, it is always a utility bean.
What kind of data can be converted to JavaBeans?
As long as you follow the Naming and Design examples mentioned in the JavaBeans rules, and you use it as a bean, then it can be regarded as a bean. [1]
Classes are usually named in the form of "dynamic words + bean", such as userinfobean and checkstockbean. This is an example. Although there is no such naming rule, it is a good thing: clearly, it can be seen at a glance that this is a bean from other programming languages.
How does JSP use JavaBeans?
To enable JSP to use your bean, your bean must provide a set of features so that jsp can access the flexibility of this bean through special standards. In fact, getter and setter methods are a group of getter and setter methods. The two methods are access methods ), access other private members through this set of access methods. Of course, this set of access methods must be declared public. For example, if a bean is similar to employeebean, it must provide annual attention for external (JSP) access. The difference is as follows:
Public class employeebean {private int age; Public int getage () {return age;} public void setage (INT age) {self. Age = age ;}}
When used in JSP, this method is as follows:
<JSP: usebean id = "EMP" class = "com. huanlin. employeebean "Scope =" request "/> <JSP: setproperty name =" EMP "property =" Age "value =" 25 "/> the annual worker quota is: <JSP: getproperty name = "EMP" property = "Age"/>
Where
- <JSP: usebean> the identifier indicates that a bean object is to be used. The ID indicates the name of the bean object, and the class indicates the type of bean to be used, scope indicates the lifecycle of an object.
- <JSP: setproperty> the tag used to set the bean's compile value. Property specifies the parameter to be set, and value indicates the number. Note that, the data imported into an HTML table is a string, but our age-sensitive data is an integer, the Web iner will take care of this part.
- <JSP: getproperty> the tag property is used to obtain the bean's signature value.
Note the following two points:
- The size of the compaction. In JSP, the attention name is the "Age" of the complete small response, but the names of getter and setter methods are getage () and setage (), the response rules of this naming rule are fixed. According to this rule, the Web iner can locate the correct access method.
- For those who are not familiar with OOP, they may assume that the "Age" features accessed in JSP are, that is, the declaration in the definition of a private member (AGE). In fact, the two are only literally the same. In reality, the actual operation can be irrelevant, because JSP is completely accessible through the getter and setter methods, external users cannot access other private members.
This is where the basic knowledge center is located. Next, it is the actual work. If you have not completed this operation, please refer to the relevant documents on your own.
2.2 create
Let's take the last example of the last tutorial file, that is, the JSP program for determining the quality to modify, among them, the isprimenumber function can be established explicitly (for reuse) and put in a class. I name this class as checkprimebean. The program sequence is shown in table 1.
Table 1. primevalidator. Java
// Producer name: checkprimebean. java // zookeeper: javac-D .. \ Classes checkprimebean. java // =================================================== =========== package COM. huanlin. util; public class checkprimebean {private int number; Public String getnumber () {return integer. tostring (number); // returns an integer to a string} public void setnumber (string s) {try {number = integer. parseint (s); // returns the string to an integer} catch (numberformatexception e) {number =-1 ;}} public Boolean isvalidnumber () {// check whether the number entered by the keyword is legal if (number <2) | (number> 10000) return false; return true;} public Boolean isprimenumber () {// determine whether the condition is a quality number for (INT I = 2; I <= Number/2; I ++) {If (Number % 2 = 0) return false;} return true ;}} |
Remark:
- The named package is used here. The package name is com. huanlin. util indicates that you are coming to Alibaba Cloud. there must also be the same link structure for the class program case, that is, the written statement and the path name will be "com \ huanlin \ util \ checkprimebean. class ". In this case, the browser will write your package name to help you automatically build the target audience. (
- When arranging the structure of the proposed project, I split the original and original categories into different categories for storage, the structure of the proposed project is as follows:
Sources \ checkprimebean. Java classes \ com \ huanlin \ util \ checkprimebean. Class |
In this example, there will be two categories: Sources and classes, not the original and original cases. For this reason, you must specify the output case category during the preparation. For this part, please refer to the 2nd rows of table 1 for solution.
- The usage of this type is to first set the flexibility of the number, and then call isvalidnumber () to check whether the entered number is a valid integer, isprimenumber () determines whether the parameter is a quality data.
About package You may also find that, even if you do not configure the package, the program can pass through the response, but since this bean is used in JSP, if you do not name the package, Web iner cannot find this bean when using this bean in JSP. Go to the related documents to find the parameter package description. |
2.3 use JavaBeans in JSP
After some Java program tokens in JSP are extracted into checkprimebean classes, the program handler is refreshed. The modified JSP handler name is called calcprime2.jsp, exam List 2.
Table 2. calcprime2.jsp
<% -- Check whether a number is a quality JSP program -- %> <% @ page Language = "Java" contenttype = "text/html; charset = big5 "%> <% request. setcharacterencoding ("big5"); string num = request. getparameter ("Number"); // get the HTTP Request Response Number %> <HTML> <body> <JSP: usebean id = "checker" class = "com. huanlin. util. checkprimebean "Scope =" request "/> <JSP: setproperty name =" checker "property =" Number "value =" <% = num %> "/> <% IF (! Checker. isvalidnumber () {%> <% response. setheader ("refresh", "5; url1_prime2.htm"); %> Please refer to 2 ~ The integer between 10000 and. <P> after five seconds, the system will automatically return to prime2.htm. <% Return ;}%> <% -- indicates that the subsequent commands are not handled -- %> <% IF (checker. isprimenumber ()) {%> <% = num %> Yes Quality <%} else {%> <% = num %> Not Quality <% }%> </body> |
The bean Method Used in JSP has been mentioned before. Only a bit worth mentioning is <JSP: setproperty> value adequacy (attribute) of this line. Please note that it uses <% = .. %> mark to merge a variable value into value adequacy. In fact, it can also be as follows:
<JSP: setproperty name = "checker" property = "Number" Param = "Number"/>
That is to say, if you do not understand the specified value, use Param instead, allow the Web container to automatically add the "Number" HTML table to the table when processing JSP commands. Since our HTML table named "Number" and bean named "Number", JSP allows us to omit "Param, like this:
<JSP: setproperty name = "checker" property = "Number"/>
In this way, it is even more difficult. If you think this is not clear, or test to some programming programs that do not know this method, it is better to set up Param program.
2.4 Alibaba Cloud and Alibaba Cloud
- Upload prime2.htm and calcprime. jsp under the sources category to the webapps \ MyApp \ category of Tomcat.
- Upload the classes to Tomcat's webapps \ MyApp \ WEB-INF \ contents.
Enter "http: // 127.0.0.1: 8080/MyApp/prime2.htm" in the website of the scanner ".
3.0 example: servlet call JSP
Servlet needs to call (say exactly: Dispatch JSP hosts) JSP, which is much simpler than Using JavaBeans in JSP, it's only about the online delivery technique, which is useful when designing architecture 2.
3.1 create render Servlet
Servlet program detail is listed in table 3.
Table 3. helloworldservlet. jsp
Import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; public class helloworldservlet extends httpservlet {public void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = big5"); Request. setcharacterencoding ("big5"); string themessage = "Hello, world! "; String TargetUrl ="/hellofromservlet. JSP "; request. setattribute ("message", themessage); requestdispatcher RD; RD = getservletcontext (). getrequestdispatcher (TargetUrl); Rd. forward (request, response );}} |
The program has several points worth special attention:
- The previous servlet processing routines use doget to process HTTP requests on the processing end. In this case, the service is used.
- Request. setattribute ().
- Requestdisatcher.
- Getservletcontext ().
- The getrequestdispatcher () method of servletcontext.
- The forward () method of requestdispatcher.
Please refer to the instructions from your local or online resources to understand how the program works.
3.2 Create JSP
Table 3. hellofromservlet. jsp
<% @ Page Language = "Java" contenttype = "text/html; charset = big5" %> <% string MSG = (string) request. getattribute ("message"); %> <HTML> <body> response message received from servlet: <% = MSG %> </body> |
Request is used in previous servlet programs. setattribute (), in which request is used. getattribute (). It can be seen from this that the servlet and JSP are stored and distributed to the peer through the request object.
The program running process is as follows:
- Send an HTTP request with the sender. The requested webpage is "http: // 127.0.0.1: 8080/MyApp/helloworldservlet ".
- After the helloworldservlet receives the request, it passes through request. setattribute () to send the response string "Hello, world! "Exist in the request object.
- Helloworldservlet establishes a requestdispatcher object through servletcontext and specifies the website to be assigned.
- Helloworldservlet calls the forward () method of requestdispatcher and sends this HTTP request token to another website, that is, hellofromservlet. jsp.
- JSP first obtains the response value in the request object through request. getattribute (). The response value is specified by Servlet in step 2. Finally, the signature value is displayed with the HTML Tag.
I turn the entire process into a UML sequential process (sequence 3). You can use the above text description to understand the program running process.
Protocol 3. The servlet assigns the JSP network's process (sequence digoal)
3.3 Alibaba Cloud and Alibaba Cloud
-
- Create a project structure under the webapps category of Tomcat: MyApp \ WEB-INF \ Classes \. Please note that the size of the Shard is different.
-
- Upload hellofromservlet. jsp to MyApp.
- just pull helloworldservlet. Java, and keep the helloworldservlet. Class generated after login into MyApp \ WEB-INF \ Classes \ contents.
- the contents of the MyApp \ WEB-INF \ WEB. xml example are as follows:
Table 4. Web. xml
helloworldservlet
helloworldservlet
helloworldservlet
/helloworldservlet
|
- Open the browser and paste the URL "http: // 127.0.0.1: 8080/MyApp/helloworldservlet" in the website column ".
4.0 examples: servlet, JavaBeans, and JSP combination
In fact, this example is similar to the example of 3.0. It is all sent to JSP by the servlet internal statistics, and then the JSP obtains and displays the statistics, only the number of samples in 3.0 is a string, and the data to be displayed here is shared information based on the number of JavaBeans objects.
The project structure is shown in Step 4:
Article 4. Object Structure
The Java class cases after the successful execution are all written to the classes category, and the helloservlet2.java requires the test userinfobean. java. Therefore, you must use the-class sequence number when creating a batch. Otherwise, the class sequence cannot be found. For convenience, we use a batch of sequence make. bat helps us identify all Java class differences.
4.1 create
We plan to use a userinfobean class to store a user's related information and compile this object between Servlet and JSP, to allow communication and information sharing. For the convenience of display, this type does not only provide a sensitivity: username, program parameters are listed in table 5.
Table 5. userinfobean. Java
// Producer name: userinfobean. java // zookeeper: javac-D .. \ Classes userinfobean. java package COM. huanlin; public class userinfobean {private string username; Public void setusername (string username) {This. username = username;} Public String GetUserName () {return this. username ;}} |
4.2 create render Servlet
Table 6. helloservlet2.jsp
// Example: helloservlet2.java // example: Make. bat import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; import COM. huanlin. userinfobean; public class helloservlet2 extends httpservlet {public void Service (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// The following two lines allow the Chinese text to explicitly display response. setcontenttype ("text/html; charset = big5"); Request. setcharacterencoding ("big5"); // create a userinfo object and specify the attribute and parameter of a session. userinfobean userinfo = new userinfobean (); userinfo. setusername ("Ling HU Jing"); httpsession session = request. getsession (); Session. setattribute ("userinfo", userinfo); // go to the specified website requestdispatcher RD; RD = getservletcontext (). getrequestdispatcher ("/hellofromservlet2.jsp"); Rd. forward (request, response );}} |
Session. setattribute () stores the token of the userinfobean object in the session.
4.3 create JSP
<% @ Page contenttype = "text/html; charset = big5" %> <JSP: usebean id = "userinfo" class = "com. huanlin. userinfobean "Scope =" session "/> <HTML> <body> <p> userinfobean imported from servlet connector. username: <B> <JSP: getproperty name = "userinfo" property = "username"/> </B> </body> |
Note that when the servlet volume is stored, the session is called. the setattribute () method, that is, storing the data in the session. Therefore, the scope of the <JSP: usebean> label in the JSP must be specified as "session ", otherwise, the data cannot be retrieved.
After a user logs in, the related information such as the login token must exist until the user logs out or closes the reader, therefore, we store the userinfobean object in the session. Generally, in order to save the memory resources, do not store the data in the session when necessary. If bean metadata is sent to JSP, it can be stored in the request.
4.4 Alibaba Cloud and Alibaba Cloud
- make. Bat produces all. Class classes.
- The. Class program case generated by make. bat, that is, the entire classes is directed to MyApp \ WEN-INF \ Classes \ category.
- route hellofromservlet2.jsp to MyApp.
- Add the following content to MyApp \ WEB-INF \ WEB. xml example:
Table 4. Web. xml
helloservlet2
helloservlet2
helloservlet2
/helloservlet2
|
- enable the Web tracking tool and add the URL "http: // 127.0.0.1: 8080/MyApp/helloservlet2" to the website ".
5.0 student quota
- The solution involves the architecture of the zookeeper page-centric and servlet-centric, which is missing from the two organizations.
- What is JavaBeans?
- What criteria does JSP provide for us to access the adequacy of JavaBeans?
- How does JavaBeans provide modularity for JSP access?
- Why should I use a named package? What are the advantages?
- In table 3, the helloworldservlet class does not change the override method to the Service () method. What is the difference between this and the previous method to modify the doget () method?
- Description: The purpose of httpservletrequest. setattribute.
- Describe the purpose of requestdispatcher. Forward.
- <JSP: usebean> what is the role of the standard definition scope? In addition to setting the value as "session", what values can be set? What are their differences?
Exam question
[1] |
Web developement with JavaServer Pages. Duane K. Fields, mark a Kolb, Shawn Bayern. Manning, 2002. |
[2] |
The second version of UML, written by Martin Fowler, Lu guangzheng, Xue Wenwen Yu, Ji Feng, 2000. |