Results 1 to 6 of 6

Thread: Programming with JSPs

  1. #1
    Join Date
    Nov 2008
    Posts
    996

    Programming with JSPs

    Introduction: servers and servlet containers / JSPs

    Servlets and Java Server Pages (JSPs) are two methods for creating dynamic web server using the Java language. In that sense are similar to other methods or languages such as PHP, the CGI (common gateway interface), programs that generate web pages on the server, or ASP (Active Server Pages), a specific method of Microsoft. However, they differ from them in other things.

    For starters, JSPs and servlets running on a Java virtual machine, which allows, in principle, can be used on any computer, provided a Java virtual machine for him. Each servlet (or JSP, from now on we will use interchangeably) runs in its own thread, that is, in its own context, but do not begin to run each time it receives a request, but persists to a request to the next, so that no time is lost in putting it forward (loading program + interpreter). Their persistence also allows you to make a number of things more efficiently: database connection and session management, for example. The JSPs are actually servlets: a JSP is compiled to a Java program the first time it is called, and the Java program creates a class that begins to run on the server as a servlet. The main difference between servlets and JSPs is the approach to programming: a JSP is a Web page with special tags and embedded Java code, while a servlet is a program that receives requests and generates from them a web page.


    Both need a program that contains, and whatever it actually send web pages to the server, and receive petitions, circulated among the servlets, and perform all management tasks specific to a web server. While servers like Apache are specially designed for static web pages CGI, and programs implemented by the server, such as PHP, there are other specific servers for servlets and JSPs called servlet containers (servlet containers) or servlet engines. The main are:
    • Resin, Rubber Technologies , a unit specifically focused on the XML pages service with a free license for developers. It claims to be quite fast. Javascript also includes support for Java. It also includes a template language called XTP. It's pretty easy to install, and in two minutes, you can begin to serve JSP pages.
    • BEA Weblogic application server is a high-level and high price. It is written entirely in Java, and is combined with another series of products such as Tuxedo, a database server for XML.
    • JRun, Macromedia , a Java application server, mid-priced and probably average benefits. You can download a free trial
    • Enhydra lutris, another server Free and Open Source, although it has a paid version. Also focused to serve XML, and mobile platforms. The latest versions are extra, of course
    • The most popular, Open Source, and continually evolving, is the Jakarta Tomcat , Apache consortium, a servlet container around with many additional developments, such as Cocoon to serve XML pages. Can serve pages only or as an addition to the Apache server. Open Source is relatively fast, and easy to install. The current version is the 4.0.3 , but keep coming versions of the three.

  2. #2
    Join Date
    Nov 2008
    Posts
    996

    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

  3. #3
    Join Date
    Nov 2008
    Posts
    996

    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.

  4. #4
    Join Date
    Nov 2008
    Posts
    996

    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 ...

  5. #5
    Join Date
    Nov 2008
    Posts
    996

    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.

  6. #6
    Join Date
    Nov 2008
    Posts
    996
    Form Processing

    Enough of both implicit and so gaita object, we will go directly to the frosting process forms as God. We will try to make a JSP page to create and simultaneously process the form, in this way is easier to maintain. The form will allow us to fill the pool without doing anything concrete with her, only a request. In practice, there would probably be to store the results into a database, or at least one file, but for now, we'll leave it. To begin, we created a new bean containing an array of games, called Predictor, this bean will we use on the page is generally a good idea to reflect the structure of a page in a bean, or vice versa. In the former case we used the Party and PartidoValidado beans, and in this case we use it. The only peculiarity of this class is that, due to its structure as a Bean, you can not call any method with two arguments, so we have to establish a party cursor to indicate on which party will act the methods that are or class values extracted.

    The object that will contain the pool is declared on the front lines, using the tag <jsp:useBean>. Then, after opening the form, it detects if you have used one of the data on it (pronostico0), in which case it begins to process it: it creates a string with the name of the parameter (forecast + index) is uses that string to place the cursor ( %lt;jsp:setProperty name='Predictor' property='numParty' value="<%= i %>" /> ) and assign the forecast to the corresponding game of pool.

    The code can be improved somewhat, avoiding mistakes in putting checkboxes origin (ie, squares on which you can click) instead of entering through the keyboard. That does not mean you have to delete the error correction code, because you can always hand edit the request to the server. Simply, it avoids problems to the user. The truqui of the matter is the principle: instead of using getParameter to get a single parameter is used getParameterValues , which returns an array with all values which have a parameter in this case, each group of three buttons uses the same name form element, so each parameter will have little buttons that many elements have been completed. In any case, stick to the parameters in a single string, which is used to assign a value to the forecast.

    As to form, in this case we have to use the forecast as an array of Boolean values (instead of a string as we did before) because it suits us more time to put the default to the buttons. We also use a Java class method to move from a rate of 0-2 the symbol (1, X 2). But of course, the interesting thing is not just submit the form data, but add on statistics for the entire office (and on the way, teasing the showing her prognosis does not share one) and presented in a graph.

    There are four different areas in the variables used in JSPs and servlets:
    • page level: objects which are only accessible during the execution of the code of a page
    • request: shared objects between the different pages that handle a request, for example, a page and to handle errors of the first, or a page and another that is passed with the command control jsp:forward
    • meeting; shared objects between the different pages that are called through a session, and finally
    • application, shared by all objects within the server

    This last area is what we use just on this page. To understand, would be a kind of persistent objects, which will stay there until you reboot the server.

    The news of this new file start soon: in the first line. The graphics is not something that can be done with JSPs and, to hair, so we use a tag library, a tag library. In this case it is the library BarChart, a taglib to make graphs of horizontal and vertical bars. Installation is easy: it takes two files: the java class file, .jar , and a description of the labels and their correspondence with methods and classes .tld . Each of these files usually go to a different site: the first to WEB-INF/lib and the second WEB-INF/tlds.

    The taglibs are simply a change of interface with respect to the normal Java code, save you insert code within the pages, and are generally easier to maintain, because in the OO style, encapsulate your logic and that the use does not have to worry about how to do what they do, just to access them. There are many free, and there are collections such as that of JSPin. In this case we have complicated life and have put the file directly in the same directory as the corresponding JSP file, it'll mark with uri="bartag.jar" ; also have to define the prefix (actually, the space name) that we use to refer to the taglib: in this case prefix="bar" indicates that the prefix will be bar (bar).

Similar Threads

  1. What does DOM mean in programming?
    By Gadin in forum Software Development
    Replies: 5
    Last Post: 11-03-2010, 05:33 PM
  2. Xml with C# in .NET programming
    By Remedy in forum Software Development
    Replies: 4
    Last Post: 03-03-2010, 08:10 PM
  3. Socket programming: Is any new Programming Language?
    By Kushan in forum Software Development
    Replies: 3
    Last Post: 14-11-2009, 11:13 AM
  4. Programming - Mat
    By garfield1 in forum Software Development
    Replies: 7
    Last Post: 02-02-2009, 11:09 PM
  5. Replies: 3
    Last Post: 13-12-2008, 01:49 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,419,513.11765 seconds with 17 queries