050_Servlet詳解
- 2021 年 3 月 17 日
- 筆記
- 060_JavaWeb
目錄
Servlet
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
//響應的類型:html
response.setContentType("text/html");
//響應的編碼
response.setCharacterEncoding("utf-8");
//獲取響應的輸出流
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!--web.xml中配置web的核心應用-->
<!--註冊Servlet-->
<servlet>
<!--名稱,可以隨意寫-->
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<!--映射:一個Servlet對應一個mapping-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!--請求路徑,可以隨意寫-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Servlet簡介
- Servlet是sun公司開發動態web的一門技術
- sun公司在這些API中提供一個接口:Servlet,如果想開發一個Servlet程序,只需要完成兩個步驟
- 編寫一個類,實現Servlet接口
- 把開發好的java類部署到web服務器中
- 我們把實現了Servlet接口的java程序叫做Servlet
- Servlet接口sun公司有兩個默認的實現類:HttpServlet和GenericServlet
HelloServlet
- 構建一個普通maven項目,刪掉src目錄,這個空的工程就是Maven主工程,可以在裏面建立Module;
- 配置pom.xml,添加依賴;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="//maven.apache.org/POM/4.0.0"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qing</groupId>
<artifactId>javaweb-03-servlet</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- //mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
</project>
- 在父工程中新建子模塊Module;
- 關於父子工程的理解:父項目中的jar包子項目可以直接使用;
- 父項目中會有
- 子項目中會有
<modules>
<module>servlet-01</module>
</modules>
<parent>
<artifactId>javaweb-03-servlet</artifactId>
<groupId>com.qing</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
- Maven環境優化:
- 修改web.xml為最新版本:修改子工程web.xml中的版本;
- 將maven的結構搭建完整:子工程添加java和resources目錄;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
- 編寫一個Servlet程序;
- 編寫一個普通類
- 實現Servlet接口,這裡繼承HttpServlet
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
//由於get或者post只是請求實現的不同方式,可以相互調用,業務邏輯都一樣
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("進入doGet方法");
PrintWriter writer = resp.getWriter();//響應流
writer.print("hello,servlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
- 在web.xml中編寫Servlet的映射
為什麼需要映射?
我們寫的是Java程序,但是要通過瀏覽器訪問,而瀏覽器需要連接web服務器,所以我們需要在web服務中註冊我們寫的Servlet,還需要給他一個瀏覽器可以訪問的路徑
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!--註冊Servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<!--Servlet的請求路徑-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
- 配置Tomcat
- 啟動測試
Servlet原理
Servlet是由web服務器調用,web服務器收到瀏覽器請求後,會:
servlet-mapping Servlet請求路徑
- 一個Servlet指定一個映射路徑
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
- 一個Servlet指定多個映射路徑
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>
- 一個Servlet指定通用映射路徑
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
- 默認請求路徑,會跳過index.jsp,直接進Servlet
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
- 指定後綴
<!--可以自定義後綴實現請求映射,注意:*前面不能加任何字符,否則會報錯-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>*.qing</url-pattern>
</servlet-mapping>
- 優先級問題:指定固定映射路徑優先級最高,如果找不到就會走默認請求路徑
<!--404-->
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.qing.servlet.ErrorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
ServletContext Servlet上下文
web容器在啟動的時候,會為每個web程序都創建一個對應的ServletContext對象,它代表了當前web應用
ServletContext的應用
共享數據:在一個Servlet設置的數據,可以在另一個Servlet獲取到
package com.qing.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("hello");
//Servlet上下文
ServletContext context = this.getServletContext();
//設置數據
String username = "清風";
context.setAttribute("username", username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.qing.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
String username = (String) context.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.qing.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.qing.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>
獲取初始化參數
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<context-param>
<param-name>url</param-name>
<param-value>127.0.0.1</param-value>
</context-param>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>com.qing.servlet.GetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping>
</web-app>
package com.qing.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
String url = context.getInitParameter("url");
resp.getWriter().println(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
請求轉發
package com.qing.servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
ServletContext context = this.getServletContext();
//轉發到/hello
context.getRequestDispatcher("/hello").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
讀取Properties文件
username=root
password=123456
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取流,根路徑為打包後target下的項目名稱
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(in);
String user = properties.getProperty("username");
String pwd = properties.getProperty("password");
resp.getWriter().print(user + ":" + pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>prop</servlet-name>
<servlet-class>com.qing.servlet.PropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>prop</servlet-name>
<url-pattern>/prop</url-pattern>
</servlet-mapping>
</web-app>
HttpServletResponse
- web服務器接收到瀏覽器的http請求,針對這個請求,分別創建一個代表請求的HttpServletRequest對象和一個代表響應的HttpServletResponse對象
- 如果要獲取瀏覽器請求過來的參數:找HttpServletRequest
- 如果要給瀏覽器響應一下信息:找HttpServletResponse
- 簡單分類
- 負責向瀏覽器發送數據的方法
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
- 負責向瀏覽器發送響應頭的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
- 響應的狀態碼
int SC_OK = 200;
int SC_CREATED = 201;
下載文件
- 獲取下載文件的路徑
- 獲取文件名
- 設置瀏覽器支持下載
- 文件下載的消息頭和編碼問題 [//www.cnblogs.com/hackxiyu/p/9046247.html](//www.cnblogs.com/hackxiyu/p/9046247.html)
response.setHeader("Content-Disposition", "attachment;filename="+new String(AREA_FILE.getBytes("gb2312"), "ISO-8859-1"));
- 獲取下載文件的輸入流
- 創建緩衝區
- 獲取OutputStream對象
- 將輸入流寫入buffer緩衝區,使用輸出流將緩衝區中的數據輸出到客戶端
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取下載文件的路徑
String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/靜.jpg");
System.out.println("下載文件的路徑為:" + realPath);
//獲取文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
System.out.println("文件名為:" + fileName);
//設置瀏覽器支持下載
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//獲取下載文件的輸入流
FileInputStream fileInputStream = new FileInputStream(realPath);
//創建緩衝區
int len = 0;
byte[] buffer = new byte[1024];
//獲取OutputStream對象
ServletOutputStream outputStream = resp.getOutputStream();
//將輸入流寫入buffer緩衝區,使用輸出流將緩衝區中的數據輸出到客戶端
while ((len=fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
fileInputStream.close();
outputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>fileDown</servlet-name>
<servlet-class>com.qing.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileDown</servlet-name>
<url-pattern>/fileDown</url-pattern>
</servlet-mapping>
</web-app>
驗證碼功能
package com.qing.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//設置瀏覽器3秒自動刷新一次
resp.setHeader("refresh", "3");
//在內存中創建一個圖片
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
//得到畫筆
Graphics2D g = (Graphics2D) image.getGraphics();
//設置畫筆顏色,畫矩形背景
g.setColor(Color.WHITE);
g.fillRect(0,0,80,20);
//設置畫筆顏色和字體,畫隨機數
g.setColor(Color.BLUE);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeRandom(),0,20);
//告訴瀏覽器,這個請求用圖片的方式打開
resp.setContentType("image/jpeg");
//網站存在緩存,不讓瀏覽器緩存
resp.setDateHeader("expires",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把圖片寫給瀏覽器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生產隨機數
private String makeRandom() {
Random random = new Random();
String num = random.nextInt(9999999) + "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 7 - num.length(); i++) {
sb.append(0);
}
num = sb.toString() + num;
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.qing.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
</web-app>
重定向
一個web資源收到客戶端請求後,他會通知客戶端去訪問另外一個web資源,這個過程叫重定向。
常見場景:用戶登錄
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
重定向相當於
resp.setHeader("Location","/resp/image");
resp.setStatus(302);
*/
//重定向
resp.sendRedirect("/resp/image");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.qing.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/image</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>redirectServlet</servlet-name>
<servlet-class>com.qing.servlet.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>redirectServlet</servlet-name>
<url-pattern>/redirect</url-pattern>
</servlet-mapping>
</web-app>
重定向和轉發的區別
登錄demo
- pom.xml添加jsp依賴:javax.servlet.jsp
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="//maven.apache.org/POM/4.0.0"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//maven.apache.org/POM/4.0.0 //maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qing</groupId>
<artifactId>javaweb-03-servlet</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>servlet-01</module>
<module>servlet-02</module>
<module>response</module>
</modules>
<dependencies>
<!-- //mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- //mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
</project>
- 編輯登錄頁,${pageContext.request.contextPath}代表當前項目
<html>
<body>
<h2>Hello World!</h2>
<%--這裡提交的路徑,需要尋找到項目的路徑--%>
<%--${pageContext.request.contextPath}代表當前項目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用戶名:<input type="text" name="username">
密碼:<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
- 編輯登錄成功頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
- 處理登錄請求,重定向到成功頁面
package com.qing.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("進入登錄請求");
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + ":" + password);
//重定向
resp.sendRedirect("/resp/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
- 在web.xml中添加Servlet映射
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="//xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="//xmlns.jcp.org/xml/ns/javaee
//xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.qing.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
HttpServletRequest
HttpServletRequest代表客戶端的請求,用戶通過http協議訪問服務器,http請求中的所有信息都會被封裝到HttpServletRequest,通過HttpServletRequest的方法,可以獲得客戶端的所有信息。
獲取瀏覽器傳遞的參數
String contextPath = req.getContextPath();//項目路徑
String servletPath = req.getServletPath();//Servlet路徑
String requestURI = req.getRequestURI();//請求路徑
String name = req.getParameter("name");
String[] names = req.getParameterValues("name");
請求轉發
//請求轉發
//這裡的/代表當前的web應用,即contextPath
req.getRequestDispatcher("/success.jsp").forward(req,resp);