ĐẠI HỌC QUỐC GIA TPHCM
TRƯỜNG ĐẠI HỌC CÔNG NGHỆ THÔNG TIN
Controlling web application
behavior
Gvhd: Th.s Nguyễn Quang Minh
Agenda
Location and purpose of web.xml
Custom URLs
Initialization parameters
Servlets
JSP Pages
Preloading pages
Welcome pages
Error pages
Deployment Descriptor:
•Basics
Location
Eclipse: WebContent/WEB INF/web xml
Deployed: webAppName/WEB-INF/web.xml
install_dir/conf/web.xml is Tomcat-specific! Ignore it!
• When processed
Only required to be read when server (app) starts
Tomcat monitors web.xml and reloads Web app when web.xml
changes Eclipse redeploys app when web xml changes. Eclipse redeploys app when web.xml changes.
• Basic format
Custom URLs
(Servlet Mappings)
Custom URLs
Default servlet URL:
http://host/webAppPrefix/servlet/ServletName
•
Convenient during development, but wrong for
deployment
Init parameters, security settings, filters, etc. are
associated only with custom URLs
Default URL is long and cumbersome
=> How to make that URL shorter ???
Custom URLs
How to make The URL shorter ???
USE WEB.XML
USE @WEBSERVLET(“”)
Custom URLs
Using web.xml:
Servlet code:
package myPackage;...
public class MyServlet extends HttpServet { ... }
web.xml entry (in ...)
Give name to servlet
MyNamemyPackage .MyServlet
Give address (URL mapping) to servlet
MyName/MyAddress
Custom URLs
Result:
http://hostname/webappName/MyAddress
Custom URLs
USING @WebServlet(“”):
Before “public
class MyServlet extends
HttpServet”, add
@WebServlet(“/MyAddress”)
Examble:
Custom URLs
Note: in both solution, the address must start with “/”
Custom URLs
You should always use custom URLs on deployed
projects
URLs look cleaner and simpler and shorter.
URLs have more meaningful names– URLs have more
meaningful names
You don't expose possibly proprietary class file names
You can use web.xml to assign init params laters
Does not work with …/servlet/myPackage.MyServlet
You can apply filters and security settings later (via
web xml) in a more predictable and controllable
manner
Init param
Init Param
Init Param use to define data before the servlet start
=>How to do that ???
1.
Use WEB.XML
2.
Use Constuctor
Init Param
USING Web.xml
Aabc.AnameDuyTaimail[email protected]A/A
Init Param
In Servlet, to get the param, we use:
ServletConfig config = getServletConfig();
name = config.getInitParameter(“param_name");
Init Param
Examble:
Init Param
Examble:
Init Param
Result:
Init Param
Init param for JSP page
Web.xml:
KhoiTao/first.jspnameDuyTaiKhoiTao/first.jsp
Init Param
JSP file:
First name: <%= name %>
<%!
private String name;
public void jspInit()
{
ServletConfig config = getServletConfig();
name = config.getInitParameter("name");
if (name == null) { name = "No first name"; }
}
%>