在Java中,response.write()方法用于將數據寫入HTTP響應的輸出流。以下是使用response.write()的示例:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); // 設置響應的內容類型為HTML
response.setCharacterEncoding("UTF-8"); // 設置響應的字符編碼為UTF-8
String message = "Hello, World!";
response.getWriter().write(message); // 將消息寫入響應的輸出流
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My JSP Page</title>
</head>
<body>
<%
String message = "Hello, World!";
response.getWriter().write(message); // 將消息寫入響應的輸出流
%>
</body>
</html>
無論是使用Servlet API還是JSP頁面,都需要獲取響應對象response,并調用response.getWriter()方法來獲取輸出流,然后使用write()方法將數據寫入輸出流。在上述示例中,將字符串"Hello, World!"寫入了響應的輸出流中。