Java Servlet and JSP technologies enable Java Server 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 many reasons, including: these technologies are easy to learn, one-time writing, and Run everywhere (Write Once, Run Anywhere ). More importantly, if the following practices are adopted more efficiently, Servlet and JSP can help separate the Web representation and content. "Best practices" are proven to be a good way to develop high-quality, reusable, and easily maintained Web applications based on Servlet and JSP. Correspondingly, Java code is mixed in HTML, which can easily produce complicated applications that are inefficient, reusable, and difficult to maintain. Best practices will change these drawbacks.
This article describes the importance of the best practices for Servlet and JSP preparation. Here we assume that the reader has understood the basic working principles of both. This article covers the following content:
Similar to the Common Gateway Interface (CGI) script, servlets supports the request response programming mode. When a client sends a request to the server, the server sends the request to the servlet. Then, the servlet constructs a response, and the server sends the response back to the client. However, unlike CGI scripts, servlets and HTTP servers run in the same process.
When sending a client request, call the service method and pass a request and response object. Servlet first checks whether the request is a GET operation or a POST operation. Then it calls the following method: doGet or doPost. If the request is GET, the doGet method is called. If the request is POST, The doPost method is called. Both doGet and doPost accept requests (HttpServletRequest) and responses (HttpServletResponse ).
In short, servlets is a Java class that can use print statements to generate dynamic HTML content. However, it must be mentioned that servlets runs in a container and APIs manages the session and object lifecycle. Therefore, when using servlets, you can gain all the advantages of the Java platform, including sandbox (Security), database access API through JDBC, and Server Load balancer with cross-platform portability.
Java Server Pages (JSP)
JSP technology is a high-level abstraction of Servlet technology. It is a technology developed and open by Sun, similar to Microsoft's ASP dynamic web page technology, and is a key component of Java2 Enterprise Edition (J2EE. Currently, many commercial application servers such as BEA WebLogic, IBM WebSphere, Live JRun, and Orion support JSP.
How does a JSP page work?
JSP pages are actually Web pages with traditional HTML and Java code. The file extension name on the jsppage is .jspand not .htmlor .htm. This extension tells the server that the page needs special processing. This special processing must be implemented by server extensions or plug-ins.
When a JSP page is read, it is first compiled into a Servlet. At this time, this Servlet is handed over to the Servlet engine for processing like other servlets. Then the Servlet engine reads the corresponding Servlet class (using ClassLoader) and executes it to generate a dynamic HTML page 1 ). This Servlet creates some necessary components, and then writes these components as a string to the output stream (OutputStream) and displays them in the browser.
When calling a JSP page, it is first compiled into a Java servlet (through the JSP engine. In this case, the servlet engine processes the servlet just like any other servlet. Then, the servlet engine loads the servlet class (using the Class Loader) and executes it to create dynamic HTML and send it to the browser, as shown in 1. The Servlet creates all required objects, writes all objects to the output stream as strings, and displays them in the browser.
When you request this page the next time, the JSP Engine executes a servlet that has been loaded for a long time unless the JSP page has been changed for a long time. In this case, it is automatically re-compiled into a servlet and executed.
Best practices
This section describes best practices in Servelt, especially JSP. The best practice of JSP is emphasized because JSP is more widely used than Servlet, maybe because JSP technology promotes the separation of representation and logic ). The best practice for integrating Servlet and JSP is Model View Controller (MVC), which will be discussed later in this article.
Do not use too much Java code on the HTML page: Place all Java code directly on the JSP page. This is no problem for small projects, but over-using it will lead to spaghetti-like code, difficult to read and understand. The method to reduce Java code is to write independent Java classes to implement computing logic. Once these classes are tested, an instance is created.
Select an appropriate include mechanism: it is best to store the content of the header, footer, and navigation bar in a single file, and do not generate them dynamically again. Once these contents are stored in each independent file, you can use any of the following include mechanisms to introduce them to all pages:
Include command: <% @ include file = "filename" %>
Include behavior: <jsp: include page = "page. jsp" flush = "true"/>
When JSP is being converted to Servlet, the first include mechanism will contain the content of the specified file (in the conversion phase). For the second include mechanism, when the page is executed, the page contains content generated by Response. When the contained page does not change much, I recommend the first include command method, which is faster and better in performance; when the contained file often changes and contains dynamic content), and the page to be introduced cannot be determined during the execution of the home page, the second include behavior method is used.
Another include mechanism is to use the <c: import> behavior tag in JSTL. You can use this method to include local or remote files. The following are some examples:
- <c:import url="./copyright.html"/><c:import url=
"http://www.somewhere.com/hello.xml"/>
Do not mix business logic and Representation: when more code is introduced into more complex applications, it is important not to mix the business logic and representation in the same file. Separate the business logic and representation so that any change required by either party will not affect the other party. JSP is only used as the front-end representation. How can we implement the business logic? This is the application of JavaBeans. The JavaBeans technology is a lightweight, platform-independent model that allows developers to write components and run them everywhere. In the 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 calls the get method and set Method of the JavaBeans component to operate on Bean attributes. The advantages of using JavaBeans technology are as follows:
Reusable: different applications can use the same component.
Separation of business logic and representation: You can change the data display appearance on the JSP page without affecting the business logic. In other words, web designers only need to focus on design, while Java developers only need to focus on business logic.
Maintain source code security and protect your intellectual property rights.
If you use the Enterprise JavaBeans (EJBs) component in your application, you must keep the business logic in the EJB component to provide lifecycle management, transaction support and multi-client access to the domain object Beans. You can obtain more detailed information in Enterprise BluePrints.
Using custom tags: not all HTML content developers like to embed Java code (or scriptlets) into HTML documents, it may be because they do not know the Java language and are not willing to learn its syntax. However, you cannot use the JavaBeans component to encapsulate a lot of Java code. using them on JSP pages still requires content developers 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 HTML syntax. Custom tags allow you to provide better Encapsulation by further separating the business logic and representation logic. In addition, they provide custom representation methods, but it is difficult to do this with JSTL.
Benefits of custom tags:
They can eliminate scriptlets in JSP applications. Required parameters can be passed as attributes or content bodies. Therefore, you do not need to initialize Java code or set component attributes. Their syntax is very similar. Scriptlets is written in Java code, but you can use custom tags in HTML-like syntaxes. They can improve the productivity of non-programmer content developers and allow them to execute tasks that cannot be completed by HTML. They are reusable. It saves time for development and testing. Scriptlets is not reusable unless you cut and paste it to "reuse ". In short, you can use the same method as creating an expression in HTML to complete complex tasks with custom tags. When writing a custom tag library, you can use the following programming guide: Keep Simplicity: If you need to include multiple attributes in a tag, you 'd better divide it into multiple tags. Make it available: Consult the user HTML Developer) to obtain high availability. Do not create a programming language on the JSP page: do not develop custom tags for users to write explicit programs. Try not to re-invent the wheel: There are currently multiple JSP tag libraries available, such as Jakarta Taglibs Project. Check these tag libraries to see if you have what you want.
Do not reinvent the wheel: although custom tags provide methods to reuse valuable components, they still need to be created, tested, and debugged. In addition, developers still need to constantly re-invent the wheel, and the efficiency of this solution is not the highest. The problem is to provide a set of reusable Standard tags to solve the problem of JavaServer Pages Standard Tag Library (JSTL ). JSTL defines a set of standard tag libraries that work the same way anywhere, so that you no longer need to use scriptlet or iterative tags provided by various vendors) to iterate in the set. JSTL includes various tags, loop, read attributes without using Java syntax, iterate various data structures, calculate expressions conditionally, set attributes and script variables in a precise way, and analyze XML documents.
Use JSTL Expression Language: use JSP range attributes and request parameters to pass information to the JSP page. Expression Language (EL) is a language specially designed for page authors to promote JSP range attributes to the standard method for business logic to JSP page communication. However, Servlet and JSP should be noted, but EL is a key aspect of JSP technology.
- Analysis of the best solution example of JSP IIS
- Can JSP meet the Web boom?
- Multi-thread synchronization in Servlet and JSP
- Is JSP a major failure in the Development of Java?
- JSP blocks the JSF light like a dark cloud