Java Video Tutorial 41

Eclipse ServletsIn this part of the Java Video Tutorial, I’ll show you how to make Java Servlets in Eclipse.

I’ll cover how to set up Tomcat to work with Eclipse. I’ll also show you how to fix the restricted library error, how to set up Eclipse tool tips and more.

If the video is to fast, I list everything below step-by-step. All of the code also follows the video.

If you like videos like this, tell Google

Always feel free to share anything

Install Tomcat for Macs and PCs

The first thing you need to do, is to install Tomcat. I assume you have Apache set up already. You can download Tomcat here. Then depending on your operating system, here are the best Tomcat installation articles:

Setup Tomcat in Eclipse

In Eclipse click on Preferences in the top menu. Then click the following:

  • Click Server
  • Click Runtime Environments
  • Click Add
  • Select your version of Tomcat (Probably 7)
  • Locate the Tomcat directory on your computer

Create a Java Servlet in Eclipse

This is how you create a Java Servlet step-by-step:

  • Right click on your code directory in the Eclipse Project Explorer
  • Click New then Project
  • Click Dynamic Web Project
  • Give it a name (mine is Lesson41) then click Finish
  • Right click on the Java Resources directory
  • Select New and then Servlet
  • Enter a Package Name (mine is helloservlets)
  • Enter a Class Name (mine is Lesson41)
  • Click Next and Finish
  • Edit the doGet method (My Code is Below)
  • Change the web.xml file (My Code is Below)
  • Right click on the project and select Run on Server

Shut Off Serializable Errors in Eclipse

  • Click Preferences
  • Expand Java – Compiler – Errors/Warnings
  • Shutoff Serializable class without serialVersionUID

Setup Java Servlet Tooltips in Eclipse

  • Download the Tomcat Source Code Distribution Zip
  • Open the Java Resources Folder in your project in the Eclipse Project Explorer
  • Open the Libraries Folder
  • Expand the JRE System Library
  • Right click servlet-api.jar
  • Click Properties
  • Select Java Source Attachement
  • Click External File and locate the zip file above

Code From the Video

package helloservlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Lesson41
 */
@WebServlet("/Lesson41")
public class Lesson41 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */ 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		
		PrintWriter output = response.getWriter();
		
		output.println("<html><body><h3>Hello Servlets</h3></body></html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Lesson41</display-name>
  <welcome-file-list>
    <welcome-file>Lesson41</welcome-file>
  </welcome-file-list>
</web-app>

29 Responses to “Java Video Tutorial 41”

  1. Punit says:

    hey nice finally you started with servlets….;-)
    hey darek i have a problem in swing, i have a form in which i have a jcombobox, values in jcombobox are coming from database, i have one more form using which i am inserting the values into database, and those values are displaying in jcombobox.
    but the problem is, i have to close my application once to get the last inserted value, how can i automatic refresh/reload my jcombobox, so it will update automatically??
    Any help will be appreciable.

    Thank you darek.

  2. Rick says:

    Hey there Derek how’s it going bud and happy fathers day to you sir. I spoke to you before about you possibly putting together java j2ee. Pplleeaasseee Derek can you do that? I asked you this before but not sure if you remembered or not. But with a brain like yours I wouldn’t be surprised if you remembered. lol. I joined this guy Sang java passion and this guy after getting accustom to you just breaking things down in a manner where you stay awake to absorb the info you are conveying he does the opposite and puts me right to sleep. OMG he bores me right into the bed to take a nap. Just talks to much. I just want to learn everything from you. I wish you were in a classroom setting sometimes. Your teaching style I like very much and you just crack me the hell up. I bust a gut sometimes and pause the video to have a laugh. I let a friend sit down to check you out and she started laughing. Anyway please if can be so kind to add j2ee to your java tutorial and blow these guys out of the water.You are awesome

    • admin says:

      I do remember you 🙂 I’m going to cover J2EE, but I want to cover Java Design Patterns first. To really understand how to use Java you need to understand OOP and the common design patterns. I’ll go as fast as I can. I’ve been forced to speak a lot lately, but that is calming down.

      I’ll see if I can cover design patterns with j2ee mixed in maybe?

  3. Punit says:

    hey darek, how are you??
    i just want to say, please please start with design patterns as soon as possible…
    can’t wait………

  4. Anne says:

    The most laconic and understandable definition of Servlets I’ve ever met! Thank You! 🙂

  5. fred says:

    Derek you has the best tutorials – Thanks a lot

    When I run lesson41 I got:

    Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.
    Apr 04, 2013 2:12:07 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance
    in production environments was not found on the java.library.path:

    C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;
    ………………………

    Apr 04, 2013 2:12:08 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property
    ‘source’ to ‘org.eclipse.jst.jee.server:Lesson41’ did not find a matching property.
    Apr 04, 2013 2:12:09 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler [“http-bio-8080”]
    Apr 04, 2013 2:12:09 PM org.apache.coyote.AbstractProtocol init
    INFO: Initializing ProtocolHandler [“ajp-bio-8009”]
    Apr 04, 2013 2:12:09 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 3300 ms
    Apr 04, 2013 2:12:09 PM org.apache.catalina.core.StandardService startInternal
    INFO: Starting service Catalina
    Apr 04, 2013 2:12:09 PM org.apache.catalina.core.StandardEngine startInternal
    INFO: Starting Servlet Engine: Apache Tomcat/7.0.39
    Apr 04, 2013 2:12:21 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
    INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [213] milliseconds.

    • Niraj says:

      Hi Fred,
      I am getting the same error in eclipes indigo as well as eclipse juno on ubuntu 12.04.Did you solved it coz even after increasing the timeout I am not able to start tomcat7.You are talking about some optimization stuff how did you resolve that?

  6. fred says:

    I reloaded; Now run ok

  7. Niraj says:

    MY TOMCAT 7 IS FOREVER NOT STARTING in eclipse Juno

    • Derek Banas says:

      Switch to Eclipse Indigo. Juno is a mess

      • Niraj says:

        I installed Indigo.still having the same problem.

      • Niraj says:

        29 Jun, 2013 3:42:04 PM org.apache.catalina.core.AprLifecycleListener init
        INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/lib/jvm/java-6-openjdk-i386/jre/lib/i386/server:/usr/lib/jvm/java-6-openjdk-i386/jre/lib/i386:/usr/lib/jvm/java-6-openjdk-i386/jre/../lib/i386:/usr/lib/jvm/java-6-openjdk-i386/jre/lib/i386/client:/usr/lib/jvm/java-6-openjdk-i386/jre/lib/i386::/usr/java/packages/lib/i386:/usr/lib/i386-linux-gnu/jni:/lib/i386-linux-gnu:/usr/lib/i386-linux-gnu:/usr/lib/jni:/lib:/usr/lib
        29 Jun, 2013 3:42:04 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
        WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Lesson41’ did not find a matching property.
        29 Jun, 2013 3:42:04 PM org.apache.coyote.AbstractProtocol init
        INFO: Initializing ProtocolHandler [“http-bio-8080”]
        29 Jun, 2013 3:42:04 PM org.apache.coyote.AbstractProtocol init
        INFO: Initializing ProtocolHandler [“ajp-bio-8009”]
        29 Jun, 2013 3:42:04 PM org.apache.catalina.startup.Catalina load
        INFO: Initialization processed in 1453 ms
        29 Jun, 2013 3:42:05 PM org.apache.catalina.core.StandardService startInternal
        INFO: Starting service Catalina
        29 Jun, 2013 3:42:05 PM org.apache.catalina.core.StandardEngine startInternal
        INFO: Starting Servlet Engine: Apache Tomcat/7.0.41
        29 Jun, 2013 3:42:06 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
        INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [771] milliseconds.
        29 Jun, 2013 3:42:06 PM org.apache.catalina.core.ContainerBase startInternal
        SEVERE: A child container failed during start
        java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Lesson41]]
        at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
        at java.util.concurrent.FutureTask.get(FutureTask.java:111)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:679)
        Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Lesson41]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        … 7 more
        Caused by: java.lang.IllegalArgumentException: The servlets named [Lesson41] and [helloservlet.Lesson41] are both mapped to the url-pattern [/Lesson41] which is not permitted
        at org.apache.catalina.deploy.WebXml.addServletMapping(WebXml.java:335)
        at org.apache.catalina.startup.ContextConfig.processAnnotationWebServlet(ContextConfig.java:2450)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2132)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsFile(ContextConfig.java:2093)
        at org.apache.catalina.startup.ContextConfig.processAnnotationsFile(ContextConfig.java:2086)
        at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1293)
        at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
        at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5269)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        … 7 more
        29 Jun, 2013 3:42:06 PM org.apache.catalina.core.ContainerBase startInternal
        SEVERE: A child container failed during start
        java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
        at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
        at java.util.concurrent.FutureTask.get(FutureTask.java:111)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
        Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:679)
        Caused by: org.apache.catalina.LifecycleException: A child container failed during start
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        … 7 more
        29 Jun, 2013 3:42:06 PM org.apache.catalina.startup.Catalina start
        SEVERE: Catalina.start:
        org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
        Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        … 7 more
        Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        … 9 more
        Caused by: org.apache.catalina.LifecycleException: A child container failed during start
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
        at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        … 11 more
        29 Jun, 2013 3:42:06 PM org.apache.catalina.startup.Catalina start
        INFO: Server startup in 1518 ms

  8. DunderKlumpen says:

    I can’t get my server to run. It just says it encountered a problem and couldn’t start within the timeout. Increasing the timeout did not help.

  9. kuldeep says:

    Hi Derek,

    for me the servlet-api.jar is missing in JRE System Library list !
    Do I need to copy it from tomcat installation ?

    thanks
    Kuldeep

  10. Erik Elek says:

    Hello Derek,

    Thank you for teaching us with your unique but super effective style.

    I am following your Java tutorials now and got stuck at lesson42. I am trying to start the server with the servlet from lesson42 and the same problem is happening(server failed to start) however, if I remove lesson42 from the server and start the server with the servlet from lesson41, the server is running and everything is good. If I add both of the servlets, and try to run each one, again same problem with each runs.
    I am sure I did everything the same as you did in your tutorial so I think maybe we should do something with the servlet lesson42 Project file (which could be something very very super ridiculously simple thing, but we can’t figure it out what is that 😀 ) which you maybe accidentally didn’t cover in the tutorial.

    I am super noob in coding and all this stuff(I wish I wake up one day and have all the knowledge of yours in my brain), I will have a Java training/internship soon at a company(maybe, if I am lucky) and I think tomcat will be included so it will be really helpful if I could at least know how to run a servlet app 😀

    Wish you the best!

    Sincerely,
    Erik

    • Derek Banas says:

      Hello Erik,

      Getting a server running properly isn’t the easiest thing. Are you seeing any errors and if so what are they? I can try to find the problem.

  11. Erik Elek says:

    Hello,

    Well, when I try to start the server with Lesson42 servlet, a little window pops up with the message:

    ‘Starting Tomcat v7.0 Server at localhost’ has encountered a problem. Server Tomcat v7.0 Server at localhost failed to start.

    And I don’t think it is appropriate to copy and paste everything from the Console(its to long) but it says: ‘SEVERE: A child container failed during start’ than ‘java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component…’ followed by a bunch of java.util and org.apache classes, ‘Caused by:.. ‘ a bunch of ‘org.apache.catalina.LifecycleException:..’ and one ‘java.lang.IllegalArgumentException:..’ and these again followed by a bunch of classes.. than few INFO: about Pausing, Stopping, Destroying ProtocolHandler. (I don’t know if these were helpful 😛 but I hope ).

    I made another Project which contains only the calculatejsp.jsp file from Lesson43, if I add only that Project to the server, again the server run, and when I run the the calculatejsp.jsp file everything is good, the fields are showing up with the button and the date, but when I click on the Calculate button after I introduce the numbers the page is showing this error message: ‘HTTP Status 404 – /Lesson43/calculate.jsp’ also end of the link changed from calculatejsp.jsp to calculate.jsp and (I noticed that at your browser the link did not changed at all :D).

    I also made changes to the settings of the server: switched the location and also server location(Use Tomcat Installation) because I tried to solve the problem by following some instructions I found on the web.

    I’m sorry for the long message I don’t want to bother you with this. However, if any idea comes in your mind about what could be the problem than please share it, because I’m sure that it is a common error which only noobs like me have to face 😀

    Thank You Derek,

    Your Romanian Student, Erik 😀

    • Erik Elek says:

      Hello Derek :),

      Ok, I solved the problem with the server. I can run it now, it was just that annotation I had to delete it 😀 haha, incredible.

      But, I still get the web browser error with the

      ‘HTTP Status 404- /ServletName/calculate.jsp
      ————————
      type Status report

      message /ServletName/calculate.jsp

      description The requested resource is not available.
      ————————
      Apache Tomcat/7.0.53’

      whenever I click on the Calculate/Submit button when the jsp/html file is running.
      It is probably again something easy 😀

      If you have any solution please reply.

      Thank You,
      Erik

  12. Prakash says:

    Hi Admin,
    I am your great fan. When are you going to start J2EE ?

Leave a Reply

Your email address will not be published.

Google+