JSP全名為Java Server Pages,java服務(wù)器頁(yè)面。JSP是一種基于文本的程序,其特點(diǎn)就是HTML和Java代碼共同存在!
JSP是為了簡(jiǎn)化Servlet的工作出現(xiàn)的替代品,Servlet輸出HTML非常困難,JSP就是替代Servlet輸出HTML的。
String s = "HelloWorda"; out.println(s);
JSP也是Servlet,運(yùn)行時(shí)只有一個(gè)實(shí)例,JSP初始化和銷毀時(shí)也會(huì)調(diào)用Servlet的init()和destroy()方法。另外,JSP還有自己初始化和銷毀的方法
JSP代碼可以分為兩部分:
JSP腳本
<jsp:scriptlet> String s = "HelloWorld"; out.println(s); </jsp:scriptlet>
JSP注釋
<%--這是JSP注釋--%> <%--%> //這是java的當(dāng)行注釋 // /*這是java的多行注釋*/ /**/
JSP指令
JSP指令用來(lái)聲明JSP頁(yè)面的相關(guān)屬性,例如編碼方式、文檔類型等等
JSP指令的語(yǔ)法:
<%@指令 屬性名="值" %>
page指令
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page contentType="application/msword;charset=UTF-8" language="java" %> <html> <head> <title>簡(jiǎn)單使用JSP</title> </head> <body> 1111 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="error.jsp" %> <html> <head> <title>該頁(yè)面出錯(cuò)了!</title> </head> <body> <%--模擬頁(yè)面出錯(cuò)了!!!--%> <% int result = 2 / 0; %> 你好呀 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %> <html> <head> <title>友好提示頁(yè)面</title> </head> <body> 服務(wù)器正忙著呢! </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>頁(yè)頭</title> </head> <body> 我是頁(yè)頭 <br> <br> <br> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁(yè)尾</title> </head> <body> 我是頁(yè)尾 </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>包含頁(yè)頭和頁(yè)尾進(jìn)來(lái)</title> </head> <body> <%@include file="head.jsp" %> <%@include file="foot.jsp" %> </body> </html>
taglib指令
JSP行為
JSP行為(JSP Actions)是一組JSP內(nèi)置的標(biāo)簽,只書寫少量的標(biāo)記代碼就能夠使用JSP提供豐富的功能,JSP行為是對(duì)常用的JSP功能的抽象和封裝。
為什么我不把它直接稱為JSP標(biāo)簽?zāi)兀?strong>我把這些JSP內(nèi)置的標(biāo)簽稱之為JSP行為,能夠和JSTL標(biāo)簽區(qū)分開(kāi)來(lái)。當(dāng)然了,你也可以把它稱之為JSP標(biāo)簽,你不要搞混就行了。我個(gè)人喜歡把這些JSP內(nèi)置標(biāo)簽稱之為JSP行為。
include行為
<jsp:include page=""/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>包含頁(yè)頭和頁(yè)尾進(jìn)來(lái)</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>頁(yè)頭</title> </head> <body> <% String s = "zhongfucheng"; %> 我是頁(yè)頭呀 <br> <br> <br> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>頁(yè)尾</title> </head> <body> <% String s = "zhongfucheng"; %> 我是頁(yè)尾呀 </body> </html>
param行為
forward行為
<jsp:forward page=""/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>訪問(wèn)1.jsp就跳轉(zhuǎn)到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"); %> 獲取到的參數(shù)是: <%=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=""/>
文章來(lái)源:https://dwz.cn/OtXvyvh3
作者:Java3y
建Web應(yīng)用
這里使用IDEA構(gòu)建Web應(yīng)用
添加新的Tomcat
勾選上正確的Tomcat
選擇Filsh
創(chuàng)建好目錄如下
其自動(dòng)生成的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>
同時(shí)還生成了一個(gè)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>
配置應(yīng)用首頁(yè)
<?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>
啟動(dòng)相關(guān)的應(yīng)用
這樣就完成了最基本的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>
<%-- 注釋內(nèi)容 --%>
$END$
</body>
</html>
對(duì)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>
<%!
// 聲明一個(gè)整形變量
public int count;
// 聲明一個(gè)方法
public String info(){
return "hello";
}
%>
$END$
<%
// 把count值輸出后加1
out.println(count++);
%>
<%
// 輸出info()方法后的返回值
out.println(info());
%>
</body>
</html>
訪問(wèn)的頁(yè)面結(jié)果如下
jsp提供了一種簡(jiǎn)單的輸出表達(dá)式
<%--
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>
<%!
// 聲明一個(gè)整形變量
public int count;
// 聲明一個(gè)方法
public String info(){
return "hello";
}
%>
$END$
`<%=count++%>
<%=info()%>
</body>
</html>
這里對(duì)jsp有三個(gè)編譯的指令
page指令位于jsp頁(yè)面的頂端,一個(gè)jsp頁(yè)面可以有多個(gè)page指令,page指令的語(yǔ)法為
<%@ page import="java.sql.*" %>
include指令可以將一個(gè)外部文件嵌入到當(dāng)前jsp文件中,同時(shí)解析這個(gè)頁(yè)面中的jsp語(yǔ)句。include命令既可以包含jsp頁(yè)面也可以包含靜態(tài)文本。編譯指令語(yǔ)法如下:
<%@ include file="要導(dǎo)入的jsp頁(yè)面或文本文件" %>
taglib指令用于引入一些特定的標(biāo)簽庫(kù),語(yǔ)法格式:
<%@ taglib prefix="tagPrefix" uri="tagLibraryURI" %>
如使用struts標(biāo)簽庫(kù):
<%@ taglib prefix="s" taglib="/struts-tags" %>
進(jìn)行頁(yè)面跳轉(zhuǎn)的指令 如果轉(zhuǎn)發(fā)的時(shí)候需要傳遞參數(shù)可以使用jsp:param</jsp:param>指令進(jìn)行設(shè)置。 比如,訪問(wèn)index.jsp頁(yè)面時(shí)自動(dòng)轉(zhuǎn)發(fā)至login.jsp,需要把username和password傳遞過(guò)去: 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鍵),再點(diǎn)擊login.jsp forword以下的代碼不會(huì)被執(zhí)行 --%>
在login.jsp中可以使用getParameter方法獲取傳入的參數(shù)值:
<%
String name=request.getParameter("username");
String pwd=request.getParameter("password");
out.println(name);
out.println("<br>");
out.println(pwd);
%>
執(zhí)行forword指令時(shí)用戶請(qǐng)求的地址沒(méi)有發(fā)生變化,頁(yè)面內(nèi)容被forward目標(biāo)替代。
include指令用于包含某個(gè)頁(yè)面,但不會(huì)導(dǎo)入被include頁(yè)面的編譯指令。可以通過(guò)param指令傳遞參數(shù): 新建一個(gè)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 標(biāo)簽一起使用,來(lái)允許用戶上傳文件到服務(wù)器。上傳的文件可以是文本文件或圖像文件或任何文檔。
我們使用 Servlet 來(lái)處理文件上傳,使用到的文件有:
upload.jsp : 文件上傳表單。
message.jsp : 上傳成功后跳轉(zhuǎn)頁(yè)面。
UploadServlet.java : 上傳處理 Servlet。
需要引入的 jar 文件:commons-fileupload-1.3.2、commons-io-2.5.jar。
結(jié)構(gòu)圖如下所示:
接下來(lái)我們?cè)敿?xì)介紹。
創(chuàng)建一個(gè)文件上傳表單
下面的 HTML 代碼創(chuàng)建了一個(gè)文件上傳表單。以下幾點(diǎn)需要注意:
表單 method 屬性應(yīng)該設(shè)置為 POST 方法,不能使用 GET 方法。
表單 enctype 屬性應(yīng)該設(shè)置為 multipart/form-data.
表單 action 屬性應(yīng)該設(shè)置為在后端服務(wù)器上處理文件上傳的 Servlet 文件。下面的實(shí)例使用了 UploadServlet Servlet 來(lái)上傳文件。
上傳單個(gè)文件,您應(yīng)該使用單個(gè)帶有屬性 type="file" 的 <input .../> 標(biāo)簽。為了允許多個(gè)文件上傳,請(qǐng)包含多個(gè) name 屬性值不同的 input 標(biāo)簽。輸入標(biāo)簽具有不同的名稱屬性的值。瀏覽器會(huì)為每個(gè) input 標(biāo)簽關(guān)聯(lián)一個(gè)瀏覽按鈕。
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>文件上傳實(shí)例 - 菜鳥(niǎo)教程</title></head><body><h1>文件上傳實(shí)例 - 菜鳥(niǎo)教程</h1><form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data">
選擇一個(gè)文件:<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="上傳" /></form></body></html>
編寫后臺(tái) Servlet
以下是 UploadServlet 的源代碼,同于處理文件上傳,在這之前我們先確保依賴包已經(jīng)引入到項(xiàng)目的 WEB-INF/lib 目錄下:
下面的實(shí)例依賴于 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/ 下載。
你可以直接下載本站提供的兩個(gè)依賴包:
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;
// 上傳文件存儲(chǔ)目錄
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
/**
* 上傳數(shù)據(jù)及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 檢測(cè)是否為多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳參數(shù)
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設(shè)置內(nèi)存臨界值 - 超過(guò)后將產(chǎn)生臨時(shí)文件并存儲(chǔ)于臨時(shí)目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設(shè)置臨時(shí)存儲(chǔ)目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設(shè)置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設(shè)置最大請(qǐng)求值 (包含文件和表單數(shù)據(jù))
upload.setSizeMax(MAX_REQUEST_SIZE);
// 構(gòu)造臨時(shí)路徑來(lái)存儲(chǔ)上傳的文件
// 這個(gè)路徑相對(duì)當(dāng)前應(yīng)用的目錄
String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
// 如果目錄不存在則創(chuàng)建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析請(qǐng)求的內(nèi)容提取文件數(shù)據(jù)
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數(shù)據(jù)
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);
// 在控制臺(tái)輸出文件的上傳路徑
System.out.println(filePath);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message",
"文件上傳成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"錯(cuò)誤信息: " + ex.getMessage());
}
// 跳轉(zhuǎn)到 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>文件上傳結(jié)果</title></head><body>
<center>
<h2>${message}</h2>
</center></body></html>
編譯和運(yùn)行 Servlet
編譯上面的 Servlet UploadServlet,并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:
<?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>
現(xiàn)在嘗試使用您在上面創(chuàng)建的 HTML 表單來(lái)上傳文件。當(dāng)您在瀏覽器中訪問(wèn):http://localhost:8080/TomcatTest/upload.jsp ,演示如下所示:
如您還有不明白的可以在下面與我留言或是與我探討QQ群308855039,我們一起飛!
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。