目录
9.ServletContext(Servlet上下文对象):
一、Servlet深入:
1.HTTP请求结构:
- 包含3部分:请求行、请求头、请求体。
- Get方式把请求放在URL中,故没有请求体。而Post方式把请求放在请求体中。
2.巧用请求头开发多端应用:
例:
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UserAgentServlet
*/
@WebServlet("/ua")
public class UserAgentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserAgentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userAgent = request.getHeader("User-Agent"); // 获取请求头
response.setContentType("text/html;charset=utf-8"); // 设置编码
response.getWriter().println(userAgent);
String output = "";
// 若找到
if (userAgent.indexOf("Windows NT") != -1) {
output = "<h1>这是PC端</h1>";
} else if (userAgent.indexOf("iPhone") != -1 || userAgent.indexOf("Android") != -1) {
output = "<h1>这是移动端</h1>";
}
response.getWriter().println(output);
}
}
3.响应的结构:
- 包含3部分:响应行、响应头、响应体。
状态码 | 错误描述 |
200 | 服务器处理成功 |
404 | 无法找到文件 |
500 | 内部服务器错误 |
403 | 服务器拒绝访问 |
301、302 | 请求重定向 |
400 | 无效请求 |
401 | 未经授权 |
503 | 服务器超负载或正停机维护,无法处理请求 |
4.ContentType的作用:
- 决定了内容输出的结果与样式。
类型 | 描述 |
text/plain | 纯文本 |
text/html | HTML文档 |
text/xml | XML文档 |
application/x-msdownload | 需要下载的资源 |
image/jpeg image/gif image/... | 图片资源 |
例:
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class contentTypeServlet
*/
@WebServlet("/cts")
public class contentTypeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public contentTypeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String output="<h1><a href='http://www.baidu'><span>百度</span></a></h1>";
response.setContentType("text/plain;charset=utf-8");
response.getWriter().println(output);
}
}
修改:
Ctrl+F5:清除缓存,强制刷新。
5.请求转发和重定向:
多个Servlet(JSP)之间跳转有2种方式:
- request.getRequestDispatcher().forward() 请求转发
- response.sendRedirect() 响应重定向
例:
package com.redirect;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CheckLoginServlet
*/
@WebServlet("/check")
public class CheckLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CheckLoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("用户登录成功!");
//A 实现了请求转发功能
request.getRequestDispatcher("index").forward(request, response); // 参数1对应请求,参数2对应响应
//B 响应重定向(需要增加contextPath,此处是/servlet_advanced)
response.sendRedirect("/servlet_advanced/index");
}
}
IndexServlet.java:
package com.redirect;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class IndexServlet
*/
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("<h1>This is index page!username</h1>);
}
}
当注释B,执行A:
当注释A,执行B:
请求转发是从一个Servlet 转发到另一个Servlet,地址栏不变。而请求重定向是将第一次处理完请求后,由浏览器重新发送一个新的请求发送给另一个Servlet,地址栏变化。
①请求转发:
- 请求转发是服务器跳转,只会产生一次请求。
- 从始至终只有一次请求,请求转发是在Tomcat内部自动完成的。
②响应重定向:
- 重定向则是浏览器端跳转,会产生2次请求。
- URL显示第2次请求。
6.设置请求自定义属性:
- 请求允许创建自定义属性。
- 设置请求属性:request.setAttribute(属性名,属性值)
- 获取请求属性:Object attr = request.getAttribute(属性名)
例:
CheckLoginServlet.java:
package com.redirect;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CheckLoginServlet
*/
@WebServlet("/check")
public class CheckLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CheckLoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("用户登录成功!");
request.setAttribute("username", "Isebal");
request.getRequestDispatcher("index").forward(request, response); // 参数1对应请求,参数2对应响应
}
}
IndexServlet.java:
package com.redirect;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class IndexServlet
*/
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = (String) request.getAttribute("username");
response.getWriter().println("This is index page!username is" + username);
}
}
7.浏览器Cookie:
- Cookie是浏览器保存在本地的文本内容。
- Cookie常用于保存登录状态、用户资料等小文本。
- Cookie具有时效性(默认有效期就是当前的浏览器窗口,浏览器关闭,cookie自动销毁),Cookie内容会随请求发送给Tomcat。
- 数据存储在客户端。
例:
LoginServlet.java:
package com.cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/loginCookie")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("用户登陆成功!");
Cookie cookie=new Cookie("user", "Isebal");
response.addCookie(cookie);
response.getWriter().println("login success!");
cookie.setMaxAge(60*60*24*7); //设置cookie有效期,单位是秒
}
}
IndexCookie.java:
package com.cookie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class IndexCookie
*/
@WebServlet("/IndexCookie")
public class IndexCookie extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexCookie() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cs=request.getCookies(); //获得所有的cookie信息,返回一个数组
if (cs==null) {
response.getWriter().println("user not login!");
return; //程序中断
}
String user=null;
for(Cookie c:cs) {
System.out.println(c.getName()+":"+c.getValue()); //获取cookie的名称和值
if (c.getName().equals("user")) {
user=c.getValue();
break;
}
}
if (user==null) {
response.getWriter().println("user not login!");
}else {
response.getWriter().println("user:"+user);
}
}
}
8.Session(用户会话):
- Session用于保存与"浏览器窗口"对应的数据,与浏览器是绑定的。
- 数据存储在Tomcat服务器端,具有时效性(默认35min)。
- Session通过浏览器Cookie的SessionId值提取用户数据。
例:
每个浏览器(注意不是浏览器窗口!)对应的存储空间都是不同的,空间标识符就是SessionId。
LoginSession.java:
package com.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginSession
*/
@WebServlet("/LoginSession")
public class LoginSession extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginSession() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("用户登录成功");
// 获取到用户会话Session对象
HttpSession session = request.getSession();
String sessionId = session.getId();
System.out.println(sessionId);
session.setAttribute("name", "张三");
request.getRequestDispatcher("/IndexSession").forward(request, response);
}
}
IndexSession.java:
package com.session;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class IndexSession
*/
@WebServlet("/IndexSession")
public class IndexSession extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public IndexSession() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String sessionId = session.getId();
System.out.println(sessionId);
String name = (String) session.getAttribute("name");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("这是首页,当前用户为:" + name);
}
}
- Session原理:
9.ServletContext(Servlet上下文对象):
- ServletContext是Web应用全局对象。只要设置了自定义属性,就会在Web应用全局生效。
- 一个Web应用有且只有一个ServletContext对象。
- ServletContext随着Web应用启动而自动创建,随Web应用重启或关闭而销毁。
例:
ServletContext6.java:
package com.servletcontext;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletContext
*/
@WebServlet("/ServletContext")
public class ServletContext6 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletContext6() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context=request.getServletContext();
context.setAttribute("copyright", "@ 2021 7 27");
context.setAttribute("title", "测试页面");
response.getWriter().println("init sucess!");
}
}
DefaultIndex.java:
package com.servletcontext;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DefaultIndex
*/
@WebServlet("/DefaultIndex")
public class DefaultIndex extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DefaultIndex() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context=request.getServletContext();
String copyright=(String)context.getAttribute("copyright");
String title=(String)context.getAttribute("title");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h1>"+title+"</h1>"+copyright);
}
}
先初始化自定义属性,然后就可以获取了。
ServletContext与Session明显的不同之处在于,只要初始化一次,打开随意的浏览器就能直接访问获取。而Session要想在一个新的浏览器获取自定义属性必须先初始化。
10.Java Web三大作用域对象:
- HttpServletRequest——请求对象。生命周期最短,当一个请求送到Tomcat,就会被创建。当servlet处理完成后,产生的响应返回给浏览器则请求对象就会被销毁。request对象是一个瞬时对象,用完了就会被抛弃。
- HttpSession——用户会话对象。用于保存浏览器窗口对应的数据,生命周期更大,在用户首次发来请求时被创建,默认30min未被访问就会销毁(注意:将浏览器关掉只是将存储在浏览器中的SessionId的Cookie抛弃)。
- ServletContext——Web应用全局对象。在Web应用程序启动时就被创建,在Web应用程序重启或关闭时销毁。
三者由上到下,作用域和生命周期是递增的。
11.Web应用的中文乱码:
- Tomcat默认使用ISO-8859-1字符集(属于西欧字符集)。
- 解决乱码的核心是:将ISO-8859-1字符集转换成UTF-8字符集。
- 为了输入输出都能支持中文,要把Servlet的请求和响应都设置成UTF-8字符集。
①解决Post请求的中文乱码:
例:
CharsetForm.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/servlet_advanced/CharsetServlet" method="post">
姓名:<input name="name">
地址:<input name="address">
<input type="submit" value="提交">
</form>
</body>
</html>
CharsetServlet.java:
package com.charset;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CharsetServlet
*/
@WebServlet("/CharsetServlet")
public class CharsetServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CharsetServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//法2:推荐.request.setCharacterEncoding()方法用于将请求体中的字符集进行转换.一定要写在post方法的第一行,而get方法无请求体故无效.
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("name");
String address=request.getParameter("address");
System.out.println(name+":"+address);
//法1:不推荐
//String()可以转换字符集,参数1是原始字符集.参数2是要转换的字符集.getBytes()可以传入原始的字符集.
// String utf8_address=new String(address.getBytes("iso-8859-1"),"utf-8");
// System.out.println(name+":"+utf8_address);
}
}
不使用法1或法2、使用法1、使用法2的结果如下:
注意 request.setCharacterEncoding() 方法用于将请求体中的字符集进行转换.一定要写在post方法的第一行。因为get方法无请求体故不能使用该方法。
②解决Get请求的中文乱码:
- 对于Tomcat8.x的版本,默认get请求发中文就是UTF-8格式,因此无需转换。
③解决响应中的乱码:
- 使用 response.setContType("text/html;charset=utf-8");
二、web.xml常用配置:
- 修改web应有的默认首页。
- Servlet通配符映射及初始化参数。
- 设置404、500等状态码默认页面。
- 欢迎文件列表:Web会自动由上而下检测这些文件是否存在,若存在就会自动加载:
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
例①:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
我是默认首页!
</body>
</html>
例②
WebContent是根目录,不仅可以在根目录下找到页面,对于根目录下的二级路径也可以找到。
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是二级首页,我是新闻模块.
</body>
</html>
例③:
在进行URL匹配时,只需要在想获取的参数位置上,把它改成*,servlet可自动完成匹配。
PatternServlet.java:
package com.pattern;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PatternServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 查询员工基本信息
// 获取当前访问的URL
String url = request.getRequestURL().toString(); // toString()使返回String型
System.out.println(url);
String id = url.substring(url.lastIndexOf("/") + 1); // 从最后一次出现/的位置开始截取.
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(id);
if (id.equals("1")) {
out.println("张三");
} else if (id.equals("2")) {
out.println("李四");
} else {
out.println("其他员工");
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>servlet_advanced</display-name>
<servlet>
<servlet-name>patternServlet</servlet-name>
<servlet-class>com.pattern.PatternServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>patternServlet</servlet-name>
<url-pattern>/pattern/*</url-pattern> <!-- 所有以pattern开头的地址 -->
</servlet-mapping>
</web-app>
例④:全局参数的配置
在web.xml中可利用 <context-param> 标签来设置应用程序的全局参数。
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>servlet_advanced</display-name>
<context-param>
<param-name>copyright</param-name>
<param-value>梦工厂</param-value>
</context-param>
<context-param>
<param-name>date</param-name>
<param-value>2021.7.27</param-value>
</context-param>
</web-app>
ServletContext6.java:
package com.servletcontext;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServletContext
*/
@WebServlet("/ServletContext")
public class ServletContext6 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletContext6() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context=request.getServletContext();
String copyright =context.getInitParameter("copyright"); //获取全局参数
String date =context.getInitParameter("date");
context.setAttribute("copyright", copyright);
context.setAttribute("title",date);
response.getWriter().println("init sucess!");
}
}
DefaultIndex.java:
package com.servletcontext;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DefaultIndex
*/
@WebServlet("/DefaultIndex")
public class DefaultIndex extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DefaultIndex() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context=request.getServletContext();
String copyright=(String)context.getAttribute("copyright");
String title=(String)context.getAttribute("title");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h1>"+title+"</h1>"+copyright);
}
}
例⑤:
404、500等默认报错页面会暴漏我们程序实现的细节,是不安全的,所以要替换默认报错页面。
404.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
资源不存在!
</body>
</html>
500.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
服务器内部错误,请联系管理员!
</body>
</html>
package com.pattern;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PatternServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 查询员工基本信息
// 获取当前访问的URL
String url = request.getRequestURL().toString(); // toString()使返回String型
System.out.println(url);
String id = url.substring(url.lastIndexOf("/") + 1); // 从最后一次出现/的位置开始截取.
int nid=Integer.parseInt(id);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(id);
if (nid==1) {
out.println("张三");
} else if (nid==2) {
out.println("李四");
} else {
out.println("其他员工");
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>servlet_advanced</display-name>
<servlet>
<servlet-name>patternServlet</servlet-name>
<servlet-class>com.pattern.PatternServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>patternServlet</servlet-name>
<url-pattern>/pattern/*</url-pattern> <!-- 所有以pattern开头的地址 -->
</servlet-mapping>
<!-- 指定错误页面 -->
<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.html</location>
</error-page>
</web-app>
三、JSP九大内置对象:
- JSP内置对象就是Servlet内置对象的简化版:
内置对象 | 描述 |
request | 请求对象——HttpServletRequest |
response | 响应对象——HttpServletResponse |
session | 用户会话——HttpSession |
application | 应用全局对象——ServletContext |
out | 输出对象——PrintWriter |
page | 当前页面对象——this |
pageContext | 页面上下文对象——PageContext |
config | 应用配置对象——ServletConfig |
exception | 应用异常对象——Throwable |
其他:
- 把 html 页面转换成 jsp 页面,只需在首行写上:
<%@ page contextType="text/html;charset=utf-8%>
- 若写成:
<%@ page contextType="text/html;charset=utf-8" isErrorPage="true"%>
表示当前jsp是显示错误的页面。
例①:built_in_object.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String url = request.getRequestURI().toString(); //HttpServletRequest
response.getWriter().println(url); //HttpServletResponse
%>
<%
out.println("<br>CXJ");
session.setAttribute("user", "Isebal");
out.println((String) session.getAttribute("user"));
%>
<%
String x = application.getInitParameter("date"); //ServletContext.获取web.xml写好的全局参数
out.println("<hr>");
out.println(x);
pageContext.getRequest();
pageContext.getResponse();
pageContext.getSession();
pageContext.getServletContext();
%>
</body>
</html>
例②:
500.jsp:
<%@ page language="java" contentType="text/html; utf-8"
pageEncoding="utf-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
服务器内部错误,请联系管理员,错误信息如下:
<%
String msg=exception.getMessage();
out.println("<br>"+exception.getClass().getSimpleName()+":"+msg);
%>
</body>
</html>
web.xml:
四、Java Web打包与发布:
见:https://blog.csdn.net/qq_43542011/article/details/119188300