Getting Starting with JSP with Examples. Introduction. Java. Server Page (JSP) is Java's answer to the popular Microsoft's Active Server Pages (ASP). JSP, like ASP, provides a simplified and fast mean to generate dynamic web contents. It allows you to mix static HTML with dynamically generated HTML - in the way that the business logic and the presentation are well separated. JSTL Tutorial with examples on JSTL core tags, function tags, formatting tags, sql tags and miscellaneous tags. It includes c:out, c:import, c:set, c:if, c:when, c. Servlets First Examples - Learning Java Servlets in simple and easy steps using this beginner's tutorial containing basic to advanced knowledge of Java Servlet. JSP Tutorial for Beginners - Learn JSP in simple and easy steps starting from basic to advanced concepts with examples including Java JSP Technology including Form. JSP tutorial for beginners with examples in eclipse. JSP tutorial with examples. Learn java sample examples programs with output for beginners and experienced. Learn java tutorial with explanation online step by step in eclipse. A knowledgebase on JSP with a comprehensive collection of JSP tutorials, JSP sample code and articles on JSP. The advantages of JSP are: Separation of static and dynamic contents: JSP enables the separation of static contents from dynamic contents. This greatly simplifies the creation and maintenance of web contents. Reuse of components and tag libraries: The dynamic contents can be provided by reusable components such as Java. Bean, Enterprise Java. Bean (EJB) and tag libraries - you do not have to re- inventing the wheels. Java's power and portability. JSPs are Internally Compiled into Java Servlets. That is to say, anything that can be done using JSPs can also be accomplished using Java servlets. However, it is important to note that servlets and JSPs are complementary technologies, NOT replacement of each other. Servlet can be viewed as . JSP, on the other hand, is . In a typical Model- View- Control (MVC) application, servlets are often used for the Controller (C), which involves complex programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The Model (M) is usually implemented using Java. Bean or EJB. Apache Tomcat Server. JSPs, like servlets, are server- side programs run inside a HTTP server. To support JSP/servlet, a Java- capable HTTP server is required. Tomcat Server (@ http: //tomcat. RI) for Java servlet and JSP, provided free by Apache (@ http: //www. First JSP Example - . We shall use the webapp called . It should be either of the followings depending on the random number generated. The Java statements are enclosed by < % .. This is used in the anchor tag < a> for refreshing the page to obtain another random number. Behind the Scene. When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet, and execute the servlet. Check out the generated servlet for . Hence, the expression will be evaluated, and the result of the evaluation written out as part of the response message. Compare the JSP script and the internally generated servlet, you shall understand that servlet is . The service() methods takes two arguments: request and response, corresponding to the HTTP request and response messages respectively. A Print. Writer called out is created for writing out the response to the network. You have to hardcode all the HTML tags (and cannot use any WYSIWYG web authoring tools). Any change to the web page's presentation (such as background color and font size) requires re- coding and re- compilation of servlet program. Servlet, in a nutshell, is . Once the client fills in the form (by checking the boxes) and submits the form, . The values are echoed back using an unordered list. JSP Scripting Elements. JSP provides the following scripting elements: JSP Comment < %- - comments - -> JSP Expression < %= Java Expression %> JSP Scriptlet < % Java Statement(s) %> JSP Directive < %@ page. For example. < %- - anything but a closing tag here will be ignored - -> Note that HTML comment is < !- - comments - ->. JSP expression within the HTML comment will be evaluated. For example. < !- - HTML comments here < %= Math. JSP Expression < %= Java Expression %> JSP Expression can be used to insert a single Java expression directly into the response message. This expression will be placed inside a out. Hence, the expression will be evaluated and printed out as part of the response message. For examples. < p> The square root of 5 is < %= Math. For examples. < p> You have choose author < %= request. Parameter(. JSP scriptlets let you insert an arbitrary sequence of valid Java statement(s) into the service() method of the converted servlet. All the Java statements in a scriptlet are to be terminated with a semi- colon. For example: < %. String author = request. Parameter(. The HTML codes are passed to an out. JSP Directive < %@ page. The syntax of the JSP directive is. For examples. < %@ page import=. You can include any JSP files, or static HTML files. You can use include directive to include navigation bar, copyright statement, logo, etc. The syntax is. < %@ include file=. The processing script is contained in the same page. The method request. Parameter(. The steps are. Establish a database connection via a java. Connection object; Allocate a java. Statement object under the Connection; Prepare a SQL SELECT string; Execute the SQL SELECT using execute. Query() method. The result of query is returned in an object of java. Result. Set; Process the Result. Set row by row via Result. Set. next(); Free resources and close the Connection. The query result is tabulated in a HTML table. Note the mixing of HTML and Java in producing the table. Notice that JSP carries out the presentation much better and neater than servlet. The presentation can be changed easily with JSP. The JSP pages can be created and modified using a WYSIWYG web authoring tool and reload to see the effect on the presentation. Prentice Hall. Java Database Connectivity (JDBC) @ http: //java. While Java servlet technology focuses on Java classes capable of generating HTML output with Print. Writer. println() statements, JSP technology abstracts this concept to a higher level. With Java. Server Pages, a Web developer can write static HTML pages and simply add Java code in those sections of the page that need to be dynamically generated. While this flexibility enables rapid development of simple Web applications, it can be abused, resulting in unnecessarily complex applications that are difficult to maintain, reuse, and enhance. To avoid needlessly complex applications, follow the practices I present in this article: Separate HTML from Java. Place business logic in Java. Beans. Factor general behavior out of custom tag handler classes. Favor HTML in Java handler classes over Java in JSPs. Use an appropriate inclusion mechanism. Use a JSP template mechanism. Use stylesheets. Use the MVC pattern. Use available custom tag libraries. Determine the appropriate level of XML compliance. Use JSP comments in most cases. Follow HTML best practices. Utilize the JSP exception mechanism. These tips will help you write JSPs that are reusable and easy to maintain. Separate HTML from Java. It can be tempting to throw all Java and HTML code necessary for a Webpage into a single JSP file. In simple system development, such an approach makes it easy for someone new to the system to locate all relevant code in one place and understand how it all interacts. However, this approach becomes burdensome and costly when the application grows more complex and more developers become involved. Combining HTML and Java in the same source code can make the code significantly less readable. To enhance software readability, developers often use indentation; but mixing HTML and Java scriptlets in the same file can make useful indentation extremely difficult to maintain. Many Web development methodologies and architectures now emphasize the separation of HTML from Java code so different developers can focus on their strengths. Properly separating Java and HTML, including HTML- like JSP tags and custom tags, allows Web designers and HTML coders to work on the HTML (presentation) aspects, while Java developers work on the application's Java (processing logic) portions. Java developers focus on business logic as they implement the behavior behind the custom tags; Web designers then use these custom tags just as they use ordinary HTML tags. Applications with Java properly separated from HTML are more reusable because the Java components are not tied to a Web browser and can be used by other parts of the application. In addition, maintainability is enhanced because of the increased modularization that comes from Java/HTML separation. Placing business logic in Java. Beans also promotes stronger applications. I'll explain how next. Place business logic in Java. Beans. Java code included directly inside a JSP is not as readily accessible to other JSPs as Java code contained within a Java. Bean. Common behavior and business logic placed in Java. Beans can not only be used by other JSPs but also by other portions of the application. That is because Java. Beans are merely Java classes that satisfy some basic conventions (such as a constructor with no arguments and public get/set methods for private data members) and can be used as any other Java class. Note that Enterprise Java. Beans (EJBs) are also useful for storing behaviors and data common to all components of the application. Factor general behavior out of custom tag handler classes. Java classes known as custom tag handlers implement custom tags. Unlike Java. Beans, custom tag handler classes are not readily used like ordinary Java utility classes. Instead, custom tag handler classes implement specific interfaces - - or extend classes that provide these interfaces' basic implementations. Because they are not readily reused outside JSPs, custom tag handlers should contain only specific behavior that would not be useful outside that custom tag - - that is, outside the JSP. Custom tags often require support for common behaviors or business logic and can utilize Java. Beans or EJBs that perform those common behaviors. Favor HTML in Java handler classes over Java in JSPs. Sometimes cleanly separating HTML, JSP tags, and HTML- like custom tags from Java requires unnecessarily convoluted code. In these cases, you either include Java scriptlets and expressions in the JSP or put some HTML code in the Java tag handler class. I'd rather see a small amount of HTML code in the Java class than see Java, such as scriptlets and expressions, in the JSP. Since custom tag handlers are specific to the custom tags they implement (and not reusable outside JSPs), placing necessary HTML there is not troublesome. Sun's Java 2 Platform, Enterprise Edition (J2. EE) Blueprints documentation discusses this issue further. There are exceptions to this standard: if including one or two lines of Java code as scriptlets in the JSP solves the same problem that would require many more lines of HTML in the Java handler class, allowing Java code to exist in the JSP page might be prudent. Use an appropriate inclusion mechanism. It is rarely good design to reproduce code commonly used by different application pieces each time another piece of that application needs that functionality. Factoring common JSP or HTML code out of multiple pages and into a single file improves maintainability (you need to make changes in only one location) and reusability. Two JSP include mechanisms reduce code redundancy and promote reusability; to ensure that you use the appropriate include mechanism, it is important to know the differences between the two. Generally, I use the include directive unless I can justify a need for the include action. Question 7 in the Blueprints' . Use the include mechanism for situations when text, such as ASCII or HTML, needs to be included in multiple JSPs. For example, I commonly use the include directive to include footer information, such as company name or copyright date, on every JSP in a company's application. Since you include the content of any file specified by the include directive in the calling JSP before it compiles, variables and other values specified in the calling JSP can also be utilized in the included content. However, I try not to rely on variables defined in the calling JSP, since this dependency reduces the included file's reusability. Include action. The include action executes the specified JSP first and then places the generated response in the calling JSP. Because the include action includes the generated response rather than the source content itself, variables and other values specified in the calling JSP are not available to the page included with the include action. One disadvantage of the include action as currently implemented by the JSP implementations with which I am familiar relates to the flush=. In the JSP implementations I have used, this attribute is required and must be set to true. The true value indicates that the buffer will always flush before a target page specified by the include action executes. This can prove problematic if the forward mechanism is invoked either explicitly or implicitly later in the JSP. In the recently released JSP specification (1. Tomcat 4. 0 provides a reference implementation of this specification and supports this new include action argument. Use a JSP template mechanism. A template mechanism allows for a common file to control Webpage, or JSP, layout. Then, when you want to change the layout, you need to modify only one file, and all the other pages will reflect the layout change. This doesn't just make for more maintainable code; using templates to control layout also makes Webpages more aesthetically pleasing to users who see consistent layouts for all an application's pages. I use Struts' custom tag template library as a template mechanism. David Geary's article . I use Cascading Style Sheets (CSS) to control such items as font families, font sizes, and table characteristics. Like templates, stylesheets allow the developer to make changes in one location; those changes immediately reflect on all appropriate pages, resulting in increased maintainability and consistent appearance to users. Use the MVC pattern. While other design patterns can be used effectively with JSPs, I often use the Model- View- Controller (MVC) architecture with JSP technology. MVC enables the development of applications that are easier to create, test, maintain, and enhance. In JSP terminology, implementation of an MVC architecture is often referred to as Model 2 (from an early JSP specification). The J2. EE Blueprints samples are based on MVC. See . The base controller is implemented as a Java servlet, and its configuration is controlled by an XML file called struts- config. When a Struts- based JSP Web application is created correctly, most changes in flow control are made in the struts- config. Implementing an application that is MVC- compliant involves extra initial effort, but the investment in time up front is worth the rewards of more maintainable and reusable code. Plus, Struts significantly reduces the preliminary work involved in implementing MVC. Besides supporting MVC implementations, Struts also provides some valuable custom tag libraries, such as the template tag library mentioned previously. The logic tag library has custom tags for iteration and tags for if- then- else structures. The HTML tag library features many useful custom tags, including custom tags for FORM tags and form item tags used in Struts' form handling and validation. See the Struts documentation for more details on these libraries and other Struts custom tag libraries. I'll discuss the advantages of using these libraries next. Use available custom tag libraries. Why should developers spend time reinventing the wheel and worrying about testing and debugging when custom tag libraries are readily available for many different purposes?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
September 2017
Categories |