Manage complex large sites with this servlet and JSP framework

xiaoxiao2021-03-06  185

Malcolm Davis Consultant February 2001

Content: Introduction JSP is the use of too many javamvcmvc model 2Struts in my HTML Detailed analysis Struts Mail list Sample Front comparison Struts Prospects Final Comment Reference Resources Author

This article describes Struts, which is a Model-View-Controller implementation using servlet and JavaServer Pages technology. Struts helps you control changes in the web project and improve the level of specialization. Although you may never use Struts to implement a system, you can use some of these ideas for your future servlet and JSP webpage implementation.

Introduction Primary school students can also post HTML web pages on the Internet. However, primary school students' web pages and professional development websites have quality. Web designers (or HTML developers) must understand colors, users, production processes, webline layouts, browser compatibility, image creation, and JavaScript, and more. The beautiful website needs to do a lot of work, most Java developers pay more attention to create a beautiful object interface, not the user interface. JavaServer Pages (JSP) technology provides web designers and Java developers with a link.

If you have developed a large web application, you understand the meaning of changing the word. "Model - View - Controller" (MVC) is a design pattern used to help you control changes. The MVC weakens the coupling between the business logic interface and the data interface. Struts is an MVC implementation that uses Servlet 2.2 and JSP 1.1 tags (belonging to J2EE specification) as part of the implementation. Although you may never use Struts to implement a system, you know that Struts may allow you to use some of the ideas for the JSP implementation of your later servlet.

In this article, I will discuss the advantages and disadvantages of the web page with a JSP file, which may be what you are familiar. Then I will discuss strut and explain how it controls changes in your web project and improves the level of specialization. Finally, I will re-develop this simple JSP file, I have taken into account in web designers and changes during the development process.

A JSP file is a Java ServletJavaserver page (jsp) file just another way of reviewing the servlet. The concept of JSP file allows us to view Java servlet as an HTML page. JSP eliminates the annoying PRINT () statement that often appears in the Java code. The JSP file is first preprocessed as .java files, then compile to .class files. If you are using Tomcat, you can view the pre-processed .java files in the Work directory. Other containers may store .java and .class files in other locations; this location is related to the container. Figure 1 illustrates the process from the JSP file to the servlet.

Figure 1. Process from JSP files to servlet

(This is clearly different from Microsoft's Active Server Page (ASP). Theasp is compiled into memory instead of compiling into a separate file.)

Simple stand-alone JSP files In a small JSP application, you often see data, business logic, and user interfaces are combined in a code module. In addition, applications typically include logic used to control application flow. Listing 1 and Figure 2 show a simple JSP file that allows users to join a mailing list.

Listing 1. Join.JSP - a simple request and response JSP file

<% @ page language = "java"%>

<% @ page import = "business.util.validation"%> <% @ page import = "business.db.mailinglist"%>

<%

String Error = "";

String email = Request.getParameter ("email");

/ / Is there an email address?

IF (email! = null) {

// Verify input ...

IF (Business.util.Validation.issalidemail (email)) {

// Storage input ...

Try {

Business.db.mailingList.addemail (email);

} catch (exception e) {

Error = "Error adding email address to system." E;

}

IF (Error.Length () == 0) {

%>

/ / Redirect to Welcome Page ...

<%

}

} else {

/ / Set the error message and resume the web page

Error = Email "IS Not a Valid Email Address, please try again."

}

} else {

Email = "";

}

%>

Join Mailing List

<% = Error%>

ENTER Your Email To join the group

Figure 2. In a simple request and response, the JSP file sets the data, controls the process of the next web page and creates HTML

This mailing list JSP file is an independent and autonomous module that completes all tasks. Only code not included in this JSP file is the actual verification code included in IsValideMail () and the code to store the email address into the database. (ISVALIDEMAIL () method seems to be of course selection in reusable code, but I have seen the isvalidemail () code directly embedded in the web page. The advantages of a single page method are easy to understand, and it is also easy to build. In addition For a variety of graphical development tools, it is easy to get started.

Join.JSP activities

Display the open input web page. Read the value of Email from the form parameter. Verify the Email address. If the email address is valid:

Add this address to the database. Redirect to the next page. If the email address is invalid:

Set an error message. Re-display Join.jsp containing the error message.

Frequency of single page

The writers of HTML and Java strong coupling JSP files together must be both web designers and Java developers. The result is usually either a very bad Java code, either a grunge web page, sometimes even Java code and web pages are very bad. The shortcomings of Java and JavaScript have gradually become bigger with web pages, and it is easy to think of some JavaScript. This script may be confused with Java code when JavaScript appears in a web page. An example of possible confusion is to verify the Email domain using JavaScript using the client. The embedded process logic understands the entire process of the application, and you must browse all the web pages. Imagine the intricate logic of the website with 100 webpages. In addition to the worse appearance, the HTML tag, Java code, and JavaScript code are set in a web page and make debugging quite difficult. Strong coupling changes business logic or data may involve each web page. Aesthetics is in a large web page, this code style looks messy. When I was developed by Microsoft ASP, I often saw a 1000-line web page. Even with color syntax shows that reading and understanding these codes is still more difficult. Please don't join too much Java code in my HTML in Listing 1, not having a lot of HTML in the Java code, but there is a lot of Java code in the HTML file. From this point of view, in addition to allowing web designers to write Java code, I don't actually do anything. However, we are not all; in JSP 1.1, we get a new feature called "tag".

The JSP tag is just a way to extract the code from the JSP file. Some people regard JSP tags as a macro of the JSP file, which is included in the servlet used for this tag. (Macro's view is largely correct.) For the same reason, I don't want to see HTML tags in the Java code, and I don't want to see Java code in the JSP file. The entire starting point of JSP technology is to allow web designers to create servlets without entanglement of Java code. The tag allows Java programmers to extend JAVA code into HTML to extend JSP files. Figure 3 shows the general concepts of extracting code from the JSP page and put them in a JSP tag.

Figure 3. JSP tag

Listing 2 is an example in which the function of the Struts tag is used. In Listing 2, normal HTML

Model - Session Status Joinform extends ActionForm and contains form data. The form data in this example only has an email address. I have added a write method and reading method to the email address for framework access. For convenience of explanation, I rewrite the validate () method and use the Struts tracking function. Struts will create Joinform and set status information.

Model - Business Logic As mentioned before, Action is an interface between the controller and the actual business object. JoinAction wrapped in call to Business.jar, which was originally in the join.jsp file. JoinAction's Perform () method lists in Listing 5.

Listing 5. - joinaction.perform ()

Public ActionForward Perform (ActionMapping Mapping,

Actionform Form,

HTTPSERVLETREQUEST REQUEST,

Httpservletresponse response

THROWS IOException, servletexception {

// Extract the properties and parameters we will use

JOINFORM JOINFORM = (JOINFORM) Form;

String email = joinform.getemail (); actionerrors errors = new actionerrors ();

// Store input ....

Try {

Business.db.mailingList.addemail (email);

} catch (exception e) {

// Record the log, print the stack

// Disconnect the wrong back to the user

Errors.Add ("email", new actionerror ("error.mailing.db.add"));

}

// If you need any messages, save the specified error message key to

// HTTP request for

Tag use.

IF (! errors.empty ()) {

SaveerRors (Request, Errors);

// Return to the initial form

Return (maping.getInput ())));

}

// Transfer control to the 'Success' URI specified in Action.xml

Mapping.Findforward ("Success"));

}

Note: Perform () returns a class called an ActionForward that does this class notify the controller what to do next. In this example, I use the mapping that is incorporated from the controller to determine the next step.

The controller I have modified the JSP file and create two new classes: A class is used to include form data, a class to call the business package. Finally, I integrate them by modifying profile struts-config.xml. Listing 6 shows the Action elements I added, this element is used to control the process of JoinMvc.jsp.

Listing 6. Action configuration

The Action element describes a mapping from the request path to the corresponding Action class, which should use these classes to handle requests from this path. Each request type should have a corresponding action element to describe how to handle the request. For Join Request:

Joinform is used to accommodate form data. Because Validate is marked as True, Joinform will try to perform self-authentication. Web.mailingList.joinAction is an Action class to handle requests to this mapping. If everything goes well, the request will go to Welcome.jsp. If a business logic failure occurs, the process will return to Joinmvc.jsp, which is a web page that originally issued a request. Why is this so? In the Action Element of Listing 6, there is an attribute called INPUT whose value is "/jinmvc.jsp". In my joinaction.perform () (as shown in Listing 5), if the business logic fails, Perform () returns an actionforward and as mapping.getInput () as a parameter. The getInput () in this example is "/joinmvc.jsp". If the business logic fails, it will return to Joinmvc.jsp, which is the first page that was originally issued.

The comparison before and after using Struts is as seen in Figure 9, has a significant increase in complexity and layers. No longer there is a direct call from the JSP file to the Service layer.

Figure 9. Comparison before and after Struts

Struts Advantages

The use tag feature of the JSP tag mechanism is a reusable code and abstract Java code from the JSP file. This feature is well integrated into JSP-based development tools, which allows you to write code with tags. Why should the tag library have an inventive wheel or a tag library? If you can't find the tag you want in the library, then you will define it. Also, if you are learning JSP tag technology, Struts provides you with a starting point. Open source You can get all the advantages of open source, such as you can view the code and check each person of the library to check the code. Many people can check very well. MVC implementation If you want to create your own MVC implementation, Struts can increase your knowledge. Management problem spatial rules are excellent ways to solve problems and make problems manageable. Of course, this is a double-edged sword. The problem is getting more complicated, and more and more management is needed. Struts Disadvantages

The development of Struts is still in the initial stage. They are working hard to the release version 1.0, but as with any 1.0 versions, it is impossible to do it. This frame is still changing in a variety of changes. Struts 1.0 varies greatly compared to Struts 0.5. In order to avoid the use of the method that does not agree, you may need to download the latest Struts over one day. In the past 6 months, I witnessed the Struts library increased from 90k to 270K. Due to changes in Struts, I have to modify my example several times, but I don't guarantee that my example works with Struts you downloaded. Does the correct abstraction level Struts provide the correct abstraction level? What is the correct abstraction level for web designers? This is a problem with the text with $ 64K. In the development of a web page, should we let the web designers visited the Java code? Some frameworks (such as velocity) should not, but it provides another web development language to make us learn. Restrict access Java in UI development has certain rationality. Most importantly, if web designers use a little Java, he will use a lot of Java. In the development of Microsoft ASP, I always see this situation. In ASP development, you should create a COM object, then write a small amount of ASP scripts to link these COM objects. However, ASP developers will use ASP scripts crazy. I will hear this, "Since I can write COM objects with VBScript, why should I wait for COM developers to create it?" By using the tag library, Struts helps limit the Java code required in the JSP file. Quantity. Logic Tag is a library that manages conditionally generated output, but this does not prevent UI developers from fanatizing the Java code. Whether you decide which type of framework you want to use, you should know the environment you want to deploy and maintain the framework. Of course, this task is really difficult to do. Limited Scope Struts is a web-based MVC solution that must be implemented with HTML, JSP files, and servlets. The J2EE application supports Struts that requires Servlet containers that support JSP 1.1 and Servlet 2.2 specification. This is far from which you can solve all your installation issues unless Tomcat 3.2 is used. I am installing this library with Netscape Iplanet 6.0, I encountered a lot of problems, and it is the first application server that meets J2EE. I recommend that you access the archive of the Struts user mailing list when you encounter problems (see Reference Resources). The complexity is also introduced into several parts of several parts. There is no doubt that you must understand that struts must accept certain training. As the changes continue to join, this is sometimes very frustrating. Welcome to this website. Where can I still point out other issues, for example, where the controller's client verification, how can the workflow and dynamic policy mode? However, this is now too easy to become a problem of phenomenon, some problems are irrelevant, or these issues should be issued for 1.0 issues. With the continuous efforts of the Struts team, Struts may have these features when you read this article, or it will have these features soon.

Struts's prospects in this new era development, everything has become very fast. In less than five years, I have witnessed from CGI / Perl to ISAPI / NSAPI, and then use VB's ASP, until the current Change of Java and J2EE. Sun is trying to reflect new changes to the JSP / Servlet architecture, as they are the same as the change made by the Java language and the API. You can get a new draft of JSP 1.2 and Servlet 2.3 specification from Sun's website. In addition, a standard JSP tag library is about to appear; for links to these specifications and tag libraries, see Reference Resources. The final comment Struts uses tags and MVC to solve certain major problems. This method helps to increase the reusability and flexibility of the code. By dividing problems into smaller components, you have more opportunity to reuse code when there is a change in technical space or problem space. In addition, Struts enables web designers and Java developers to focus on their best aspects. However, while strongness is enhanced, it also means complexity increases. Struts is much more complicated than a simple single JSP page, but for larger systems, Struts actually helps manage complexity. In addition, I don't want to write my own MVC implementation, but I just want to know a such implementation. Whether you will use Struts, review this Struts framework (sorry, it should be library) will make you a better understanding of the JSP file and servlet, and how to combine them for your next Web project. The positive image wing pillar is an indispensable part of the wing structure, and Strut may become an indispensable part of your next web project.

Reference resource

You can download the code used herein: Business.zip is used to build business.jar files, JoinStruts.zip is used to build JoinStruts.war files. For documents, installation instructions, and downloads about Struts, see the home page of Struts. You can download the most recent Struts from the Jakarta project. If you want to get started, I suggest you download the reference to the JSP Servlet implementation Tomcat 3.2. If you use a container other than Tomcat, visit the Struts user mailing list to get the help of installing Struts in your specific environment. To get information not included in the Document or Install Guide, see the Struts User Mail List Archive File. The Apache Mail list archive contains Struts information that archives with other information. To understand more information that will build and test the process, see "Incremental Development With Ant and Junit". See Proposed Final Draft for Java Servlet 2.3 and JavaServer Pages 1.2 Specifications. See Standard Tag Library for JavaServer Pages, JSR # 000052.

About the author Malcolm G. Davis lived in Alabama Birmingham City, he was president in his own consulting company. He claims to be a Java officer. He will go to the long run in the leisure time of promoting Java, or play with your child. You can contact Malcolm via Malcolm@Nuearth.com.

转载请注明原文地址:https://www.9cbs.com/read-128618.html

New Post(0)