Servlets and JSP development principles

Source: Internet
Author: User
Tags filter connection pooling contains data structures expression implement include interface
The Js|servlet servlet and JSP technology is the main technology used in Java Development server-side application, and is the standard of developing business application presentation end. Java developers like to use it for a variety of reasons, one is familiar with the Java language developers are easy to learn the technology, the second is the "write, run everywhere" concept into the Web application, the implementation of the "write, everywhere." And more importantly, if you follow some good design principles, you can separate the presentation from the content, creating high-quality, reusable, easily maintainable and modified applications. For example, if you embed too much Java code (scriptlet) in an HTML document, you can create applications that are complex, difficult to read, easy to reuse, and difficult to maintain and modify later. In fact, in the CSDN jsp/servlet forum, often can see some questions, the code is very long, can be logical but not very clear, a lot of HTML and Java code mixed together, let people see confused. This is the abuse of random development.

If you have a basic understanding of the JSP and servlet technologies (preferably with some Web applications), we can explore some of the guidelines for how to develop "good" applications. Let's start by browsing the servlet and JSP technologies.

Servlet and JSP overview

The early dynamic Web pages mainly use CGI (Common Gateway Interface, Common Gateway Interface) technology, you can use different languages to write CGI programs, such as VB, C + + or Delphi. Although the CGI technology is mature and powerful, it has been replaced gradually because of the shortcomings of programming difficulty, inefficiency and complex modification. Among all the new technologies, Jsp/servlet has become more efficient, easier to program, more powerful, more secure and more portable, and thus is considered by many to be the most promising Dynamic Web site technology in the future.

Like CGI, the servlet supports the request/response model. When a client submits a request to the server, the server sends the request to Servlet,servlet responsible for processing the request and generating the response, which is then sent to the server and sent to the client by the server. Unlike CGI, the servlet does not generate a new process, but rather is in the same process as the HTTP server. It reduces the cost of the server by using threading technology. The servlet processes the request by invoking the service method when a request is received from the client, in which the servlet first determines what type of request is coming (Get/post/head ...). , and then calls the appropriate processing method (Doget/dopost/dohead ...). ) and generate a response.

Don't look so complicated, in fact, a servlet is simply a Java class. Unlike the general class, this class runs within a servlet container, providing session management and object Lifecycle management. So when you use the servlet, you can get all the benefits of the Java platform, including security management, access to the database using JDBC, and cross-platform capabilities. Also, the servlet uses threads, so that it can develop more efficient web applications.

JavaServer Pages (JSP)

JSP technology is a key technology of Java EE, it abstracts the servlet at a higher level. It allows regular static HTML to be combined with dynamically generated content that looks like an HTML Web page, but runs as a servlet. There are many commercial application servers that support JSP technology, such as Bea WebLogic, IBM WebSphere, JRun, and so on. Using JSPs is simpler than using a servlet. If you have a Web server that supports JSP, and you have a JSP file, you can put it in a position where any static HTML file can be placed, without compiling, without packaging, and without classpath settings, you can access it like a regular web page, The server will automatically help you do other work.

JSP working principle

The JSP file looks like a normal static HTML file, except that it contains some Java code. It uses the. jsp suffix to tell the server that the file needs special processing. When we visit a JSP page, the file is first translated by the JSP engine into a Java source file, which is actually a servlet, compiled, and then processed by the servlet engine like any other servlet. The servlet engine loads this class, processes requests from customers, and returns the results to the customer, as shown in the following illustration:

screen.width-333) this.width=screen.width-333; " >
Figure 1: The process of invoking the JSP page

As soon as a client visits this page, the JSP engine directly invokes the servlet that has been mounted as long as the file has not changed. If you have already done so, you will perform the above process again, translating, compiling, and loading. In fact, this is the so-called "first person punishment." Because it takes a while to perform more than a series of processes during the first visit, this will not be the case in future visits.
Development principles

In this section we list some development principles, focusing on JSP pages. about how to detach the performance and content of MVC because it involves the integration of JSP and servlet, we'll talk about it later.

Do not embed excessive Java code in JSP pages: for very simple or testable code, it is no problem to put all the Java code directly into the JSP page. But this method should not be overused, otherwise it would produce a lot of HTML and Java mixed code, it is difficult to read and understand. The solution is to write a separate class that performs the related calculations. Once this class test passes, it can be placed in any instance where the same calculation is performed. This can facilitate the reuse of code.

Select the appropriate include (include) mechanism: if each page in an application has the same header and bottom, or navigation bar, then you should put them in a separate file and use the inclusion mechanism in each page to add them to the page:

Include directives: <%@ include file= "filename"% or equivalent XML syntax
<jsp:directive.includefile= "FileName"/>

Include actions: <jsp:include page= "page.jsp" flush= "true"/>

The include directive is to include another file when the JSP page is translated into a servlet, including the output of another file when the request is requested. If the included files are not constantly changing, I recommend using the include directive, which is faster. Include actions should be used if the included files need to be changed from time to again, or when the request is known to determine what needs to be included.

If you use the JSP Standard tag library (JavaServer pages Standard tag libraries, jstl), then there is a third containing mechanism <c:import> that can be used to contain local or remote resources. For example:

<c:import url= "./copyright.html"/>
<c:import url= "Http://"/>

Do not mix business logic with presentation: Complex applications involve a lot of code, so separating the business logic from the presentation of the front-end is especially important, and this separation can make the changes on either side not affect the other side. So, all JSP code should be limited to the presentation layer, but if so, how do you implement your business logic? This is what JavaBean does. JavaBean Technology is a platform-independent component model that allows developers to write and test a component that can be used everywhere and improve reusability. In the JSP technology, JavaBean realizes the business logic part, it returns the data to the JSP page, the JSP page is responsible for formatting the data and outputting to the client's browser. The benefits of using the JavaBean component in a JSP page are:

Produces reusable components: Any application can use these components

You can separate the business logic from the presentation: You can modify how the data is displayed without considering the business logic. This results in a clear division of work among developers, where web developers can focus on how to display data, and Java developers are more concerned with the implementation of business logic.

For JavaBean you do not have to provide source code, so that your code will not be easy access to the browser Web page, you can protect the fruits of your labor.

If you use EJB components in your application, the business logic should be placed in the EJB because the EJB model provides lifecycle management, transaction management, and multiple client Access domain objects (Entity Beans). You can take a closer look at the example in enterprise blueprints, and that's what it does.

Using custom Tags: as we've discussed above, it's not appropriate to embed all the Java code inside a JSP page, because Web developers don't necessarily know the Java language and are more difficult to understand Java syntax. JavaBean can encapsulate a lot of Java code, but using JavaBean in a JSP page still requires the page developer to understand some Java syntax.

JSP technology contains the functionality of a custom tag library. Java developers can build their own tag libraries so that page designers can use HTML-like syntax to work with these tags. Writing and using your own custom tag libraries can contribute to greater separation of business logic and presentation. Using a custom tag library has the following main benefits:

You can eliminate any parameters that are used with the scriptlet tag in a JSP page by passing properties, so that you do not need to use Java code to achieve the desired purpose.

You can simplify the use of web designers without learning to use Java syntax, they can use tags like HTML syntax.
Web page designers who do not know Java can use tag libraries to accomplish tasks that cannot be accomplished by using HTML alone.

Improved reuse tag libraries are fully reusable, which can save time for development and testing. Scriptlet code can only be reused at the copy paste level.

To put it simply, you can use a tag library to do very complex tasks like using the HTML build presentation layer. Here are some considerations for the table page tag library:

1. Keep it simple: If a tag requires several attributes, divide it into several tags as much as possible.

2. Maintain the reusability: With the user of the Mark (Web designer) a lot of communication, as far as possible to develop a highly reusable tag library.

3. Don't start all over again: there are some tag libraries that you can use for free, such as Jakarta Taglibs. If you want to use a tag, first see if there is already a ready-made available.

Don't "Reinvent the wheel", don't start all over again: by customizing components You can improve reusability, but custom components still need to write, test, and debug programs. The problem is that someone else may have achieved it, and you don't have to do it better than others. This is what the JSP Standard Tag library (JavaServer Pages Standard tag Libraries, JSTL) to do (JSTL please refer to the JSTL official website). JSTL provides a variety of tags such as looping, reading properties, traversing various data structures, and evaluation of conditional expressions. It also provides a number of complex tags, even like parsing XML document tags. So if you're going to use a tag, it's best to see if there's someone else you can use instead of starting from scratch and doing it yourself.

Use JSTL expressions to make the language (JSTL Expression Language): The data passed to the JSP page is typically done through the JSP scope properties or request parameters. The expression language specifically designed for Web developers (Expression Language, EL) uses scope attributes to pass information as a standard way of delivering information from business logic to JSP pages. It's important to note that El is just one of the key aspects of JSP technology, not a general-purpose programming language. Instead, it is just a data access language that simplifies access to data in an application, and can be accessed without scriptlet and request-expression evaluation.
In JSP, a web designer uses the expression syntax <%= name% or JavaBean components to get the values of certain variables or attributes, such as:

<taglib:tag attribute= "<%=

Pagecontext.getattribute ("name")%> ">


<%= acustomerbean.getaddress (). Getcountry ()%>

Expression enables a web designer to use simplified syntax to access information. If you just want to access a simple variable, you can use this syntax:

<taglib:tag attribute= "${name}" >

If you want to access a nested JavaBean attribute, you can do this:

<taglib:tag attribute = "${} ">

The expression language (EL) borrows the JavaScript syntax, so if you're familiar with JavaScript, you'll feel great.

Use Filter: A filter is an object that can transfer requests or modify responses. It can be preprocessed before the request reaches servlet/jsp and can be processed after the response leaves the servlet/jsp. So if you have several servlet/jsp that need to perform the same data conversion or page processing, you can write a filter class and then associate the filter with the corresponding servlet/jsp in the deployment description file (web.xml).

Creating a filter is really easy, you just have to implement the Javax.servlet.Filter interface and its three methods:

public void init (filterconfig config)

public void Dofilter (ServletRequest req, Servletresponse Rep,

Filterchain chain)

public void Destroy ()

This way, you can finish your filter.

Using a portable security model: Most application servers provide a security model, but generally they are proprietary to a single server or to a particular vendor. If your application needs to be ported, then your application is best to use a portable security model. If your application has some pre-defined fixed users, you can use from and basic validation. However, if you want to dynamically generate customers (which is generally the case), you may need to use server-specific APIs to create and manage users. This way, when your application is ported to another server, you may encounter problems with API incompatibility. In this case, the best solution is to use the adapter (Adapter) mode (if you are unfamiliar with the design pattern, refer to Gof's "design Patterns" book).

Use a database to hold persistent data: servlet/jsp can use the HttpSession object, which is the session object, to hold the user's temporary data. However, if you want to save persistent data, you should use the database, the data to save the data will be more secure, and the customer's browser does not have any requirements. So even if your application server crashes for some reason, your data is still good.

Cache Pages: There are always some things in the application that are relatively fixed, while others are constantly changing. You should use static HTML documents to store the relatively fixed content so that the client can cache, and each time the client accesses your application, it simply accesses the part that has changed. This will speed up the customer's access.

Use connection pooling: If you want to write your own database access code, I think you should learn how to use the database connection pool technology. Each server has a configuration document for the database connection pool, and you need to learn how to use it. Database connection pooling can speed up data access for your application, and because the server manages the database connection for you, this can save you a lot of work.

Cached database Access results: If your application has frequent access to the database, you can use an object to cache your data, so you can save a lot of access to the database. In the "Java-ee core model" and "Practical Java Design mode Programming Guide" two books have about the value object pattern (values objects patterns) Detailed discussion, you can refer to these two books to obtain the appropriate knowledge.

Using the data Access object pattern: If your application requires access to multiple database systems or may migrate to other storage systems, your optimized code for a particular vendor may fail. There is a problem of execution efficiency with common code, and there are porting problems with optimized code. So the data Access object pattern, which provides both the adaptability of the database vendors and the unique benefits they offer, is generated. In accordance with the principle of object-oriented separation tasks, this pattern isolates the logic required by the Enterprise Information System (Enterprise information System, EIS) into its own class. In this way, object objects, such as servlet/jsp components, JavaBean, can use data Access Objects (DAO) to handle all EIS-related transactions.

It is best to use JSP XML syntax: JSP technology often exists in two kinds of syntax to complete the same task, one is the general JSP syntax, one is the corresponding XML syntax. Although the two syntaxes work the same way, you'd better use XML syntax. The reason for the existence of two syntaxes is that JSP syntax can be compatible with previous code, while Java EE uses XML as the core of its exchange data, so it also provides XML syntax. With the development of Java EE, XML will become more and more important, so I suggest you use XML syntax.

Studying Sun-provided Java EE Blueprints:sun's Enterprise blueprints offers a number of guiding principles, design patterns and good examples (pet stores, pet store). You can take a good look at the content, so you can improve your design and development level.
Consolidating servlet and JSP

JSP technology specification species gives two ways to use JSP to develop Web applications, which can be summed up as model one and model two, and the main difference between the two models is that they deal with different processes of the business. Model one, as shown in the following figure, is called the Jsp+javabeans model. In this model, the JSP page responds to the request alone and returns the processing results to the customer, all the data is processed by JavaBean, and the JSP realizes the performance of the page.

screen.width-333) this.width=screen.width-333; " >
Figure 2:jsp Model One

As can be seen from the above figure, the model one also realizes the separation of the page performance and the business logic. In this way, however, a lot of Java code is used in JSP pages, which can be very bad when the business logic that needs to be handled is complex. A large number of embedded code makes the entire page program extremely complex. This is a nightmare for Web developers who design the front-end interface. Therefore, the model one can not meet the needs of large applications, but for small applications, because the model is simple, do not involve a number of elements, so as to meet the needs of small applications, so in a simple application, you can consider model one.

Model two, as shown in the following figure, is called the Jsp+servlet+javabeans model. This model combines JSP and servlet technology, taking full advantage of the original advantages of JSP and servlet two technologies. This model uses JSP technology to represent pages, uses servlet technology to do a lot of transaction processing, and uses beans to store data. The servlet handles the requested transaction, acts as a controller, and is responsible for sending the request to the customer. It creates the beans and objects that the JSP needs, and then decides which JSP page to send to the customer based on the behavior of the user's request.

screen.width-333) this.width=screen.width-333; " >
Figure 3:jsp Model II

From a development point of view, model two has a clearer page performance, clear Development Role Division, can take full advantage of the development team of Web designers and Java developers. These advantages are particularly prominent in large-scale projects, web designers can give full play to their own art and design to fully represent the page, program writers can give full play to their own business logic processing thinking, to achieve the business process in the project.

In addition, from the design structure, this model fully embodies the Model View controller (MVC) design framework. In fact, many of the existing development frameworks are based on this model, fully implementing MVC, such as the Apache Struts framework and the JavaServer faces framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.