1、 外文翻译 Servlets and JSP Pages Best Practices Material Source: Oracle magazine Author: Qusay H.Mahmoud Java Servlet technology and JavaServer Pages (JSP pages) are server-side technologies that have dominated the server-side Java technology market, theyve become the standard way to develop commercial
2、web applications. Java developers love these technologies for myriad reasons, including: the technologies are fairly easy to learn, and they bring the Write Once,Run Anywhere paradigm to web applications. More importantly, if used effectively by following best practices,servlets and JSP pages help s
3、eparate presentation from content. Best practices are proven approaches for developing quality, reusable, and easily maintainable servlet and JSP based web applications. For instance, embedded Java code (scriptlets) in sections of HTML documents can result in complex applications that are not effici
4、ent, and difficult to reuse, enhance, and maintain. Best practices can change all that. In this article, Ill present important best practices for servlets and JSP pages ;I assume that you have basic working knowledge of both technologies. This article: 1 Provides hints, tips, and guidelines for work
5、ing with; 2 ervlets and JSP pages; 3 Provides best practices for servlets and JSP pages; 1. Overview of Servlets and JSP Pages Similar to Common Gateway Interface (CGI) scripts, servlets support a request and response programming model. When a client sends a request to the server, the server sends t
6、he request to the servlet. The servlet then constructs a response that the server sends back to the client. Unlike CGI scripts, however, servlets run within the same process as the HTTP server. When a client request is made, the service method is called and passed a request and response object. The
7、servlet first determines whether the request is a GET or POST operation. It then calls one of the following methods: doGet or doPost. The doGet method is called if the request is GET, and doPost is called if the request is POST. Both doGet and doPost take request ( HttpServletRequest) and response (
8、 HttpServletResponse). In the simplest terms, then, servlets are Java classes that can generate dynamic HTML content using print statements. What is important to note about servlets, however, is that they run in a container, and the APIs provide session and object life-cycle management. Consequently
9、, when you use servlets, you gain all the benefits from the Java platform, which include the sandbox (security), database access API via JDBC, and cross-platform portability of servlets. JavaServer Pages (JSP) The JSP technology-which abstracts servlets to a higher level-is an open, freely available
10、 specification developed by Sun Microsystems as an alternative to Microsofts Active Server Pages (ASP) technology, and a key component of the Java 2 Enterprise Edition (J2EE) specification. Many of the commercially available application servers (such as BEA WebLogic, IBM WebSphere, Live JRun, Orion,
11、 and so on) support JSP technology. How Do JSP Pages Work? A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is .jsp rather than .html or .htm, which tells the server that this page requires special handling that will be accomplished by
12、a server extension or a plug-in. When a JSP page is called, it will be compiled (by the JSP engine) into a Java servlet. At this point the servlet is handled by the servlet engine, just like any other servlet. The servlet engine then loads the servlet class (using a class loader) and executes it to
13、create dynamic HTML to be sent to the browser, as shown in Figure 1. The servlet creates any necessary object, and writes any object as a string to an output stream to the browser. The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed
14、, in which case it is automatically recompiled into a servlet and executed. 2. Best Practices In this section, I present best practices for servlets and particularly JSP pages. The emphasis on JSP best practices is simply because JSP pages seem to be more widely used (probably because JSP technology
15、 promotes the separation of presentation from content). One best practice that combines and integrates the use of servlets and JSP pages is the Model View Controller (MVC) design pattern, discussed later in this article. Dont overuse Java code in HTML pages: Putting all Java code directly in the JSP
16、 page is OK for very simple applications. But overusing this feature leads to spaghetti code that is not easy to read and understand. One way to minimize Java code in HTML pages is to write separate Java classes that perform the computations. Once these classes are tested, instances can be created.
17、Dont mix business logic with presentation: For advanced applications, and when more code is involved, its important not to mix business logic with front-end presentation in the same file. Separating business logic from presentation permits changes to either side without affecting the other. However,
18、 production JSP code should be limited to front-end presentation. So, how do you implement the business logic part? That is where JavaBeans technology comes into play. This technology is a portable, platform-independent component model that lets developers write components and reuse them everywhere.
19、 In the context of JSP pages, JavaBeans components contain business logic that returns data to a script on a JSP page, which in turn formats the data returned from the JavaBeans component for display by the browser. A JSP page uses a JavaBeans component by setting and getting the properties that it
20、provides. The benefits of using JavaBeans components to augment JSP pages are: a. Reusable components: Different applications will be able to reuse the components. b. Separation of business logic and presentation logic: You can change the way data is displayed without affecting business logic. In ot
21、her words, web page designers can focus on presentation and Java developers can focus on business logic. c. Protects your intellectual property by keeping source code secure. If you use Enterprise JavaBeans (EJBs) components with your application, the business logic should remain in the EJB componen
22、ts which provide life-cycle management, transaction support, and multi-client access to domain objects (Entity Beans). Please refer to the Enterprise BluePrints for further details on this. Use custom tags: Embedding bits of Java code (or scriptlets) in HTML documents may not be suitable for all HTM
23、L content developers, perhaps because they do not know the Java language and dont care to learn its syntax. While JavaBeans components can be used to encapsulate much of the Java code, using them in JSP pages still requires content developers to have some knowledge of Java syntax. JSP technology all
24、ows you to introduce new custom tags through the tag library facility. As a Java developer, you can extend JSP pages by introducing custom tags that can be deployed and used in an HTML-like syntax. Custom tags also allow you to provide better packaging by improving the separation between business lo
25、gic and presentation logic. In addition, they provide a means of customizing presentation where this cannot be done easily with JSTL. Some of the benefits of custom tags are: a. They can eliminate scriptlets in your JSP applications. Any necessary parameters to the tag can be passed as attributes or
26、 body content, and therefore no Java code is needed to initialize or set component properties. b. They have simpler syntax. Scriptlets are written in Java code, but custom tags can be used in an HTML-like syntax. c. They can improve the productivity of nonprogrammer content developers, by allowing t
27、hem to perform tasks that cannot be done with HTML. d. They are reusable. They save development and testing time. Scriptlets are not reusable, unless you call cut-and-paste “reuse“. In short, you can use custom tags to accomplish complex tasks the same way you use HTML to create a presentation. The
28、following programming guidelines are handy when writing custom tag libraries: a. Keep it simple: If a tag requires several attributes, try to break it up into several tags. b. Make it usable: Consult the users of the tags (HTML developers) to achieve a high degree of usability. c. Do not invent a pr
29、ogramming language in JSP pages: Do not develop custom tags that allow users to write explicit programs. d. Try not to re-invent the wheel: There are several JSP tag libraries available, such as the Jakarta Taglibs Project. Check to see if what you want is already available. Do not reinvent the whee
30、l: While custom tags provide a way to reuse valuable components, they still need to be created, tested, and debugged. In addition, developers often have to reinvent the wheel over and over again and the solutions may not be the most efficient. This is the problem that the JavaServer Pages Standard T
31、ag Library (JSTL) solves, by providing a set of reusable standard tags. JSTL defines a standard tag library that works the same everywhere, so you no longer have to iterate over collections using a scriptlet (or iteration tags from numerous vendors). The JSTL includes tags for looping, reading attri
32、butes without Java syntax, iterating over various data structures, evaluating expressions conditionally, setting attributes and scripting variables in a concise manner, and parsing XML documents. Use filters if necessary: One of the new features of JSP technology is filters. If you ever come across
33、a situation where you have several servlets or JSP pages that need to compress their content, you can write a single compression filter and apply it to all resources. In Java BluePrints, for example, filters are used to provide the SignOn. Use a portable security model: Most application servers prov
34、ide server- or vendor-specific security features that lock developers to a particular server. To maximize the portability of your enterprise application, use a portable web application security model. In the end, however, its all about tradeoffs. For example, if you have a predefined set of users, y
35、ou can manage them using form-based login or basic authentication. But if you need to create users dynamically, you need to use container-specific APIs to create and manage users. While container-specific APIs are not portable, you can overcome this with the Adapter design pattern. Use a database fo
36、r persistent information: You can implement sessions with an HttpSession object, which provides a simple and convenient mechanism to store information about users, and uses cookies to identify users. Use sessions for storing temporary information-so even if it gets lost, youll be able to sleep at ni
37、ght. (Session data is lost when the session expires or when the client changes browsers.) If you want to store persistent information, use a database, which is much safer and portable across browsers. Cache content: You should never dynamically regenerate content that doesnt change between requests.
38、 You can cache content on the client-side, proxy-side, or server-side. Use connection pooling: Id recommend using the JSTL for database access. But if you wish to write your own custom actions for database access, Id recommend you use a connection pool to efficiently share database connections betwe
39、en all requests. However, note that J2EE servers provide this under the covers. Cache results of database queries: If you want to cache database results, do not use the JDBCs ResultSet object as the cache object. This is tightly linked to a connection that conflicts with the connection pooling. Copy
40、 the data from a ResultSet into an application-specific bean such as Vector, or JDBCs RowSets. Adopt the new JSP XML syntax if necessary. This really depends on how XML-compliant you want your applications to be. There is a tradeoff here, however, because this makes the JSP more tool-friendly, but l
41、ess friendly to the developer. Read and apply the Enterprise BluePrints: Suns Enterprise BluePrints provide developers with guidelines, patterns, and sample applications, such as the Adventure Builder and Pet Store. Overall, the J2EE BluePrints provide best practices and a set of design patterns, wh
42、ich are proven solutions to recurring problems in building portable, robust, and scalable enterprise Java applications. 3. Integrating Servlets and JSP Pages The JSP specification presents two approaches for building web applications using JSP pages: JSP Model 1 and Model 2 architectures. These two
43、models differ in the location where the processing takes place. In Model 1 architecture, the JSP page is responsible for processing requests and sending back replies to clients. The Model 2 architecture, integrates the use of both servlets and JSP pages. In this mode, JSP pages are used for the pres
44、entation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page. The controller is also responsible for deciding to which JSP page to forward the request. The JSP page retrieves objects created by t
45、he servlet and extracts dynamic content for insertion within a template. This model promotes the use of the Model View Controller (MVC) architectural style design pattern. Note that several frameworks already exist that implement this useful design pattern, and that truly separate presentation from
46、content. The Apache Struts is a formalized framework for MVC. This framework is best used for complex applications where a single request or form submission can result in substantially different-looking results. Conclusion Best practices - which are proven solutions to recurring problems - lead to h
47、igher quality applications. This article presented several guidelines and best practices to follow when developing servlet- and JSP-based web applications. Keep an eye on servlets and JSP technologies, because several exciting things are in the works. JavaServer Faces (JFC), for example, a Java Comm
48、unity Process effort that aims to define a standard web application framework, will integrate nicely with Apache Struts. 译文 Servlets 和 JSP Pages 最佳实践经验 资料来源 : Oracle 杂志 作者: Qusay H.Mahmoud Java Servlet 技术和 JavaServer Pages(JSP)是主导服务 Java 技术市场的服务器端的技术,它们已经成为开发商业 Web 应用程序的标准。 Java 开发人员喜欢这些技术的原因有很多,包括:
49、这些技术是很容易学习的,编写一次,便可在任何平台上运行 Web 应用程序。更重要的是,如果有效地利用 servlets 和 JSP最佳实践, servlets 和 JSP 能将内容的生成和显示进行分离。使用 servlet 和 JSP来开发 Web 应用程序的最佳实践已经证明了自己的特点:开发优越,可重复利用,易于维护。例 如,在 HTML 文件中嵌入 Java 代码 ( scriptlets) 可能导致开发效率不够高,难以重复利用 , 难以增强和维护复杂的应用程序,而最佳实践可以改变这一切。 在这篇文章中,我将介绍 servlet 和 JSP 页面重要的最佳实践经验;假设你已经掌握了这两种技术的基本知识。这篇文章包括: 1 提供一个 Java servlet 和 JavaServer Pages( JSP 页面)概述; 2 提供使用 servlet 和 JSP 页面的提示、技巧和指导方针; 3 提供使用 servlet 和 JSP 页面的最佳实践经验; 1 Servlets 和 JSP 页面的概述 与通用网关接口 ( CGI) 脚本相似, servlets 支持编程模型的请求和响应。当一个客户端发送一个请求到服务器,服务器再发送请求给 servl