Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java: Servlets, the basics.

servlet

  • Please log in to reply
4 replies to this topic

#1 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 13 August 2011 - 03:43 AM

Notes:
Click images for a bigger view
I marked this as 'advanced'. Not because there's difficult coding going on here, but since I believe you should know Java well before jumping onto web projects.
At the bottom of this tutorial are a few files to download: 1 library (.jar) you need, and 2 zip files. 1 with the base file structure, 1 with the final project. If you can't use .zip and need a .tar. Please post a reply.
Servlets
What is a Servlet?
A servlet can be compared to a .php file for php and a .asp file for .NET. It can execute Java code and/or as well render an HTML page for the user to see.
You will however not so often use Servlets to render HTML pages, that’s often done with the help of a JSP or JSF file.
But when you compile these, in the background these will be transformed in a Servlet anyway. Using a JSP or JSF file just allows the developer for easier writing of HTML pages since you don’t have to mess with actual Java code in those.
So basically a Servlet is a piece of Java code that you can execute which is also accessible by browsing to a certain URL. You can call it a web service if you want to.

Setup
First of all, this is a Java Web Project. If your IDE supports it, go ahead and create a new Java Web Project instead of a regular Java project.
You don’t need an IDE which supports it, it just helps you on building the structure of a web project. For those with no web project support, or no IDE at all, create the following structure.
start_folder_structure.png
This is the base structure for most web projects. Java code and classes go in the src folder. web contains server configuration files, resources, and HTML/JSP/JSF/whatever pages.
As of yet, the web.xml file is “empty”. Well actually it isn’t, it contains some namespaces and has an empty <web-app> tag.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5"> 
  
</web-app>
This file contains configuration data for your webserver. Yes you will be running a webserver by the end of this tutorial.(I will be using Tomcat, if you prefer JBoss, or a Glassfish server. Go ahead, those will work too.)
Configuration could be: setting a default error page to show instead of displaying the stacktrace, setting the welcome page, security,... and mapping Servlets of course. More on that later.

Now there’s 1 more thing before we can go create our servlet. You will need a library which is not in the default Java JDK. At the bottom of this tutorial you can download this (javax.servlet.jar) This library is part of the Java Enterprise Edition.

In IntelliJ you can add a library by going to File>Project Structure. Click libraries on the left. Click the ‘+’ sign. Give it a name. click “Attach Classes…” Browse to the .jar file, and add it. Apply> ok. Done.
(If you actually have the IntelliJ Ultimate edition, you don’t have to do this, I’ll mention later what you can do)
Eclipse: Right click the project > properties > Java Build path. Libraries Tab. Click “Add Jars”. Browse to the library, Click “Ok”. Done.
For Netbeans you also right click the project and go to properties. Click Libraries > Add Jar/Folder > browse to the library > Open > Ok. Done
The library can be put somewhere outside the project, Tomcat has its own copy of it, so you only need the library to be able to compile without errors and don't have to deploy this.

Setup done!


Creating the Servlet

Now the project is all set up to get going. Let’s start by creating a package in the “src” folder, as putting classes on the root is considered not-done. I named mine “servlets”.
Inside this create a new class. I named mine “MyServlet.java”.The first thing to do to turn this into a servlet is making it extend HttpServlet.

(For intelliJ ultimate: make it extend javax.servlet.http.HttpServlet, put caret on “servlet” there, press ALT+ENTER, choose add Java 6 EE module dependencies. IntelliJ will download a bunch of jar so you don’t have to manually download and add them to this project. In the popup window you can choose “configure” to only download javax.servlet)

This requires the import: import javax.servlet.http.HttpServlet; (From the downloaded library). If this class is unknown, the library isn’t properly added.
The HttpServlet has a bunch of methods we can override:
override.png

Let’s take doGet to start with. Get is the http method, like there’s POST, PUT, DELETE,…
This takes 2 parameters: HttpServletRequest req, HttpServletResponse resp
Request can give you info about the request (duh), like for getting cookies, or attribtues/parameters at a POST request.
response is used to send stuff back to the requester. We will start by just showing “Servlet doGet called” to the user. We send stuff back by using the writer which the response object contains.
PrintWriter out = resp.getWriter();
Now we can use “out” to send text back. To send text, use the print() method. Like said before, I will send “Servlet doGet called” back. The Servlet is finished now, and it should look like:
package servlets;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
 
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.print("Servlet doGet called");
    }
}
Okay.. Now where do we go to to call this servlet? That is written down in the now still “empty” web.xml you created at the start.
There are 2 things to do there:
1)Define the servlet
2)Map it to an URL

<servlet>
        <servlet-name></servlet-name>
        <servlet-class></servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name></servlet-name>
        <url-pattern></url-pattern>
    </servlet-mapping>

These are the 2 things we’ll need. Servlet-name doesn’t matter, you can choose whatever it is. As long as you use the same name in the mapping you used at the defining part. Servlet-class is the classname (including packages) of the Servlet, and url-pattern is the url at which this servlet will be mapped to. I took “someServletName” as name, and mapped it to “/doMyServlet”. My final web.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
            http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">
    <servlet>
        <servlet-name>someServletName</servlet-name>
        <servlet-class>servlets.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>someServletName</servlet-name>
        <url-pattern>/doMyServlet</url-pattern>
    </servlet-mapping>
</web-app>

Deploy
Now compile the classes (only the single Servlet class actually | javac command for the manual way) and dump it all in your server.

You don't have a server? No worries. You can download Tomcat 7 here:Apache Tomcat - Apache Tomcat 7 DownloadsI suggest you take the zip for windows ->direct download link: http://apache.megamo...mcat-7.0.20.zip It's only 10-ish MB.
Unzip it to wherever you want.

Many IDEs have the capability to integrate well with webservers. I will however do this the manual way for those with no IDE + this way this tutorial is independant of your IDE choice.

After compilation you need this kind of file structure. Do this outside your development environment. Note how WEB-INF now contains a "classes" directory with all your compiled classes in.
deploy_folder_structure.png

Copy this WEB-INF folder, including its contents, to xxx\apache-tomcat-7.0.20\webapps\name
Where "xxx" is the place where you unzipped tomcat
And where "name" is any kind of name you want. This name will be the name you'll be browsing to: http://localhost:8080/name
I named mine "servletExample" so my folder structure looks like:
tomcat_deploy.png

Note: if port 8080 (tomcat's default) is not free on your computer, you can change it by editing the server.xml file in xxx\apache-tomcat-7.0.20\conf\server.xml
This line:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
Just change 8080 in something else then.

Now we're ready to start the server. (Use commandline to) Go to xxx\apache-tomcat-7.0.20\bin folder, and execute startup.bat. To shut down: shutdown.bat
(Or .sh if you're on a mac or unix environment)
tomcat.png
Now open your favorite web browser and go to: http://localhost:808...MyServlet<br />Remember how when you copied the files, you created "servletExample". And remember how in web.xml we mapped the servlet to "doMyServlet". Now all of that is important for the URL.

If everything is correct you now see "Servlet doGet called"

There, you now created your Servlet, mapped it, compiled it, deployed it, and ran it.

Attached Files


Edited by wim DC, 13 August 2011 - 07:02 AM.

  • 2

#2 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 16 August 2011 - 11:32 AM

Really nice. I'm going to try this later. I will give you a 100 if I can get through it without any issues. :-P

As a side note, I've deployed some Java applications using Glassfish - but they used a war file. Where to the war files fit in?
  • 0

#3 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 16 August 2011 - 12:53 PM

I honestly have no idea how to deploy a .war file on tomcat nor glassfish.
Since a .war file is basically the file structure zipped, you can instead of copying the whole file tree to xxx\apache-tomcat-7.0.20\webapps\name dump the war there, but you'll have to unpack it with 7-zip or some other good unzipper.

Glassfish propably has a way to unpack that stuff on its own to deploy it all, but like I said I don't know how to.

You'll see if you open the .war with a zip program it just contains the web-inf folder, with in that folder the classes folder and web.xml. It's really just a .zip of the files.
  • 0

#4 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 16 August 2011 - 01:21 PM

I okay, I thought it was an archive, just wanted to make sure.
  • 0

#5 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 25 January 2012 - 06:54 AM

I (finally) read about these wars. A .war is just a .jar of everything with the file extension changed.
Its only purpose is to make it easier to move around the web application as it's 1 file instead of the pile of folders and files you have without it.

To deploy it under tomcat it's enough to place the .war file under the 'webapps' directory in tomcat.
As where you previously created the servletExample directory. It's enough to place the war there instead and not have the servletExample directory then.

tomcat_deploy.png

servletExample was the name of the contextroot. The name you use to browse to the application in the browser. With a war it will use the name of the war.
http://localhost:8080/servletExample/doMyServlet

http://localhost:8080/{war-filename}/doMyServlet
Thus, to get the same results, you would have a .war file called "servletExample.war" in there.
  • 0





Also tagged with one or more of these keywords: servlet

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download