Basic Java Servlet/JSP Web Development David Lucek Lucek Consulting www.lucek.com dave@lucek.com May 13th, 2003 @2003 Lucek Consulting Download the Sample Application Download from www.lucek.com, select the downloads tab Includes the full source Unzip to c:\ drive or $HOME/lucek May 13th, 2003 What is a Servlet? Java Servlets/JSP are part of the Sun’s J2EE Enterprise Architecture – Java Servlet – – – The web development part is a simple, consistent mechanism for extending the functionality of a web server Are precompiled Java programs that are executed on the server side. Require a Servlet container to run in Latest Servlet Spec is 2.3 May 13th, 2003 What is a Java Server Page (JSP) Java Server Pages (JSP) – – – – A simplified, fast way to create dynamic web content HTML or XML pages with embedded Java Code or Java Beans Can be a mix of template data in HTML/XML with some dynamic content A JSP is a complied to a Java Servlet automatically by the Servlet container, it is then cached Latest JSP Spec is 1.2 May 13th, 2003 Why Use Servlets? Work well in a Heterogeneous Environments – – OS and platform neutral Work with all major web servers (IIS, Apache,etc..) Well defined Web Architecture framework – Standard built in services such as: Standard Approach to Authentication using declarative security vice programmatic security Database connection pooling Complete support for sessions via cookies and/or URL re-writing – Has automatic fallback to URL re-writing May 13th, 2003 Why Use Servlets Con’t? – Robust Object-Orientated API in Java language Ever try to maintain a large ASP, Perl, or PHP site Clean separation of Controller/Logic from Presentation Efficient, scales very well There are good free Servlet/JSP containers and connectors – That run under both UNIX and win32 May 13th, 2003 J2EE Web Application Components Java Servlets – JSP pages, normally for Presentation Java Beans – Extend off of HttpServlet Normally used as value objects, pass to data to JSPs Tag Libraries – XML based JSP elements Web Deployment Descriptor – /web-inf/web.xml May 13th, 2003 Web Deployment Descriptor /web-inf/web.xml – – – – Part of the standard Defines servlets used in the web application Maps servlets to URLs A servlet can map to many URLs Defines resources available to the web app Defines security constraints Defines other stuff like – – – Welcome file list Session timeout Error page mapping May 13th, 2003 J2EE Web Directory Structure 1 Top Directory is normally the context Path – – – /tomcat/webapps/servletdemo Normally, the URL would be http://localhost:8080/servletdemo Contains JSP and other static content plus the web-inf directory /web-inf directory – – – – This is a protected directory, can not point browser to any file in this directory /classes – unpacked web application classes, auto-magically added to CLASS_PATH /lib – web application JAR files /taglib – tag library descriptor files May 13th, 2003 J2EE Web Directory Structure 2 /web-inf/web.xml /web-inf/* – – – Would normally put any static or JSP files here Protects them from Direct Invocation Always best to call a JSP through a servlet first May 13th, 2003 JSP Constructs 1 Used in JSP pages, pages that end *.jsp Comment <%-- Comment --%> Declaration <%! int x = 0; %> Expression <%= expression %> – – – Outputs to the Response stream Like a “printf” to the browser Do NOT use semi-colon to terminate the line Scriplets - contains Java Code – <% code fragments %> May 13th, 2003 JSP Constructs 2 <% if (value.getName().length != 0) { %> <H2>The value is: <%= value.getName() %></H2> <% } else { %> <H2>Value is empty</H2> <% } %> Implicit objects always available in the JSP Page – “request” – Browser’s Request Object – Use to get HTTP headers, length etc.. “response” - HttpResponse Object May 13th, 2003 JSP Constructs 3 – – – – – – – “session” – internal HttpSession Object “pageContext” “application” “out”, same as <%= %> “config” – servlet configuration “page” “exception” JSP Directives – Are messages or instructions to the JSP container May 13th, 2003 JSP Constructs 4 – – Do not produce any output “page” directive – “include” directive – <%@ page import=“com.lucek.*” %> Commonly used for importing class paths <%@ include file=“header.htm” %> Good for including static content “taglib” – lists the tag library descriptor location Required when using tab libraries May 13th, 2003 Java Beans as Used in Web Apps Normally used for all data transfers and business components Similar to how Java Beans are used in Swing and AWT – But do not need the full implementation Must have no constructor or no-arg constructor Must have setter and getter methods for each property value JSP constructs/tags use Java Beans May 13th, 2003 JSP Actions JSP actions are special tags that affect the output stream and are normally used with Java beans – Most commonly used: <jsp:useBean>, <jsp:getProperty>, <jsp:setProperty> The code below will display the lastName property of the student bean on the output stream <jsp:useBean id="student" scope="request" class="com.lucek.dto.StudentValue" /> <jsp:getProperty name="student" property="lastName" /> May 13th, 2003 Servlet Container/Engine Servlets/JSP require a Container Apache Tomcat is the reference implementation of the Servlet/JSP Specs It is open source, small, install quickly,and is FREE Latest Version is 4.1.24 Web Site: jakarta.apache.org/tomcat It include a simple HTTP 1.1 server, good enough for development and small intranets. May 13th, 2003 Tomcat Install Requires a JDK, get 1.4.1 and install into c:\jdk or $HOME/jdk Add JAVA_HOME to your environment and the “bin” directory to your PATH Good practice to unpack into c:\tomcat or $HOME/tomcat Add CATALINA_HOME to your environment and the “bin” directory to your PATH May 13th, 2003 Tomcat Directory Structure Everything is relative to $CATALINA_HOME /bin – Startup/shutdown scripts /conf – /common – common class and jar files used by Tomcat and web applications – Server.xml – main configuration file Put JDBC drivers here /server – class and jar files used by Tomcat internally /shared – class and jar files for all web applications /webapps – This is where you put your web application in a sub-directory or external context file. May 13th, 2003 Starting Tomcat /bin/startup.bat or startup.sh Point Browers to http://localhost:8080, should see default page All the Docs are there on the default page! Check out the examples pages, good tutorials May 13th, 2003 Other Development Tools 1 Ant Build Tool – – – – Standard Java Build tool Basic on UNIX make, but much better Site: http://ant.apache.org Install in c:\ant or $HOME/ant Java IDE – – – – Try NetBeans, it is nice Tomcat is built in, but is an older version Includes full Servlet and JSP debugging Site: www.netbeans.org May 13th, 2003 Other Development Tools 2 Junit – – Standard Automated Unit Testing Tool Site: http://junit.sourceforge.net Jedit – – – Slick Programmer’s Editor Written in Java Site: jedit.org May 13th, 2003 Simple Servlet Application 1 See “servletdemo” code Mount the servletdemo, servletdemo/java/src, and servletdemo/web in NetBeans Explorer Tab For a Hello World Servlet look at: – Java/src/com/lucek/action/HelloWorld.java To build and run – – – – – $ cd servletdemo Setup the proper build variables in the build.properties file $ ant all $ ant deploy Point your browsers at http://localhost:8080/servletdemo May 13th, 2003 Simple Servlet Application 2 Look at the web.xml file and how the same servlet can be mapped to many URLs Look at SimpleBean.java which should how to pass a Java Bean to a JSP page Look at the different ways a bean’s value can be obtained in the EditStudent.jsp May 13th, 2003 Best Practices/Patterns Always Separate out the logic from the presentation – – Have a clean separation between your data access and controller layers (DAO) Always use DTO or value object Use a Model-View-Controller Architecture – – Use servlets for the logic/controller and JSP’s for presentation Ideally should never have Java Code in the JSP page Do not write it, use Struts Site: jakarta.apache.org/struts/ Use Unit tests – Junit Automation via Ant build tasks May 13th, 2003 What we have not talked about All the specific Servlet APIs Tag libraries Sessions, cookies JDBC service support from the container Container based authentication Lots of other stuff May 13th, 2003 Next Presentation? Create a data driven web site using MySql and Servlets/JSP Setup Authentication Realm with declarative security Setup JDBC connection pooling Struts? May 13th, 2003