-
Concept
-
container
- Communications support
-
Lifecycle Management
- load
- instance
- invoke
- garbage collection
-
Multithreading Support
- create new java thread for every servlet request
- when the servlet's done running the http service method,the thread completes
-
Declarative Security
- XML config
-
JSP Support
- translate JSP to real Java
- CGI
-
HTTP
-
Method
-
POST
- complex request
- hide parameters in the message body not url
- message can be large
- not idempotent
- to change something on the server
-
GET
- just simple request
- has not body,only headers
- exposed
- length limited
- idempotent
- just getting information
-
MIME type
- Content-Type:text/html
- URL
- Servlet Life Cycle
-
listeners
- ServletContextAttributeListener
- ServletRequestListener
- ServletRequestAttributeListener
- ServletContextListener
- HttpSessionListener
- HttpSessionBindingListener
- HttpSessionAttributeListener
- HttpSessionActivationListener
-
attribute
- servletContext.setAttribute("dog",d);
- request.setAttribute("userList",userList);
- an attribute is an object set into one of the three other servlet API objects
- 返回Object类型,必须转换
-
API
- Object getAttribute(String name)
- void setAttribute(String name,Object value)
- void removeAttribute(String name)
- Enumeration getAttributeNames()
-
Scopes
-
Context
- everyone in the application has access
-
isn't thread-safe
- synchronize the ServletContext
-
Request
- accessible to only those with access to a specific ServletRequest
- only request attributes and local variables are tread-safe
-
Session
- accessible to only those with access to a specific HttpSession
- the client could open a new browser window
- SingleThreadModel
-
Servlet
-
container handle request
- see a request for servlet
- create HttpResponse,HttpRequest
-
find the requested servlet
-
real name and internal name
- <servlet>
-
internal name and url
- <servlet-mapping>
- create or allocate a thread for the request
- pass the request and response to the servlet thread
-
call the servlet's service() method
- call doGet()
- or call doPost()
- support both get and post
- put something in the response
- thread completes
- container converts response object to HTTP response
- send it back to client
- delete request and response object
-
parameters
-
jsp get from serlvet
- request.getAttribute("userList")
-
servlet get from jsp
-
request.getParameter("color")
- RequestDispatcher
- request.setAttribute("userList",userList)
- String one=request.getParameterValues("sizes")[0]
- String[] sizes=request.getParameterValues("sizes");
-
servlet's life
- load class
- instantiate servlet
-
init()--call only once
- get database connection
- register your own object
- a servlet’s service() method will not run until the servlet is fully initialized.
-
access
- ServletConfig
- used to access ServletContext
- ServletContext
- used to access web app parameters
-
service()--each request runs in a separate thread
- thread
- destroy()--call only once
-
request object
-
getParameter
- String[] sizes=request.getParameterValues("sizes");
- request.getParameter("color")
- String one=request.getParameterValues("sizes")[0]
-
getHeader
- String client=request.getHeader("User-Agent");
-
getCookies
- Cookie[] cookies=request.getCookies();
-
getSession
- HttpSession session=request.getSession();
-
getMethod
- String httpMethod=request.getMethod();
-
getInputStream
- InputStream input=request.getInputStream();
-
getHeader
- String forwards=request.getHeader("Max-Forwards");
- int forwardsNum=request.getIntHeader("Max-Forwards");
-
getRemotePort
- get the client's port
-
getServerPort
- to which port was the request originally SENT
-
getLocalPort
- on which port did the request END UP
- handle multiple clients
-
response object
-
setContentType
- text/html
- application/pdf
- video/quicktime
- application/java
- image/jpeg
- application/jar
- application/octet-stream
- application/x-zip
-
getOutputStream
- ServletOutputStream out=response.getOutputStream();
- out.write(aByteArray);
-
getWriter
- PrintWriter writer=response.getWriter();
- writer.println("some text and HTML");
- has a reference to OutputStream,and decorates to character
-
setHeader
- overwrites the existing value
-
addHeader
- adds an additional value
-
sendRedirect
- response.sendRedirect("http://www.oreilly.com");
-
http://www.wickedlysmart.com/myApp/cool/bar.do
- http://www.wickedlysmart.com/myApp/cool/foo/stuff.html
- http://www.wickedlysmart.com/foo/stuff.html
- relative to the root of this web container
- foo is a web app,separate from the myapp web app
- you can't write to the response and then call sendRedirect()
- sendRedirect() takes a String, not a URL object
- it's like asking the client(the browser) to call someone else instead
-
request Dispatch
- do the work on the server
- RequestDispatcher view=request.getRequestDispatcher("result.jsp");
view.forward(request,response);
- it's like asking a co-worker to take over working with a client
-
deployment descriptor
-
servlet initialization parameters
- <init-param>
<param-name>adminEmail</param-name>
<param-value>likewecare@wickedlysmart.com</param-value>
</init-param>
- getServletConfig().getInitParameter("adminEmail");
- only for servlet
- the servlet init parameters are read only once
-
many init parameters
- Enumeration e=getServletConfig().getInitParameterName();
- while(e.hasMoreElements()){
e.nextElement();
}
- setting a request attribute only for the jsp to which you forwarded the request
-
context init parameter
- <context-param>
<param-name>adminEmail</param-name>
<param-value>clientheaderror@wickedlysmart.com</param-value>
</context-param>
- getServletContext().getInitParameter("adminEmail");
- getServletConfig().getServletContext().getInitParameter("adminEmail");
- available to JSP and Servlet
-
ServletContextListener
-
setting
- put it in your WEB-INF/classes
- config in dd to tell the container
-
thread-safe
-
yes
- Request-scoped attributes
- Loacl variables in service methods
-
no
- Context-scoped attributes
- Session-scoped attributes
- Instance variables in the servlet
- Static variables in the servlet
-
RequestDispatcher
-
get from ServletRequest
- RequestDispatcher view=request.getRequestDispatcher("result.jsp");
-
get from ServletContext
- RequestDispatcher view=getServletContext().getRequestDispatcher("/result.jsp");
-
HttpSession
- hold conversational state across multiple requests from the same client
-
session ID
-
exchange Session ID info
- server set-cookie in http header
- client send cookie in http header
-
HttpSession session=request.getSession();
-
sending a session cookie in the response
- generate the session id and cookie for the response
- cause a cookie to be sent with the response
-
gettting the session id from the request
- if the request includes a session id cookie
- else if there's no session id cookie or don't match
-
session.isNew()
- true-->the client has not yet responded with this session id
-
HttpSession session=request.getSession(false);
- return a pre-existing session or null if there was no session associated with this client
- if (session==null) session=request.getSession();
-
if the client doesn't accept cookies
- it ignores set-cookie response header
-
use URL rewriting as a backup
- tell the response to encode the URL
- HttpSession session=request.getSession();
response.encodeURL("/test.do");
- response.encodeRedirectURL("/test.do");
- URL rewriting will happen automatically if cookies don't work with the client
-
methods
- getCeationTime()
- getLastAccessedTime()
- setMaxInactiveInterval()
- getMaxInactiveInterval()
-
invalidate()
- remove all attributes
-
session die
-
it times out
- <session-config>
<session-timeou>15</session-timeout>
</session-config>
- setting for specific session
- session.isNew()
-
call invalidate() on the session object
- session.invalidate(); you can't call session.getAttribute("foo");
- the application goes down(crashes or is undeployed
- session cookies vanish when the client's browser quits,but you can tell a cookie to persist on the client even after the browser shuts down
-
distributed
- move from one vm to another, not copy
- HttpSessionActivationListener lets attributes prepare for the big move
-
listeners
-
HttpSessionBindingListener
- valueBound
- valueUnbound
- binding for class attribute
-
HttpSessionListener
- sessionCreated
- sessionDestroyed
-
HttpSessionAttributeListener
- attributeAdded
- attributeRemoved
- attributeReplaced
- use HttpSessionBindingEvent
- binding for attribute
-
HttpSessionActivationListener
- sessionWillPassivate
- sessionDidActivate
-
Cookie
-
create
- Cookie cookie=new Cookie("username",name);
-
setting
- cookie.setMaxAge(30*60);30 mimutes
- while -1 for session will never expired
-
send to client
- response.addCookie(cookie);
- 对比addHeader() add new value if exists ;setHeader() replace the exist value
-
get from client request
- Cookie[] cookies=request.getCookies();
-
JSP
-
syntax
-
comment
- <!--html comment -->
- <%-- jsp comment --%>
-
init parameters
-
<jsp-file>/TestInit.jsp</jsp-file>
- config
- get
- application.getInitParameter("javax.sql.DataSource");
-
Directive
-
page
- <%@ page import="foo.*,java.util.*" %>
- for special instructions to container
- attributes
- import
- import java.lang.*,javax.servlet,javax.servlet.http for free
- isThreadSafe
- true--implement the SingleThreadModel
- contentType
- defines the MIME type
- isELIgnored
- to ignore EL expressions or not
- isErrorPage
- defines whether the current page represents another JSP's error page
- default false,if true, the page has access to the implicit exception object
- errorPage
- defines a URL to the resource to which uncaught Throwables should be sent
- others
- language
- extends
- session
- defines whether the page will have an implicit session object
- buffer
- defines how buffering is handled by the implicit JspWriter
- autoFlush
- defines whether the buffered output is flushed automatically
- info
- defines a string that gets put into the translated page
- pageEncoding
- defines the character encoding for the JSP
-
taglib
- <%@ taglib tagdir="/WEB-INF/tags/cool" prefix="cool" %>
-
include
- <%@ include file="wickedHeader.html" %>
-
Scriptlet
-
<% out.println(Counter.getCount());%>
- within the service method
-
Expression
-
<%=Counter.getCount()%>
- it become the argument to an out.print();
-
Declaration
-
<%! int count=0; %>
- for declaring members of the generated servlet class
- add to the class outside the service method
- variable
- method
-
Action
- <jsp:include page="foo.html" />
-
translate to servlet
- work
- variable
-
what the container do
- looks at the directives
-
create an HttpServlet subclass
- for tomcat
- if import write import statements
- if declarations,write into the class file
-
build service method
- it's called by the servlet superclass's overridden service() method
- declares and initializes all the implicit objects
- out
- JspWriter
- request
- HttpServletRequest
- response
- HttpServletResponse
- session
- HttpSession
- application
- ServletContext
- config
- ServletConfig
- exception
- Throwable
- pageContext
- PageContext
- page
- Object
- combines the html,scriptlets and expressions into the service method
- translate to java code
- compile to class code
-
API
-
jspInit()
- called from the init() method
-
jspDestroy()
- called from the servlet destroy() method
-
_jspService()
- called from the servlet's service() method
- can be overridden
-
life cycle
- translation and compilation
- load jsp class
- instantiates the servlet and invoke jspInit()
- create a new thread to handle request
- invoke _jspService() method
- send back response or forwards
-
attributes
- scope
- pageContext
-
standard actions
-
bean
-
declare and initialize a bean attribute
- if not found create
- polymorphic bean references
- if type is used without class,the bean must already exist
- if class is used the class must not be abstract,and must have a public no-arg constructor
- type x=new class()
- get bean property
-
set bean property
- set bean only not found
- it convert the string to destination type for you
-
param
- html与bean不一致
- 如果一致则无需写param
- 如果所有属性均赋值则
-
<jsp:include page="Header.jsp" />
- don't put opening and closing HTML and body tags within your reusable pieces
-
param
- pic
-
position
- Topic
-
difference to directive
- 每次获得都是最新的,但是会影响性能
- the container is creating a RequestDispatcher from the page attribute and applying the include() method
- difference with directive include
- /
-
<jsp:forward>
- <jsp:forward page="HandleIt.jsp" />
- nothing you write before before the forward will appear if the forward happens,it cleared the buffer
-
EL Expression
-
config
- <%@ page isELIgnored="true" %>
-
${} <c:out value="${user.phone}" />
- detail
- array
- string index
-
get other info
- ${header["host"]}
- ${pageContext.request.method}
- request.setAttribute("foo.person",p)
- ${cookie.username.value}
- ${initParam.mainEmail}
-
function
- write a java class with a public static method
- write a Tag Library Descriptor(TLD) file
- put a taglib directive in your JSP
- use EL to invoke the function
- 概要
-
operator
- pic
-
null-friendly
- in arithmetic-->treat null as zero
- in logical -->treat null as false
- if not found still display
-
JSP Standard Tag Library
-
install
- jstl.jar and standard.jar
-
<c:out>
- <c:out value='${pageContent.currentTip}' escapeXml='false' />
- html special characters
- <c:out value='${user}' default='guest' />
- <c:forEach>
- <c:if>
- <c:choose>
-
<c:set>
- setting attribute variables
- setting bean properties or Map values
- defalut scope is page
- <c:remove>
-
<c:import>
-
difference
- pic
- customer
-
<c:url>
- for url rewriting
-
query string
- pic
- <c:catch>
-
customer
-
URI
- a name,not a location
- container look for
-
TLD
- <rtexprvalue>
- tag file
- tag
- tag-body
- tag-file-body
- find
- difference: tags and tag file
- pic
- Topic
- Topic
- Topic
-
tag handler
- simple
- extends SimpleTagSupport
- sequence
- invoke null
- dynamic attribute
- classic
- lifecycle
- pic
- BodyTagSupport
-
Error handle
-
config in dd
- pic
-
config in jsp page
- pic
-
error page
- get ${pageContext.exception}
- <c:catch>
-
Deploy
-
structure
- pic
-
config
-
index
- pic
-
error
- pic
-
servlet initialization
- pic
-
security
-
authentication
- define roles
-
define resource/method constraints
- <auth-constraint>
-
types
- BASIC
- DIGEST
- CLIENT-CERT
- FORM
- pic
- authorization
- confidentiality
- data integrity
-
filter
-
example
- pic