Re: Programming with JSPs
Installing a servlet container :
Let's see how to install a servlet container. We will look especially at the Tomcat version 4.0, although counts as valid for most other open source containers. The payment will probably have to install a posh interface, based on little buttons, or are very expensive, there will come a man with a tie and leather case for it, so that those we do not care.
Before I ever get off the program in question, one must consider in advance the Java virtual machine that we use to execute it. All are written in Java, so this is essential. Primarily, there are two options: the Sun JVM (who are the original) or IBM, which are somewhat faster but not always updated to the latest version. A servlet container you need the full JDK, not just the runtime environment, mainly by the Java compiler contained in a file called tools.jar. In any case, we can download the Sun JVM versions for Linux , or for any other platform (version 1.4) or version 1.3 of IBM (the most advisable) . Failure to achieve a version of these, it is advisable to get one that is compatible with the version "2" of Java, ie JVMs from version 1.2. They may work with earlier versions, but most likely do not. Just Java is already installed in the system will verify that java and tools.jar are also installed, just try to run it, or ask your system administrator, who is also a creature of the breast and is entitled to direct someone the word, man.
After installing the JVM, we got the server for your site, if possible, in binary version, and compiled. If you have a Linux distro that uses RPM to install packages (like Mandrake, RedHat or SuSE), one may download the RPMs and install them directly. Depending on what you choose, will have to download only one package, or several. In any event, will include the following: Xerces-J, regexp, servletapi, tomcat-webapps and tomcat. If we lower the file. Tar.gz, is all inclusive. To install the RPM does the following:
Code:
[yo@mimaquina]$ rpm -Uvh tomcat4-4.0.2-3.noarch.rpm
This after having installed all the previous packages. If you have downloaded the tar:
Code:
[yo@mimaquina]$ tar xvfz tomcat4-4.0.2.tar.gz
Already unpacked, we will be ready to run Tomcat. Depending on how coding, we have the server in a directory or another, but there will always be directories conf, lib, bin and webapps. It is then necessary to say where is the Java virtual machine, tomcat.conf editing a file that is located in the conf directory (which will vary according to the distribution site, may be in / etc/tomcat4/conf or directory_del_tomcat / conf .) In other operating systems, or other type of installation, we must define an environment variable, like this:
Code:
[yo@mimaquina]$ export JAVA_HOME=/opt/IBMJava2-13
or
Code:
[yo@mimaquina]$ setenv JAVA_HOME /opt/IBMJava2-13
Re: Programming with JSPs
Depending on whether it is the bash shell (the first) or * csh (the second). In WinXX must be given a similar order. Finally to run the server, paying attention to the case it is installed using the RPM, do:
Code:
[yo@mimaquina yo]$ /etc/rc.d/init.d/tomcat4 start
In other cases, it will go to the bin directory of the distribution and run ./startup.sh or startup if it is Windows. By default, the server is configured to launch on port 8080 or 8180 (depending on the version). If all went well, we operate on our computer to Tomcat, and entering a URL such as http://localhost:8080 or http://localhost:8180 (if you want to use addresses below 1000 will have to be root).
er is working effectively. The main problem is that it fails silently Tomcat: running things, and seems to have started, but, however, has not done so. To see if you are working you have different choices: Use netstat to see if the port is busy and someone is listening to it (and if the Tomcat, the better, if not, why has failed because it has not been able to occupy the port ), listen carefully to see if your hard disk to start the tomcat has given vidilla, which indicates that you are actually working, look to see if there is something in the webapps directory, because if there is not, going to failure context or something, how easy it is, joer, there is no damn page, my!. It is also interesting to try to run the examples: if fail servlets JSPs but is not found the tools.jar file, which, despite its name, which compiles the JSPs. Finally, we should look in the catalina log in log / catalina_log. [Date]. Txt and if it has started correctly, something like this:
Code:
3/11/2002 8:33:13 HttpConnector Opening server socket on all available IP addresses 11/03/2002 8:33:15 HttpConnector [10001] Starting thread to post HttpProcessor 3/11/2002 8:33:15 [10001] [0] Starting thread back
If you just put the first message, crappy, it has not initiated any strand, which are actually serving the JSPs. If there's nothing like that, look for error messages in the log subdirectory, sometimes indicate that some file missing or While there is a problem of versions of the Java virtual machine.
Once installed, and has been proven to work correctly, you can try changing your setting, especially considering the number of visitors expected. Most configuration changes are made on the conf / server.xml. To change the port that is heard and the number of available servers minimum and maximum, we must change the following order:
Code:
<Connector className="org.apache.catalina.connector.http.HttpConnector" port=" 10001 "minProcessors=" 2 " maxProcessors=" 5 " enableLookups="true" redirectPort="8543" acceptCount="10" debug="0" connectionTimeout="60000"/>
The Tomcat configuration is done on a file that uses XML. With it, identifies a number of components: servers, connectors and containers, the configuration is greatly simplified since the previous version, but introduces new elements: the valves and motors. Tomcat for each server defines a set of connectors, whereby different classes respond to different ports, and are responsible for serving, the containers or engines are within the connectors, and are responsible for handling all requests for service. Unless to be used for particular applications (such as Cocoon), do not worry much about it. In some case, you just have to change the minimum number of processors (or threads serving requests) and the maximum, not to overburden the system if they have limited main memory. The bottom line is 2, and the maximum is up to 65535, or until the memory hold (which will not last long). As for the port, you can use any, if not already used, and always run from root, if you are not root, you use ports over a thousand. Once done, you have to reboot the server to take the new changes:
Code:
[yo@mimaquina yo]$ /etc/rc.d/init.d/tomcat4 restart
To save resources, you can delete stuff from that file. For example, if it is a development server, no need for apache connectors or connections using SSL. You can drop the service, Apache Tomcat, removing everything from the label and back label Service. You can also eliminate the AJP connectors, SSL, "proxied", and test, indicated with a comment, just below the normal connector (non-SSL HTTP/1.1). You can save a few more resources by starting the JVM in a way that limits the size of the heap and the stack, but do not save too much space. A running Tomcat not take never less than 90 megs (which you can see the top or gtop running either from the command line, ps-exfua. You can also add a new context to the server, especially if we want our applications do not mix with the other applications in the context root (those in the ROOT directory. This may be added, just after the line which defines this context, the following:
Code:
<Context path="/micontexto" docBase="micontexto" debug="0"/>
Once the application can be hosted on a server that offers this service. For example, Verio offers solutions based on the Solaris operating system (the price should be consulted). There are also free alternatives, though not eternal as in the case of GeoCities. One is iSavvix Devspace , which allows free hosting JSPs with tag libraries and even XSLT, what does not, is that you upload their own classes, although you can use different class libraries on the site. Alternatively, WebAppCabaret , which gives several alternative servlet container: Tomcat and NGASI, Enterprise Java Beans, MySQL databases, but all this for only 15 days beyond that, you need to recruit the premium service, from $ 3. Finally, MyCGIserver also allows free hosting, you have to answer a question related to servlets, but it is usually easy to find the answer.
Re: Programming with JSPs
Our first JSP page
If all goes well, and the examples are implemented correctly, and is a ready to create your first program, or page in JSP (depends on how one looks at it). Because JSP pages are basically HTML pages with a bit of Java through serving, theoretically, any editor that understands HTML syntax and / or XML, for example, XEmacs . Some other settings, such as Sun ONE, a comprehensive development platform (which consumes a lot of resources), the Visual Age for Java , these two are written in Java and can run on any platform. The Dreanweaver Ultradev , however, exists only in Windows version. Forte is free, and the other two are extra, although there are versions of time-limited trial can be downloaded. With any text editor can create the first JSP page :
Code:
<! - (C) JJ -> <% @ page language = "java" contentType = "text / html"%> <%! int count = 0;%> Hello <title> <head> <html> and numbers. Intro to JSP </ title> </ head> <body bgcolor="white"> Hello world. I repeat <% = count + +%> <% if (count == 1) (%> after <%) else (%> times <%)%> </ body> </ html>
After editing the page, should be put somewhere. The Tomcat directory structure (and other servlet container) is a bit more complex than the normal web server. All files hanging from the webapps directory, but can not be placed directly there. In that directory descend subdirectories, where applications are placed effectively. Each directory corresponds to a context, ROOT is a root context and so many other contexts as you want defined. Within each context, the directory structure is also always the same, directly descending from the directory can put the JSPs, and there is a WEB-INF directory where there are a number of configuration files and properties, and also other directories: classes and lib (not shown in this picture). In those directories the files will later. And class. Jar, respectively. Therefore, the previous file, will go to the ROOT directory (or the directory of the particular context that we defined in the previous year). Can also be placed in any of the subdirectories in the webapps, but not in the main.
The file contains most of the elements of a JSP. To begin, line 2: <% @ page language = "java" contentType = "text / html"%> includes a directive, which are commands that run before it starts processing the JSP, and modify somewhat the result. All JSP directives are indicated with an @ after the beginning of the order JSP (<%). In this case, we show that the page you are going to run is in Java, and that will generate content type is text / html; the standard JSP, despite its name, is not limited to a single language, although in practice it almost always uses Java and JavaScript in some cases. In terms of content, JSP works, by default, with HTML, but could generate pages on other standards such as WML used on mobile WAP, or XML. The page directive can include other attributes:
Code:
<% @ Page language = "java" contentType = "text / html" info = 'My first page in JSP "import =" java.util .* "errorPage =' error.jsp '%>
info is a kind of comment that the container used to describe the class as a management interface; import lets you specify a set of Java packages to import, and indicates errorPage page you have to jump in the event that is generated exception. Right now, none of these attributes are necessary, and indeed, the page works perfectly well without them, in which case, take the default values, ie for the page HTML and Java scriptlets.
Just then the line <%! int count = 1;%> is a statement, the bang (!) is used to indicate global variable declarations, ie persistent variables between calls the JSP, and is shared by all calls to a page. The statement will execute the first time you call the page, and re-run every time you recompile the page (or restart the server), the effect of this declaration will be a hit counter, which will increase each time you visit. Moreover, the declaration is a normal statement in Java, you can include as many statements as you want, not necessarily at the top of the page.
Then come a series of HTML elements to the line 7, where the order <% = count + +%>. Everything begins with <% = is a JSP expression, the effect is to evaluate expression and print the result. In this case, it runs the expression and then print the value, which is what the post-increment operator + +. The expressions in JSP Java can contain only expressions that return a value, and need not be completed with, as in the case of statements.
Below is a combination of Java code and text items commonly referred scriptlet. The scriptlets using normal JSP syntax, <% and%>, and inside you can include any piece of Java program you want. In this case it is an if statement, and the only thing relevant is that Java code mixed with the text, in this case, conditionally include text or other in the checkout page. It could be done using Java only, thus
Code:
<% if (count == 2) System.out.println('vez') } else { System.out.println('veces') } %>
However, in this way, you can easily include all sorts of HTML structures without the need to put lots of System.out. What the count == 2 is because when he gets there the first time the program is running, the counter and counts two, because it has increased in the last line.
(Although in the RPM for version 4.0.2 is not working properly, I think ...). If all goes well, it creates a file test.java that would be the one, compiled, the servlet would, in fact, this file could be compiled and made as a servlet. This compilation is not necessary, but if we are working with a big file and we have no very clear if the syntax is correct, you can use, although in most cases, will swallow it whole and let the engine catching errors . In fact, I failed to give an error, many things that I've done ...
Re: Programming with JSPs
Additional elements of the JSP Beans.
To begin, let's just riding a JSP to present the result of a match, a result that will also include within the page (resultado0.jsp , and in action in iSavvix).
The JSP is a bit long, especially for embedded Java code. This code creates a class called party, comprising the two teams playing at home and abroad, and prognosis. The forecast is defined as an array of 3 booleans, one for each possible outcome, 1, X 2 (home team win, draw or win from outside). The forecasts can be combined (multiple bets are called), so that a possible outcome of a match can be X, 12 or even 1X2. The class consists of three pairs of methods, to set the value (set) of a variable, and to return (get) the value of it. It then creates an instance of the class by calling new, the object Part1 contain the value of the variable, and share all calls to JSP. Not that sharing be of much use, but we stopped that. A few lines later using the jsp: include, our first label JSP. It is a specific order of JSP on the server, before the creation of response that is sent to the customer, will be implemented, including, in this case, a JSP file (or HTML). If this is a JSP file, this file, in turn, shall be construed and include results on the page. This can also be done as follows:
Code:
<%@ import file='cabecera.jsp' >
with the difference that in this case, first include the contents of the file and then interpreted. import is a compile-time directive, while jsp: include works at runtime. In this case, it includes a small header common to all exercises, the same way that at the end of the file, it includes a caption, which closes the HTML file and the font changes. The following scriptlet sets the values of the variables by calling the methods set, and then recover within a table, using the getters and the result of the boolean array returned getPronostico have to reformat to become 1X2.
Indeed, for what we did, we could have saved so much class and so both JSP and bagpipes, but serves to introduce a concept that is terribly useful in the world of JSP: the beans or beans . The beans are defined by a standard Sun, and have some complexity, but from the point of view of the JSPs are simply classes in which the variables can be accessed by methods set (to change its value) and get to recover their value , the set methods are called with one argument of the same type as the instance variable and get methods return an object type of the instance variable, without taking any arguments. Not all set methods must correspond to an instance variable, nor do the get, but all methods that return a value must have this structure, like all that alter a value. The class above is a Bean Party, as is the following, slightly enlarged.
Before this work, you have to compile the bean and put it in their correct places. In this case we must place it in the subdirectory WEB-INF/classes/football, the first two parts correspond to the way in which we must put all. Class, and pool is the name of the package in which we put our class Party. All compiled classes in this package will have to go to that directory. The JARs will also go into its corresponding directory and other files which are not intended directly to serve the public. The JSP uses the compile-time command above to import the bean within the context of the page. Subsequently declares a bean named estePartido by jsp: useBean. This tag creates a bean of a particular class, is equivalent to calling new on Java. The properties of this bean (the variables accessible through get and set) will be used by methods jsp: getProperty and jsp: getProperty, ie <jsp: setProperty name = "Party1" property = "playingathome" value = "Madrid "/> is equivalent to Party1.playingathome ("Madrid"). The attribute property includes the property that will be accessible, that property becomes the first letter is capitalized and prefixed with get or set method to find the class to which to call. The following lines set the values of the three properties of the bean. Subsequently, print the values returned by these properties. Only have to look a bit on the property formatted in reality, is a method call without correspondence to any instance variable, the JSP that gives the same, and calls the corresponding method.
Dynamic pages.
As for static pages, we have the HTML itself, going to get a bit of dynamism in the pages, allowing them to modify the page, depending on how you call it. Later we will see how to make the user enter the data directly. In this case, we, as in the examples above, jsp: setProperty, but now we assign values to all properties at the same time borrowing from the arguments with which the JSP is called. Variable = value & variable = value, and so on. It is the normal syntax to pass values to programs running on the server, such as JSPs. The result can be seen in the image. By using the parameters passed to the JSP, we are actually using a JSP implicit object, the request object, an instance of the javax.servlet.http.HttpServletRequest class, just as is used in servlets (and is, in fact, are treated the same).
Here we are using the implicit request object by calling its getParameter method to get the value of call parameter AsString. This object has the same methods as the equivalent of servlets, so we did not extend him the most. The most useful are the previous getParameterValues getParameterNames and others, such as getCookies will be used to obtain client cookies. In this case, they are in different output channels depending on the value of the forecast, if multiple results are not included at all. There are other implicit objects, probably the most used are Session, which handles the session variables and application, with methods related to the context where you are running the servlet which is responsible for the JSP.
With respect to the previous version have been added a series of checks that are too long, too small, or if there is any character other than 1X2. Capture the exception in a Java program is easy (with the try and catch). For this error message used to be called if an exception has occurred, is more or less logical that the exceptions are not treated within the same page, because in some cases may occur even before that the code has been generated. The most important thing is the first line: the page is declared herself as a page that responds to errors, which allows you to create the exception implicit object. This object is used later to print the message that has been produced (though not always work). Also recovered an attribute of the implicit request object, which had been put to the page the error occurred, so that people know where it comes from the error.