Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.

Similar presentations


Presentation on theme: "CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles."— Presentation transcript:

1 CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles

2 Java Web Application Components Compiled Java classes (.class files) Servlets, beans, filters,... Addtional Java libraries (.jar files) JavaServer Pages (JSPs) Static resources HTML, CSS, images,... Metadata files web.xml,...

3 Directory Structure of a Java Web Application Application Root Directory WEB-INF JSPs and static resources classes web.xml lib Compiled Java classes Additional Java libraries

4 Directory Structure on CS3 Application Root Directory WEB-INF JSPs and static resources classes web.xml lib Compiled Java classes Additional Java libraries www

5 Directory Structure of an Eclipse Dynamic Web Project Application Root Directory WEB-INF JSPs and static resources classes web.xml lib Compiled Java classes Additional Java libraries WebContent build/classes

6 Servlet HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; @WebServlet( “/HelloWorld” ) public class HelloWorld extends HttpServlet { public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletExceptoin, IOException { PrintWriter out = response.getWriter(); out.println( “Hello World” ); }

7 Some Simple Observations Inherits from HttpServlet http://download.oracle.com/javaee/6/api/javax/se rvlet/http/HttpServlet.html http://download.oracle.com/javaee/6/api/javax/se rvlet/http/HttpServlet.html There’s no main() method doGet() Input: HttpServletRequest Output: HttpServletResponse  sent back to the client browser

8 Example: HelloWorld in HTML Modify the HelloWorld servlet to output in HTML

9 Generating HTML HttpServletResponse Set content type to “text/html” setContentType() Generate an HTML page getWriter().println() ,,...

10 Servlet Mapping @WebServlet( ) Request URL http:// / / Servlet mapping

11 Java Annotations Available since JDK 1.5 (Java 5) Data about a program that is not part of the program itself Can be used by compiler, VM, and other software tools for various purposes

12 Annotation Examples … Error detection @Override protected void doGet() Suppress warning @SuppressWarnings(“unchecked”) public List getAllUsers() { return (List ) new ArrayList(); }

13 … Annotation Examples Servlet mapping in Sevelet 3.x Specification @WebServlet(“/HelloServlet”) public class HelloServlet extends HttpServlet Web service @WebService public class HashService { @WebMethod public String md5( String text ) }

14 About Annotations An annotation may have elements E.g. @WebServlet(value={“/HelloServlet”}) The default element is value E.g. @WebServlet({“/HelloServlet”}) An element has a type (like a variable in Java) {} can be omitted for array values if there’s only one value in the array E.g. @WebServlet(“/HelloServlet”)

15 @WebServlet http://download.oracle.com/javaee/6/a pi/javax/servlet/annotation/WebServlet. html

16 @WebServlet Elements for URL Patterns value URL pattern(s) of the servlet The default element urlPatterns Same purpose as value Usually used when more than one element is specified Only one of value and urlPatterns can be specified

17 @WebServlet Examples @WebServlet( “/HelloServlet” ) @WebServlet( {“/HelloServlet”, “/member/*”} ) @WebServlet( name=“Hello”, urlPatterns={“/HelloServlet”, “/*.html”} ) @WebServlet( urlPatterns=”/MyPattern”, initParams={@WebInitParam(name="ccc", value="333")} )

18 Be Careful with URL Patterns Invalid patterns E.g. member/index.html, or /member/*.html Conflicting patterns E.g. two /HelloServlet Overlapping patterns E.g. *.html and /member/*

19 Wildcard in Servlet Mapping A string beginning with a / and ending with a /* E.g. /*, /content/* A string beginning with a *. E.g. *.html, *.do See Servlet Specification 3.0, Section 12

20 Example: RequestCounter Display the number of times a servlet is requested You are visitor #1001.

21 Servlet Life Cycle When the servlet is loaded – init() Executed only once Don’t forget super.init(config) Per request – service() dispatch to doXxx() When the servlet is unloaded – destroy()

22 Why Use init() Instead of Constructor Historical reasons – see http://csns.calstatela.edu/wiki/content/ cysun/notes/servlet_data_init http://csns.calstatela.edu/wiki/content/ cysun/notes/servlet_data_init ServletContext cannot be accessed in a constructor

23 Example: SharedRequestCounter Use one servlet to count the number of requests, and another servlet to display the count

24 Application Scope A “storage area” where data can stored and accessed Data in application scope will remain there as long as the application is running Data in application scope is shared by all servlets

25 Access Application Scope HttpServlet getServletContext() HttpServletContext setAttribute(String name, Object value)  Give any object a name and save it to application scope getAttribute(String name)  Retrieve the object from application scope

26 loadOnStartup By default, a servlet is not created until it is accessed for the first time Could cause problem if one servlet must run before another servlet Use the loadOnStartup element of @WebServlet to have a servlet created during application startup

27 loadOnStartup Example @WebServlet( name=“Hello”, urlPatterns={“/HelloServlet”, “/*.html”}, loadOnStartup=1 ) The value for loadOnStartup is the order in which the application server will start the servlets.

28 About web.xml Web application deployment descriptor  version More about web.xml in Java Servlet Specification

29 Versions Servlet/JSP SpecTomcatJava 3.0/2.27.0.x1.6 2.5/2.16.0.x1.5 2.4/2.05.5.x1.4 The version attribute of in web.xml

30 Debugging Servlets Read error message carefully View the source of the generated HTML View Source in browser Validation  http://validator.w3.org/ http://validator.w3.org/  Use the Web Developer addon of Firefox Using the Eclipse debugger Set break points Debug As  Debug on Server

31 Summary Standard directory structure Servlet basics Generate HTML response URL mapping with @WebServlet Lifecyle Data sharing using application scope loadOnStartup web.xml Debugging tips


Download ppt "CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles."

Similar presentations


Ads by Google