Servlets and JSP pages best practices

Source: Internet
Author: User
Tags filter connection pooling data structures expression html page implement include access
Js|servlet





Java servlet Technology and JSP technology enable Java server-side technology, currently they control the entire server-side Java technology market, and gradually become the standard for building commercial Web applications. Java developers like these technologies for a number of reasons, including: These technologies are easy to learn, write once, run everywhere (write Once, run Anywhere). More importantly, if the following practices are used more efficiently, servlet and JSP can help separate the representations and content of the Web. Best practices are proven to be a good way to develop high quality, reusable, and maintainable Web applications based on servlet and JSP. This corresponds to mixing Java code in HTML, which makes it easy to create complex applications that are inefficient, difficult to reuse, and difficult to maintain. Best practices will change these abuses.



This article will describe the importance of best practices for servlets and JSP preparation, assuming that the reader already understands the basic workings of both. This article will cover the following topics:


    • Provides a brief introduction to the Java servlet and JavaServer Pages (JSP).
    • Provides tips, tricks and rules for developing servlets and JSP.
    • Provides best practices for servlet and JSP.


Servlet and JSP pages overview



Similar to Common Gateway Interface (CGI) scripts, Servlets supports the request-response programming model. When a client sends a request to the server, it sends the request to the servlet. The servlet then builds a response that the server sends back to the client. Unlike CGI scripts, however, Servlets and HTTP servers run in the same process.



When a client request is made, the service method is invoked and a request and response object is passed. The servlet first determines whether the request is a get operation or a post operation. It then calls one of the following methods: Doget or DoPost. Call the Doget method if the request is get, and call the Dopost method if the request is post. Both Doget and Dopost accept requests (HttpServletRequest) and Responses (HttpServletResponse).



In the simplest sense, Servlets is a Java class capable of generating Dynamic HTML content using Print statements. One thing to mention, however, is that Servlets is run within a container, and APIs provide management of the lifecycle of sessions and objects. Therefore, when you use Servlets, you get all the benefits of the Java platform, including the sandbox (security), the database access API through JDBC, and the cross-platform portability of Servlets.



Java Server Pages (JSP)



JSP technology is a high-level abstraction of the servlet technology. It is a technology that is developed and opened by Sun and is similar to Microsoft's ASP Dynamic Web page technology and is a key component of the JAVA2 Enterprise Edition (Java EE). Currently, many business application servers (such as Bea WebLogic, IBM WebSphere, Live JRun, Orion, and so on) support JSP.



JSP How does the page work?



The JSP page is actually a Web page with traditional HTML and Java code. The file name extension for the JSP page is. JSP instead of. html or. htm, which tells the server that the page requires special processing that must be implemented by a server extension or plug-in.



When a JSP page is read, he will first be compiled (JSP engine to do this thing) as a servlet. At this point, the servlet is handed over to the servlet engine for processing like any other servlet. The servlet engine then reads the corresponding class of the servlet (with ClassLoader) and executes it, generating a Dynamic HTML page (Figure 1). The servlet creates the necessary components, writes them as a string to the output stream (OutputStream), and displays them in the browser.
When a JSP page is invoked, it is first compiled into a Java servlet (through the JSP engine). At this point, the servlet engine processes the servlet as it does with any other servlet. The servlet engine then loads the Servlet class (using the class loader) and executes it to create dynamic HTML sent to the browser, as shown in Figure 1. The servlet creates all the required objects and writes all objects as strings to the output stream and displays them in the browser.




The next time the page is requested, the JSP engine executes a servlet that is already loaded, unless the JSP page is changed early, in which case it is automatically recompiled into a servlet and executed.



Best practices



In this section, you will describe best practices in servelt, especially in JSP. JSP best practices are emphasized because JSP is more widely used than servlet (perhaps because JSP technology facilitates separation of representations from logic). One of the best practices for integrating servlet and JSP is the model-display-Controller design pattern (mode View Controller, MVC), which is discussed later in this article.


    • in the HTML do not use too much on the page Java code: Putting all the Java code directly in a JSP page is no problem for small projects, but overuse will result in spaghetti-like code that is difficult to read and difficult to understand. The way to reduce Java code is to write a separate Java class to implement logic such as computation. Once these classes are tested, an instance is created.
    • Choose the right include mechanism: It is a good idea to store headers, footers, and navigation bar content in a single file, and do not generate them again dynamically. Once this content is stored in separate files, it can be introduced into all pages using any of the following include mechanisms:
      1. Include directive: <%@ include file= "filename"%>
      2. Include behavior: <jsp:include page= "page.jsp" flush= "true"/>



When the JSP is being converted to a servlet, the first inclusion mechanism will contain the contents of the specified file (the transition phase), and for the second include mechanism, when the page is executed, the page contains the content produced with response. When the included page doesn't change too much, I recommend using the first include instruction method, which is faster and better, when the included file changes frequently (which also has dynamic content), and when the page is executed, it is not possible to identify the pages to be introduced. Use the second include behavior method.

Another include mechanism is to use the <c:import> behavior tags in the JSP standard Tag library (JSTL). You can use this method to include local or remote files, and here are some examples:


<c:import url= "./copyright.html"/>
<c:import url= "Http://www.somewhere.com/hello.xml"/>
    • do not mix business logic with presentation: in more complex applications, and when more code is introduced, it is important not to mix business logic with representations in the same file. Separating the business logic and representations so that when any one of them needs to be changed does not affect the other party. JSP is only represented as a foreground. So how do you implement the business logic section? This is the JavaBeans of the arena. JavaBeans technology is a lightweight, platform-independent build model that enables developers to write components and run them everywhere. In a JSP environment, the JavaBeans component processes the business logic and returns data to the JSP page, which in turn formats the data returned from the JavaBeans component for display in the browser. The JSP page operates on the Bean's properties by calling the Get method and the set method of the JavaBeans component. The benefits of using JavaBeans technology are as follows:
      1. Reusable: Different applications can use the same component.
      2. Separating the business logic from the presentation: You can change the appearance of the data on the JSP page without affecting the business logic. In other words, the web designer needs to focus on the design, and the Java developers need to focus only on the business logic.
      3. Keep the source code safe and protect your intellectual property.



If you use the Enterprise JavaBeans (EJBs) component in your application, you must keep the business logic in the EJB component, providing lifecycle management, transaction support, and access to the domain object (entity beans) for multiple clients. More detailed information can be obtained from the Enterprise blueprints.


    • using custom Tags: not all HTML content developers like to embed Java code (or scriptlets) in HTML documents, probably because they don't understand the Java language and are not happy to learn its syntax. But you can't use the JavaBeans component to encapsulate a lot of Java code, and using them in a JSP page still requires the content developer to have knowledge of Java syntax.

      JSP technology allows you to introduce new custom tags through tag library devices. As a Java developer, you can extend JSP pages by introducing custom tags that can be deployed and used in the syntax of HTML. Custom tags also allow you to provide better encapsulation by separating business logic and presentation logic further. In addition, they provide a way to customize the representation, which is hard to do with Jstl.

      Benefits of Custom Tags:
      1. They are able to eliminate scriptlets in JSP applications. Marking required parameters can be passed as attributes or content bodies, so Java code is not required to initialize or set component properties.
      2. Their syntax is very similar. Scriptlets is written in Java code, but can be used in HTML syntax like a custom tag.
      3. They can increase the productivity of non programmer content developers and allow them to perform tasks that HTML does not accomplish.
      4. They are reusable. Saves time for development and testing. Scriptlets is not reusable unless you "reuse" it by cutting and pasting.



In short, you can do complex tasks with custom tags using the same methods that you use to create an HTML expression.

When writing a custom tag library, you can use the following programming guidelines:


      1. Keep it simple: if you need to include more than one attribute in a tag, it's best to divide it into multiple tags.
      2. Make it available: Consult the consumer of the tag (HTML developer) for high availability.
      3. Don't invent a programming language in a JSP page: Do not develop custom tags to allow users to write explicit programs.
      4. Try not to reinvent the wheel: There are currently several JSP tag libraries available, such as Jakarta Taglibs Project. Check out these tag libraries to see if there's anything you want.
    • don't reinvent the wheel: while custom tags provide a way to reuse valuable components, you still have to create, test, and debug them. In addition, developers continue to reinvent the wheel, which is not the most efficient solution. The problem is to solve the JavaServer Pages Standard tag Library (JSTL) by providing a set of reusable standard tags. Jstl defines a set of standard tag libraries that work the same everywhere, so you no longer need to iterate through the collection with Scriptlet (or various vendor-supplied iteration tags). JSTL includes a variety of tags, loops, reads attributes without using Java syntax, iterates through various data structures, conditionally evaluates expressions, sets properties and script variables in an exact way, and analyzes XML documents.
    • Use JSTL Expression language: use JSP range properties and request parameters to pass information to a JSP page. An expression language (EL) is a language designed specifically for the author of a page, which promotes the JSP scope attribute to the standard method of communication between business logic and JSP pages. However, note that El is a key aspect of JSP technology, but it is not a general-purpose language. Moreover, it is a simple data access language that does not require the use of scriptlet or request-time expression values to easily access (and manipulate) the application data.

      In JSP 1.x, the page author must use an expression <%= aname%> to access the value of the system, as shown in the following example:
<sometags:atag attribute= "<%=
Pagecontext.getattribute ("Aname")%> ">


or custom JavaBeans component values:


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


An expression language allows page authors to access objects using simplified syntax. For example, you can use the following statement to access a simple variable:


<sometags:atag attribute= "${aname}" >


If you want to access nested JavaBeans properties, you can use the following statement:


<sometags.atag attribute= "${
ACustomer.address.country} ">


If you use JavaScript, you'll find it very familiar, because El uses JavaScript syntax to access structured data.


  • If you can use filters: filters are a new feature of JSP technology. If you've ever encountered a situation where multiple servlet or JSP pages need to compress their content, then in this case you can write a simple compression filter and apply it to all the resources. For example, in the Java blueprints, the signon is provided through a filter.
  • use a portable security model: Most servers provide server or vendor-specific security features, which limits developers to a particular server. To maximize portability of enterprise applications, a portable Web Application security model is used. In the end, however, this is a trade-off. For example, if you have a set of users that have long been defined, you can manage them using a form based login or Basic authentication. But if you want to create users dynamically, you need to use container-specific APIs to create and manage users. However, container-specific APIs are not portable, and the use of adapter (Adapter) Design patterns can overcome this.
  • use a database to store persistent information: You can use the HttpSession object to implement the session, which provides a simple and convenient mechanism for storing users and identifying the user's cookies. Use sessions to store temporary information-so even if the information is lost, you don't have to worry about it. (Session data is lost when the session expires or when the client changes the browser.) If you want to store persistent information and use a database, it is safer and more portable to share persistent information in a database between browsers.
  • Cached content: never dynamically regenerate content that does not change between requests. You can cache content on the client, proxy, or server side.
  • using the connection buffer pool: It is recommended to use JSTL for database access. But if you want to customize the behavior of database access, it is recommended that you use connection pooling, which effectively allows all requests to share database connections. Note, however, that the Java-EE server provides that functionality behind it.
  • Cached Database Request results: If you want to cache database results, do not use the JDBC ResultSet object as the cached object. It works closely with a link that conflicts with the connection pool. Copy data from resultset to a specific application bean, such as vector or JDBC rowsets.
  • when necessary, take a new JSP XML syntax: This is actually based on how you want your application to comply with XML. However, this needs to be weighed, because it makes JSP a more powerful tool, but less user-friendly for developers.
  • Read and apply Enterprise Blueprints: Sun's Enterprise Blueprints provides developers with guidelines, patterns, and example applications, such as Adventure Builder and pet Store. In general, the Java EE Blueprints offers best practices and a set of design patterns that are a solution to building problems that often arise in portable, robust, extensible Java applications.


Integrated Servlets and JSP pages



The JSP specification gives two scenarios for building Web applications using JSP pages: JSP model 1 and Model 2 architecture. The difference between the two models is the location of the processing. In the architecture of Model 1, as shown in Figure 2, the JSP page is responsible for processing the request and sending the response to the client.





Model 2 architecture, as shown in Figure 3, integrates the use of Servlets and JSP pages. In this model, JSP pages are used to represent layers, and servlets is responsible for handling various tasks. The servlet acts as a controller that handles requests and creates any beans that are required by the JSP page. The controller is also responsible for determining which JSP page to pass the request to. The JSP page retrieves the objects created by the servlet and extracts the dynamic content into a template.





This model facilitates the use of Model View Controller (MVC) architecture style design patterns. Note that multiple frameworks have long been able to implement this useful design pattern and truly separate content from presentation. Apache struts is a formal framework for MVC. The framework is ideal for complex applications where a single request or form submission can produce seemingly distinct results.



Conclusion



Best practices-proven solutions to recurring problems-produce high-quality applications. This article is a number of guidelines and best practices to follow when developing a servlet-and a JSP based Web application.



Keep an eye on servlets and JSP technology, because there are many exciting things in these technologies. For example, JavaServer Faces (JFC), a Java program community (Java Community process), aims to define a standard Web application framework that will be well integrated with Apache struts.









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: info-contact@alibabacloud.com 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.