HTTP請求
HTTP請求的結構
HTTP請求包含三部分:請求行、請求頭、請求體。
HTTP響應的結構
HTTP常見狀態碼
ContentType的作用
ContentType
示例:
/**
* Servlet implementation class ContentTypeServlet
*/
@WebServlet("/ct")
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 res) throws ServletException, IOException {
// TODO Auto-generated method stub
String output = "<h1><a href='http://www.baidu.com'>百度</a></h1>";
res.setContentType("text/html;charset=utf-8");
res.getWriter().println(output);
}
}
請求轉發與重定向
- 多個Servlet(JSP)之間跳轉有兩種方式:
request.getRequestDispatcher().forward() 請求轉發: 請求轉發是服務器跳轉,只會產生一次請求
response.sendRedirect() 響應重定向:重定向是瀏覽器端跳轉會產生2次請求。
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
req.setAttribute("username", "admin");
//實現了請求轉發的功能
// req.getRequestDispatcher("/direct/index").forward(req,res);
//響應重定向需要增加contextPath
res.sendRedirect("/myJsp/direct/index");
}
設置請求自定義屬性
請求允許創建自定義屬性。
設置請求屬性:request.setAttribute(屬性名,屬性值)
獲取請求屬性:Object attr = request.getAttribute(屬性名)
瀏覽器Cookie
- Cookie是瀏覽器保存在本地的文本內容
- Cookie常用於保存登錄狀態、用戶資料等小文本
- Cookie具有時效性, Cookie內容會伴隨請求發送給Tomcat
設置cookie
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Cookie coo = new Cookie("name","張三");
coo.setMaxAge(60*60*24);
response.addCookie(coo);
response.getWriter().println("login ok ");
}
獲取
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Cookie[] cs = req.getCookies();
if(cs==null) {
response.getWriter().println("user not login");
return;
}
String user = null;
for(Cookie c : cs) {
System.out.println(c.getName() + ":" + c.getValue());
if(c.getName().equals("name")) {
user = c.getValue();
break;
}
}
if(user == null) {
response.getWriter().println("user not login");
}else {
response.getWriter().println("user:" + user);
}
Session 用戶會話
- Session 用於保存於“瀏覽器窗口”對應的數據
- Session 的數據存在服務器的內存中,具有時效性
- Session 通過瀏覽器Cookie的SessionId值提取用戶數據
Session 常用方法
- request.getSession() --獲取 Session對象
- getAttribute() setAttribute() removeAttribute() – 獲取 設置 刪除Session屬性
- setMaxInactiveInterval — 設置Session超時時間
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = req.getSession();
String sessionId = session.getId();
System.out.print(sessionId);
session.setAttribute("name", "lucy");
req.getRequestDispatcher("/session/index").forward(req, res);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String sessionId = session.getId();
String name = (String)session.getAttribute("name");
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("這是首頁,當前用戶爲:" + name);
}
ServletContext
ServletContext(Servlet上下文對象),是web應用全局對象。
一個web應用只會創建一個ServletContext對象。
ServletContext隨着web應用啓動而自動創建。
Java Web三大作用域對象
HttpServletRequest ---- 請求對象
HttpSession ----- 用戶會話對象
ServletContext ---- web應用全局對象。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = request.getServletContext();
String copyright = context.getInitParameter("copyright");
context.setAttribute("copyright", copyright);
String title = context.getInitParameter("title");
context.setAttribute("title", title);
response.getWriter().println("init success");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = (ServletContext)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);
}
web應用的中文亂碼問題
Tomcat默認使用字符集ISO-8859-1,屬於西歐字符集。
解決亂碼的核心思路是將ISO-8859-1轉換爲UTF-8
Servlet中請求與相應都要設置值utf-8字符集。
web.xml常用配置
- 修改web應用默認首頁
- Servlet通配符映射及初始化參數
- 設置404、500等狀態碼默認頁面
<?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>
<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>
<servlet>
<servlet-name>patternServlet</servlet-name>
<servlet-class>pattern.PatternServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>patternServlet</servlet-name>
<url-pattern>/pattern/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>copyright</param-name>
<param-value>© 12003892號-22</param-value>
</context-param>
<context-param>
<param-name>title</param-name>
<param-value>淘寶</param-value>
</context-param>
<!-- 指定錯誤頁面 -->
<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
</web-app>
JSP九大內置對象
Tomcat常用配置
- 修改web應用端口號
- 修改ContextPath上下文路徑
- 設置應用自動重載
server.xml文件修改配置。
JAVA WEB打包與發佈
- Java Web應用採用war包進行發佈
- 發佈路徑爲: {TOMCAT_HOME}/webapps
- Eclipse支持war包導出
項目上右鍵,Export ---->WAR file