CS 3220 Web and Internet Programming Introduction to
CS 3220 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles
Static Web HTTP Server HTTP request Browser HTTP response Client /var /www /html cs 3220. html Server
Deliver Dynamic Content Application Server HTTP request Browser HTTP response input output program Server Client
Setting Up Development Environment https: //csns. calstatela. edu/wiki/content/ cysun/course_materials/eclipse
Servlet Hello. World import java. io. *; import javax. servlet. http. *; @Web. Servlet( "/Hello. World" ) public class Hello. World extends Http. Servlet { public void do. Get( Http. Servlet. Request request, Http. Servlet. Response response ) throws Servlet. Exceptoin, IOException { Print. Writer out = response. get. Writer(); out. println( "Hello World" ); } }
Some Simple Observations Inherits from Http. Servlet n n http: //docs. oracle. com/javaee/7/api/javax/servlet/ http/Http. Servlet. html There’s no main() method do. Get() n n Input: Http. Servlet. Request Output: Http. Servlet. Response sent back to the client browser
Generating HTML Http. Servlet. Response Set content type to "text/html" n set. Content. Type() Generate an HTML page n get. Writer(). println() w <html>, <head>, <body>. . .
Servlet Mapping @Web. Servlet(<URL Pattern(s)>)
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
Annotation Examples … Error detection @Override protected void do. Get() Suppress warning @Suppress. Warnings("unchecked") public List<User> get. All. Users() { return (List<User>) new Array. List(); }
… Annotation Examples Servlet mapping in Sevelet 3. x Specification @Web. Servlet("/Hello. Servlet") public class Hello. Servlet extends Http. Servlet Web service @Web. Service public class Hash. Service { } @Web. Method public String md 5( String text )
About Annotations An annotation may have elements (like attributes of HTML tags) The default element is value 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
@Web. Servlet http: //docs. oracle. com/javaee/7/api/jav ax/servlet/annotation/Web. Servlet. html
@Web. Servlet Elements for URL Patterns value n n URL pattern(s) of the servlet The default element url. Patterns n n n Same purpose as value Usually used when more than one element is specified Only one of value and url. Patterns can be specified
@Web. Servlet Examples @Web. Servlet( "/Hello. Servlet" ) @Web. Servlet( {"/Hello. Servlet", "/member/*"} ) @Web. Servlet( name="Hello", url. Patterns={"/Hello. Servlet", "/*. html"} ) @Web. Servlet( url. Patterns="/My. Pattern", init. Params={@Web. Init. Param(name="ccc", value="333")} )
Wildcard in Servlet Mapping A string beginning with a / and ending with a /* n E. g. /*, /content/* A string beginning with a *. n E. g. *. html, *. do See Servlet Specification 3. 0, Section 12
Be Careful with URL Patterns Invalid patterns n E. g. /member/*. html, or member/index. html Conflicting patterns n E. g. two /Hello. Servlet Overlapping patterns n E. g. *. html and /member/*
Deploy to a Server Understand the directory structure Transfer files to the right folder
Java Web Application Components Compiled Java classes (. class files) n Servlets, beans, filters, . . . Addtional Java libraries (. jar files) Java. Server Pages (JSPs) Static resources n HTML, CSS, images, . . . Metadata files n web. xml, . . .
Directory Structure of a Java Web Application Root Directory JSPs and static resources (e. g. HTML and CSS) WEB-INF web. xml classes Compiled Java classes lib Additional Java libraries
Directory Structure on CS 3 Application Root Directory www JSPs and static resources (e. g. HTML and CSS) WEB-INF web. xml classes Compiled Java classes lib Additional Java libraries
Directory Structure of an Eclipse Dynamic Web Project Application Root Directory Web. Content JSPs and static resources (e. g. HTML and CSS) WEB-INF web. xml classes Compiled Java classes lib Additional Java libraries build/classes
About web. xml Web application deployment descriptor n <web-app> w version n <welcome-file-list> More about web. xml in Java Servlet Specification
Versions Servlet/JSP Spec Tomcat Java 4. 0/2. 3 9. 0. x 8 3. 1/2. 3 8. 0. x, 8. 5. x 7 3. 0/2. 2 7. 0. x 6 2. 5/2. 1 6. 0. x 5 2. 4/2. 0 5. 5. x 4 (a. k. a. 1. 4) The version attribute of <web-app> in web. xml
Example: Hello. World Again Modify the Hello. World servlet to output in HTML n Check the source of the generated HTML in a browser
What's Next Keeping data in a servlet Sharing data among servlets
Example: Request. Counter Display the number of times a servlet is requested
Do Not Use Instance Variables Servlet A Servlet B Thread Thread Most web applications have multiple servlets working on the same data Instance variables of a servlet cannot be shared with other servlets
Application Scope … Servlet A Servlet B Thread Thread Application Scope
Application Scope A "storage area" for sharing data among all servlets Data in application scope will remain there as long as the application is running
Access Application Scope Http. Servlet n get. Servlet. Context() Http. Servlet. Context n set. Attribute(String name, Object value) w Give any object a name and save it to application scope n get. Attribute(String name) w Retrieve the object from application scope
Servlet Life Cycle When the servlet is loaded – init() n n Executed only once Don’t forget super. init(config) Per request – service() n dispatch to do. Xxx() When the servlet is unloaded – destroy()
Why Use init() Instead of Constructor Servlet. Context cannot be accessed in a constructor Historical reasons – see http: //csns. calstatela. edu/wiki/content/c ysun/notes/servlet_data_init
Example: Shared. Request. Counter Use one servlet to count the number of requests, and another servlet to display the count
load. On. Startup By default, a servlet is not created until it is accessed for the first time n Could cause problem if one servlet must run before another servlet Use the load. On. Startup element of @Web. Servlet to have a servlet created during application startup
load. On. Startup Example @Web. Servlet( name="Hello", url. Patterns={"/Hello. Servlet", "/*. html"}, load. On. Startup=1 ) The value for load. On. Startup is the order in which the application server will start the servlets.
Debugging Servlets 404 Errors: check URL and URL mapping Display Problems: check the source of the generated HTML n View Source in browser, or n Use an HTML Validator Logical errors: use the Eclipse debugger n n Set break points Debug As Debug on Server
- Slides: 37