Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
JSP全名為Java Server Pages,java服務器頁面。JSP是一種基于文本的程序,其特點就是HTML和Java代碼共同存在!
JSP是為了簡化Servlet的工作出現的替代品,Servlet輸出HTML非常困難,JSP就是替代Servlet輸出HTML的。
String s = "HelloWorda"; out.println(s);
JSP也是Servlet,運行時只有一個實例,JSP初始化和銷毀時也會調用Servlet的init()和destroy()方法。另外,JSP還有自己初始化和銷毀的方法
JSP代碼可以分為兩部分:
JSP腳本
<jsp:scriptlet> String s = "HelloWorld"; out.println(s); </jsp:scriptlet>
JSP注釋
<%--這是JSP注釋--%> <%--%> //這是java的當行注釋 // /*這是java的多行注釋*/ /**/
JSP指令
JSP指令用來聲明JSP頁面的相關屬性,例如編碼方式、文檔類型等等
JSP指令的語法:
<%@指令 屬性名="值" %>
page指令
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page contentType="application/msword;charset=UTF-8" language="java" %> <html> <head> <title>簡單使用JSP</title> </head> <body> 1111 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="error.jsp" %> <html> <head> <title>該頁面出錯了!</title> </head> <body> <%--模擬頁面出錯了!!!--%> <% int result = 2 / 0; %> 你好呀 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %> <html> <head> <title>友好提示頁面</title> </head> <body> 服務器正忙著呢! </body> </html>
<error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page> <error-page> <exception-type>java.lang.NullPointerException</exception-type> <location>/error.jsp</location> </error-page>
include指令
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁頭</title> </head> <body> 我是頁頭 <br> <br> <br> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁尾</title> </head> <body> 我是頁尾 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>包含頁頭和頁尾進來</title> </head> <body> <%@include file="head.jsp" %> <%@include file="foot.jsp" %> </body> </html>
taglib指令
JSP行為
JSP行為(JSP Actions)是一組JSP內置的標簽,只書寫少量的標記代碼就能夠使用JSP提供豐富的功能,JSP行為是對常用的JSP功能的抽象和封裝。
為什么我不把它直接稱為JSP標簽呢?我把這些JSP內置的標簽稱之為JSP行為,能夠和JSTL標簽區分開來。當然了,你也可以把它稱之為JSP標簽,你不要搞混就行了。我個人喜歡把這些JSP內置標簽稱之為JSP行為。
include行為
<jsp:include page=""/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>包含頁頭和頁尾進來</title> </head> <body> <jsp:include page="head.jsp"/> <jsp:include page="foot.jsp"/> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁頭</title> </head> <body> <% String s = "zhongfucheng"; %> 我是頁頭呀 <br> <br> <br> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁尾</title> </head> <body> <% String s = "zhongfucheng"; %> 我是頁尾呀 </body> </html>
param行為
forward行為
<jsp:forward page=""/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>訪問1.jsp就跳轉到head.jsp</title> </head> <body> <jsp:forward page="head.jsp"/> </body> </html>
<jsp:forward page="head.jsp"> <jsp:param name="username" value="zhongfucheng"/> </jsp:forward>
<% String ss = request.getParameter("username"); %> 獲取到的參數是: <%=ss%>
directive行為
<jsp:directive.include file="head.jsp"></jsp:directive.include> <jsp:directive.include file="foot.jsp"></jsp:directive.include>
javaBean行為
<jsp:useBean id=""/> <jsp:setProperty name="" property=""/> <jsp:getProperty name="" property=""/>
文章來源:https://dwz.cn/OtXvyvh3
作者:Java3y
建Web應用
這里使用IDEA構建Web應用
添加新的Tomcat
勾選上正確的Tomcat
選擇Filsh
創建好目錄如下
其自動生成的Web.XML文件如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
同時還生成了一個jsp文件,生成的jsp文件如下
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/5
Time: 22:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>
配置應用首頁
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
啟動相關的應用
這樣就完成了最基本的tomcat的部署
jsp的基本注釋如下
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/5
Time: 22:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%-- 注釋內容 --%>
$END$
</body>
</html>
對jsp的聲明如下
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/5
Time: 22:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%!
// 聲明一個整形變量
public int count;
// 聲明一個方法
public String info(){
return "hello";
}
%>
$END$
<%
// 把count值輸出后加1
out.println(count++);
%>
<%
// 輸出info()方法后的返回值
out.println(info());
%>
</body>
</html>
訪問的頁面結果如下
jsp提供了一種簡單的輸出表達式
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/5
Time: 22:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%!
// 聲明一個整形變量
public int count;
// 聲明一個方法
public String info(){
return "hello";
}
%>
$END$
`<%=count++%>
<%=info()%>
</body>
</html>
這里對jsp有三個編譯的指令
page指令位于jsp頁面的頂端,一個jsp頁面可以有多個page指令,page指令的語法為
<%@ page import="java.sql.*" %>
include指令可以將一個外部文件嵌入到當前jsp文件中,同時解析這個頁面中的jsp語句。include命令既可以包含jsp頁面也可以包含靜態文本。編譯指令語法如下:
<%@ include file="要導入的jsp頁面或文本文件" %>
taglib指令用于引入一些特定的標簽庫,語法格式:
<%@ taglib prefix="tagPrefix" uri="tagLibraryURI" %>
如使用struts標簽庫:
<%@ taglib prefix="s" taglib="/struts-tags" %>
進行頁面跳轉的指令 如果轉發的時候需要傳遞參數可以使用jsp:param</jsp:param>指令進行設置。 比如,訪問index.jsp頁面時自動轉發至login.jsp,需要把username和password傳遞過去: index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:forward page="login.jsp">
<jsp:param value="yaopan" name="username" />
<jsp:param value="123456" name="password" />
</jsp:forward>
<%--mac上按住comment鍵(windows下按住ctrl鍵),再點擊login.jsp forword以下的代碼不會被執行 --%>
在login.jsp中可以使用getParameter方法獲取傳入的參數值:
<%
String name=request.getParameter("username");
String pwd=request.getParameter("password");
out.println(name);
out.println("<br>");
out.println(pwd);
%>
執行forword指令時用戶請求的地址沒有發生變化,頁面內容被forward目標替代。
include指令用于包含某個頁面,但不會導入被include頁面的編譯指令。可以通過param指令傳遞參數: 新建一個index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<jsp:include page="head.html"></jsp:include>
<jsp:include page="body.jsp">
<jsp:param value="#1d99f6" name="bgcolor"/>
</jsp:include>
</html>
body.jsp
JSP 可以與 HTML form 標簽一起使用,來允許用戶上傳文件到服務器。上傳的文件可以是文本文件或圖像文件或任何文檔。
我們使用 Servlet 來處理文件上傳,使用到的文件有:
upload.jsp : 文件上傳表單。
message.jsp : 上傳成功后跳轉頁面。
UploadServlet.java : 上傳處理 Servlet。
需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。
結構圖如下所示:
接下來我們詳細介紹。
創建一個文件上傳表單
下面的 HTML 代碼創建了一個文件上傳表單。以下幾點需要注意:
表單 method 屬性應該設置為 POST 方法,不能使用 GET 方法。
表單 enctype 屬性應該設置為 multipart/form-data.
表單 action 屬性應該設置為在后端服務器上處理文件上傳的 Servlet 文件。下面的實例使用了 UploadServlet Servlet 來上傳文件。
上傳單個文件,您應該使用單個帶有屬性 type="file" 的 <input .../> 標簽。為了允許多個文件上傳,請包含多個 name 屬性值不同的 input 標簽。輸入標簽具有不同的名稱屬性的值。瀏覽器會為每個 input 標簽關聯一個瀏覽按鈕。
upload.jsp 文件代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上傳實例 - 菜鳥教程</title></head><body><h1>文件上傳實例 - 菜鳥教程</h1><form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
選擇一個文件:<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="上傳" /></form></body></html>
編寫后臺 Servlet
以下是 UploadServlet 的源代碼,同于處理文件上傳,在這之前我們先確保依賴包已經引入到項目的 WEB-INF/lib 目錄下:
下面的實例依賴于 FileUpload,所以一定要確保在您的 classpath 中有最新版本的 commons-fileupload.x.x.jar 文件。可以從http://commons.apache.org/proper/commons-fileupload/ 下載。
FileUpload 依賴于 Commons IO,所以一定要確保在您的 classpath 中有最新版本的 commons-io-x.x.jar 文件。可以從http://commons.apache.org/proper/commons-io/ 下載。
你可以直接下載本站提供的兩個依賴包:
commons-fileupload-1.3.2.jar
commons-io-2.5.jar
UploadServlet 的源代碼 如下所示:
package com.runoob.test;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;
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 org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/@WebServlet("/UploadServlet")public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上傳文件存儲目錄
private static final String UPLOAD_DIRECTORY = "upload";
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* 上傳數據及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 檢測是否為多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳參數
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置內存臨界值 - 超過后將產生臨時文件并存儲于臨時目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設置臨時存儲目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設置最大請求值 (包含文件和表單數據)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 構造臨時路徑來存儲上傳的文件
// 這個路徑相對當前應用的目錄
String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
// 如果目錄不存在則創建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析請求的內容提取文件數據
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數據
for (FileItem item : formItems) {
// 處理不在表單中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制臺輸出文件的上傳路徑
System.out.println(filePath);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message",
"文件上傳成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"錯誤信息: " + ex.getMessage());
}
// 跳轉到 message.jsp
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}}
message.jsp 文件代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>文件上傳結果</title></head><body>
<center>
<h2>${message}</h2>
</center></body></html>
編譯和運行 Servlet
編譯上面的 Servlet UploadServlet,并在 web.xml 文件中創建所需的條目,如下所示:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.runoob.test.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/TomcatTest/UploadServlet</url-pattern>
</servlet-mapping></web-app>
現在嘗試使用您在上面創建的 HTML 表單來上傳文件。當您在瀏覽器中訪問:http://localhost:8080/TomcatTest/upload.jsp ,演示如下所示:
如您還有不明白的可以在下面與我留言或是與我探討QQ群308855039,我們一起飛!
*請認真填寫需求信息,我們會在24小時內與您取得聯系。