Problems and Solutions that plague JSP

Source: Internet
Author: User

Every developer who uses servlets now knows that JSP is a web technology invented by Sun and put a lot of effort into implementation and constructed on top of servlet technology. JSP disconnects the html code in the servlet, which can accelerate web application development and page maintenance. In fact, the official "Application Development Model" document published by Sun goes further: "JSP technology should be regarded as a standard, while servlets can be seen as a supplement in most cases. "(Section 1.9, views ).

The purpose of this article is to listen to the evaluation of the rationality of this statement-by comparing JSP and another technology based on servlets: template engines (template engine ).

Problems with using Servlets directly

At first, servlets was invented, and the whole world saw its superiority. Servlet-based dynamic web pages can be quickly executed, and can be easily transferred between multiple servers, and can be perfectly integrated with the background database. Servlets is widely accepted as a preferred web server platform.
However, the html code that can be implemented simply requires the programmer to call each line of HTML through out. println (), which becomes a serious problem in the actual servlet application. HTML content has to be implemented through code. It is a heavy and time-consuming task to ignore large HTML pages. In addition, the person in charge of webpage content has to ask the developer for all updates. To this end, people seek a better solution.

JSP!

JSP 0.90 appears. In this technology, you can embed Java code into HTML files, and the server will automatically create a servlet for the page. JSP is considered a simple way to write servlet. All HTML can be directly obtained without calling out. println (). The person in charge of page content can directly modify HTML without the risk of cracking Java code.
However, it is not ideal for webpage art designers and developers to work on the same file. It turns out that embedding Java in HTML is just as embarrassing as embedding HTML in Java. Reading a bunch of messy code is still a difficult task.

As a result, the use of jsp has become more mature, and more use of JavaBeans. Beans contain the business authorization code required by jsp. Most code in JSP can be extracted and put into bean, leaving only a few labels for calling bean.

Recently, people began to think that JSP pages in this way really look like views ). They are a component used to display the results of client requests. As a result, people may wonder, why not directly send requests to the view? What if the target view is not suitable for this request? In the end, many requests have multiple possibilities to obtain the view of results. For example, the same request may generate a successful page, a database Exception error report, or an error report without parameters. The same request may generate an English or Spanish page, depending on the locale of the client. Why must the client directly send the request to view? Why shouldn't the client send requests to some common server components and let the server decide the return of JSP view?

This allows many people to accept the design known as "Model 2", which is a model defined in JSP 0.92 Based on Model-view-controller. In this design, the request is sent to a servlet controller, which executes a commercial token and generates a similar data "model" for display. This data is then displayed by sending it to a JSP "view" internally, which looks like a common embedded JavaBean. You can select an appropriate JSP page for Display Based on the internal logic of the servlet to be controlled. In this way, the JSP file becomes a beautiful template view. This is another kind of development that has been promoted by other developers so far.

Enter Template Engines

The template engine is used to replace the common JSP. The subsequent design will be simpler, the syntax will be simpler, the error information will be easier to read, and the tools will be more customized. Some companies have already done such an engine, and the most famous is probably WebMacro (http://webmacro.org, from Semiotek) whose engine is free of charge.
Developers should understand that choosing a template engine to replace JSP provides such technical advantages, which is also some of the shortcomings of jsp:

Question #1: Java code is too templated

Although it is considered a poor design, JSP still tries to add Java code to the web page. Some of these seem to have been done in Java, that is, the simplified modification to C ++. template engines also simplifies it by moving the lower-layer source code in jsp. Template engines implements a better design.

Question #2: Java code is required

Some Java code is required on the JSP page. For example, assume that a page needs to determine the root context of the current web application and direct it to its homepage,
The following Java code is recommended in JSP:

<A href = "<% = request. getContextPath () %>/index.html"> Home page </a>
 
You can try to avoid Java code and use the <jsp: getProperty> flag, but this will give you six strings that are hard to read:

<A href = "<jsp: getProperty name =" request"
Property = "contextPath"/>/index.html "> HomePage </a>

Using template engine, there is no Java code or ugly syntax. Here is the same requirement in WebMacro:

<A href = "$ Request. ContextPath;/index.html"> Home page </a>

In WebMacro, ContextPath serves as an attribute of the $ Request variable and uses Perl-like syntax. Other er template engines use other syntax types.
  
Let's look at another example. Assume that an advanced "view" requires a cookie to record the default color configuration of the user. This task may only be completed by the view rather than the servlet controller. The following Java code should be available in JSP:

<% Cookie c = new Cookie ("colorscheme", "blue"); response. addCookie (c); %>

In WebMacro, there is no Java code:

# Set $ Cookie. colorscheme = "blue"

As the last ion, if you want to retrieve the color settings in the original cookie again. For JSP, we can think that there is also a corresponding tool class to help, because using getCookies () directly to do this lower layer will become ridiculous and difficult. In JSP:

<% String colorscheme = ServletUtils. getCookie (request, "colorscheme"); %>

In WebMacro, there is no need for tool classes. Generally, $ Cookie. colorscheme. Value. Which syntax is easier for the graphics artist who writes jsp?

JSP 1.1 introduces a custom tag (custom tags) that allows any HTML-Like tag to execute Java code in the background on the JSP page. This will be of some value, but the premise is to have a widely known, full-featured, free, standardized tag library. There is no such tag library.

Question #3: simple work is still tiring

Even a very simple job, such as header and footer, is still very difficult in JSP. Assume that a "header" and a "footer" template are included on all pages, and each template must contain the current page title in the content.
In JSP, the best solution is:
<% String title = "The Page Title"; %>
<% @ Include file = "/header. jsp" %>
... Your page content...
<% @ Include file = "/footer. jsp" %>

The page designer should remember not to omit the semicolon of the first line and define the title as a string. In addition,/header. jsp and/footer. jsp must be in the root directory and must be a complete file that can be accessed.
It is relatively simple to include headers and footers in WebMacro:

# Set $ title = "The Page Title"
# Parse "header. wm"
Your content here
# Parse "footer. wm"

There is no semicolon or title definition to remember for the designer. The. wm file can be placed in a customizable search path.

Question #4: A Rough Loop

It is difficult to loop in JSP. The name of each ISP object is repeatedly printed using JSP.
<%
Enumeration e = list. elements ();
While (e. hasMoreElements ()){
Out. print ("The next name is ");
Out. println (ISP) e. nextElement (). getName ());
Out. print ("<br> ");
}
%>

Maybe there will be user-defined tags for these loops. This is also true for "if. JSP pages may seem odd java code. At the same time, the webmacro cycle is very beautiful:
# Foreach $ isp in $ isps {
The next name is $ isp. Name <br>
}

If necessary, the # foreach command can be replaced easily by the custom # foreach-backwards command.

Jsp is likely to change like this: (here is a possible <foreach> MARK)

<Foreach item = "isp" list = "isps">
The next name is <jsp: getProperty name = "isp" property = "name"/> <br>
</Foreach>

The designer certainly chooses the former.
Question #5: useless error messages

JSP often has some surprising error messages. This is because the page is first converted into a servlet before compilation. Good JSP tools can increase the possibility of finding error locations, but even the best tools cannot make all error information easy to understand. Due to the conversion process, some errors may not be identified by tools at all.
For example, assume that the JSP page needs to create a general title for all pages. The following code is correct:

<% Static String title = "Global title"; %>

However, Tomcat provides the following error information:
Work/% 3A8080% 2F/JC_0002ejspJC_jsp_1.java: 70: Statement expected.
Static int count = 0;
^

This information assumes that the above script is put into the _ jspService () method, while static variables are not allowed in the method. This syntax should be <%! %>. It is difficult for page designers to understand the error information. Even the best platform is not doing enough in this regard. Even if all Java code is removed from the page, the problem cannot be solved. What are the following expressions?

<% Count %>
Tomcat provides:
Work/ 8080/_ 0002ftest_0002ejsptest_jsp_0.java: 56: Class count not found in
Type declaration.
Count
^
Work/ 8080/_ 0002ftest_0002ejsptest_jsp_0.java: 59: Invalid declaration.
Out. write ("\ r \ n ");
^

In other words, a tag is lost. It should be <% = count %>.

Since the template engine can be directly generated in the template file without any dramatic conversion to the Code, it is very easy to give appropriate error reports. And so on, when the C language command is injected into the Unix shell command line, you do not want the shell to generate a C program to run this command, the shell simply needs to explain the command and execute it. If there is an error, it will be given directly.

Question #6: A compiler is required.

JSP requires a compiler placed in webserver. Sun refused to discard the tools. jar library containing their javac compiler, which became problematic. The Web server can include a third-party compiler such as ibm jikes. However, such compilers cannot work smoothly on all platforms (written in C ++) and are not conducive to the establishment of pure Java web servers. JSP has a pre-compilation option that can play a role, although not perfect.

Question #7: waste of space

JSP consumes additional memory and hard disk space. For each 30 k jsp file on the server, a class file larger than 30 K must be generated. In fact, this doubles the hard disk space. Considering that JSP files can easily include a large data file through <% @ include> at any time, such attention is of great practical significance. At the same time, the file data of each JSP class must be loaded into the server's memory, which means that the server's memory must always save the entire JSP document tree. A few JVMs have the ability to remove file-like data from the memory. However, programmers generally cannot control such a rule to redeclare the data, and it may not be very effective for large sites to redeclare the data. No second file is generated for template engines, which saves space. Template engines also provides programmers with full control over the caching of templates in the memory.

There are also some problems with using template engine:

Question about Template #1: not strictly defined

How template engine works is not strictly defined. However, this is not very important for jsp. Unlike JSP, template engines has no special requirements on web servers-any server supporting servlet can support template engines (including API 2.0 servers such as Apache/JServ, which do not fully support JSP )! If a healthy competition is provided for the best template engine design, it can lead to a dazzling innovation, especially the promotion of open source code (which can push ideas and promote each other ), so today's WebMacro will be like Perl, without strict definition, but the promotion of open source code organizations is its standard.

Question about Template #2: Not recognized

Template engines is not widely known. JSP has occupied a huge commercial market and is deeply rooted in the hearts of the people. However, using g template engines is only an unknown alternative technology.

Question about Template #3: not ready yet

Template engines has not been highly tuned yet. No performance tests and comparisons were conducted for template engine and JSP. Theoretically, a well-deployed template engine implementation should match a well-deployed JSP. However, considering that the third party has made such a far-reaching push for jsp, as a result, only jsp is well configured.

JSP role

Of course, JSP will certainly have its position in the future. Even from the name, we can see that JSP and ASP are similar, they only have one letter difference. So if we want to turn asp users to java, a very similar jsp environment will play a great role in promoting this, the role of maintaining this relationship with asp should also be taken into account by the designers of jsp.
However, it is important to emphasize that the two are very different: the workers who are conducive to the new environment and whether they are actually the best way to use the environment.

JSP increasingly shows that it is becoming one of the most important java technologies, and it leaves people out of the ASP world-Sun will support this powerful commercial case, java-related technical support will also be given greater support.

However, this is not the best solution for the java platform. This will make the java solution seem to have no java solution.

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.