Java Servlets An introduction to Java Servlet Programming.
-
date post
19-Dec-2015 -
Category
Documents
-
view
254 -
download
3
Transcript of Java Servlets An introduction to Java Servlet Programming.
Web Development
The web is static by nature Based on HTTP A stateless network environment The stateless nature is what have made the
Internet into what it is today
HTTP
A very simple and readable protocol Text based
Several methods GET
The basic request to get a page POST
Used from forms in the web pages DELETE HEAD
Java Servlets - Introduction
Extensions of the web server Run inside the Servlet Container The container can act as a web server The container can interact with a web server via plugins
(Apache and mod_jk for Tomcat for example) One of the front ends to the J2EE system
The servlet acts as the HTTP Receiver and calls EJBs, JMS and so on
Good for implementing control logic Captures that request and determines what to do Initializes Beans, EJBs and other resources Forward the request to a view (A Java Server Page)
Java Servlets - Introduction
Support for sessions A way around the stateless nature of the web Stored on the server Can contain anything Private for a specific user Identified with “jsessionid”
As a Cookie or as a request parameter
Java Servlets - Introduction
Multithreaded by nature There is only one instance of each Servlet The Servlet must be thread safe
Only read only Class variable The Servlet can implement SingleThreadModel to
force the container to only use one thread at a time No concurrent access => bad performance
Not so good for generation nice layout
Java Servlets - Different types A Servlet is a Servlet when in extends one of
the abstract Servlet-classes Currently two types
HttpServlet GenericServlet
Java Servlets - Initialization
A Servlet is only initialized once And there is only one instance
The init(ServletConfig) is executed at initialization The ServletConfig can be used to get
environment variables from web.xml The place initialize common objects like
connection pools Destroy() is called when a Servlet is uloaded
Javax.servlet.GenericServlet
The GenericServlet can work with any protocol
Not used that much in web development
javax.servlet.http.HttpServlet
HttpServlet is specialized for HTTP Contains methods to intercept most HTTP-
methods doGet(HttpServletRequest, HttpServletResponse) doPost(HttpServletRequest,
HttpServletResponse) … processRequest(HttpServletRequest…)
Intercepts all method if present
HttpServletRequst
A representation of the entire HTTP request Contains all request parameters
POST-parameters and GET-parameters are treated equally
Used to get information about the caller Hostname Web browser and OS Username if any
HttpServletRequst
Used to get a handle to the session request.getParameter(“name”)
Gets the value of a parameter. Returns a String that might be casted
request.setAttribute(obj, “name”) Used to add an attribute Usefull when forwarding
request.getAttribute(“name”) Get an attribute Returns an Object
HttpServletRequst
request.getHeader(“name”) Return any HTTP header
request.getLocale() Returns the perfered language getLocales() return an Enumeration of all
supported languages request.getSession(boolean)
Returns the HttpSession The argument decides if a new session should be
created in none is present
HttpServletRequest
request.getCookies() Return an array of all Cookies
request.getRequestDispatcher(url) Used to dispatch the URL, i.e. to pass it down the
request chain RequestDispatcher.forward()
HttpServletResponse
Represents the response that will be sent to the user
Used to write output response.getWriter()
Returns an PrintWriter print(), println()…
Used to encode URLs Used to set content type and other HTTP
Headers
HttpSession
A representation of a Session Retrieved from the request HttpSession.getAttribute(“name”)
Returns an Object HttpSession.setAttribute(Object, “name”) HttpSession.inValidate()
Destroys the Session
A very simple Servlet
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Servlet1 extends HttpServlet {
public void init(ServletConfig config) throws ServletException { super.init(config); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.println(“<h1>Yo</h1>"); out.close(); } }
J2EE Web applications
A web application is standardized The entire web application is controlled by a
single XML-file, web.xml All files (JSP, Servlets, Tags and so on) is
packaged in a WAR file (Web Archive) A JAR-file with a different ending
J2EE Web app – Directory structure / The web root. Can contain JSPs, HTML and
subdirectories WEB-INF -- NOT available to the outside
web.xml Container specific XML-files, orion-web.xml lib
Jar files that will be available for the application classes
Compiled classes like servlets, beans, Home and remote interfaces for EJBs
web.xml
<?xml version = '1.0' encoding = 'windows-1252'?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>Empty web.xml file for Web Application</description> <servlet> <servlet-name>ServletOne</servlet-name> <servlet-class>ServletOne</servlet-class> <init-param> <param-name>DBUrl</param-name> <param-value>jdbc:mimer://lara.mimer.se/fslara82</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ServletOne</servlet-name> <url-pattern>/servletone</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config>
web.xml continued
<mime-mapping> <extension>html</extension> <mime-type>text/html</mime-type> </mime-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <taglib> <taglib-uri>/jstl</taglib-uri> <taglib-location>WEB-INF/jstl.tld</taglib-location> </taglib>
web.xml continued
<security-constraint> <web-resource-collection> <web-resource-name>adminresource</web-resource-name> <url-pattern>/servlet/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/errorLogin.jsp</form-error-page> </form-login-config> </login-config> <security-role> <description>An adminstrator</description> <role-name>admin</role-name> </security-role> </web-app>