« 上一篇
个人整理非商业用途,欢迎探讨与指正!!
文章目录
- 6.JSP
- 6.1JSP的基本使用
- 6.2JSP的使用规则
- 6.3JSP内置对象
- 6.4错误页面的配置
- 6.4.1每个页面单独设置
- 6.4.2统一的错误页面设置
6.JSP
动态页面
Java Server Pages 基本Servlet的java服务页面(动态页面)
JSP之上可以编写java和html代码
6.1JSP的基本使用
<!-- jsp脚本 -->
<%@page import="com.qf.pojo.Book"%>
<%@ 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>Insert title here</title>
</head>
<body>
<a href="xxxServlet">跳转</a>
<!-- 在如下代码中编写java代码 -->
<%String str = "helloworld";/* 打印到后端控制台 */System.out.println(str);/* 打印到前端页面 */out.println(str);out.println("我叫王成輝");
%><%/* 在一个类的根部使用alt+/进行导包 */Book book = new Book(1,"钢铁是怎么样炼成","20.02");out.println(book);
%>
<br>
<!-- 直接输出某个内容 -->
<%=book %>
</body>
</html>
6.2JSP的使用规则
JSP和HTML一样,都可以作为视图,给用户展示页面信息的
不同点是JSP可以写Java代码
JSP的后缀为.jsp
使用<% java代码 %>作为语法
使用<%=变量 %>可以直接输出一个变量的值
JSP的本质是一个Java类
服务器可以将JSP自动的转换为Java类,在服务器的work文件夹下
JSP转换的核心代码
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)throws java.io.IOException, javax.servlet.ServletException {final javax.servlet.jsp.PageContext pageContext;javax.servlet.http.HttpSession session = null;final javax.servlet.ServletContext application;final javax.servlet.ServletConfig config;javax.servlet.jsp.JspWriter out = null;final java.lang.Object page = this;
6.3JSP内置对象
可以在JSP页面上直接使用的对象,在_jspService中已经定义好的对象
内置对象一共有9个
内置对象名 | 类型 | 说明 |
---|---|---|
request | HttpServletRequest | 表示当前页面的请求*** |
response | HttpServletResponse | 表示当前页面的响应 |
pageContext | PageContext | JSP的上下文,可以获取到当前JSP的任何信息 |
session | HttpSession | 表示浏览器和服务器之间的一次会话*** |
application | ServletContext | 表示当前的服务器,服务器上下文** |
config | ServletConfig | Servlet类的信息 |
out | JspWriter | JSP页面的输出流,等价与<%= %> |
page | Object | 当前页面对象(Object对象) |
exception | Throwable | 表示当前页面的错误信息 |
6.4错误页面的配置
6.4.1每个页面单独设置
<!-- 将当前页面声明为错误页面,所有的错误信息都向当前的页面跳转 -->
<%@ page isErrorPage="true"%>
<!-- 有错误的页面位置跳转 -->
<%@ page errorPage="error.jsp" %>
6.4.2统一的错误页面设置
在web.xml中进行设置
<error-page><error-code>404</error-code><location>/404.html</location>
</error-page><error-page><error-code>500</error-code><location>/500.html</location>
</error-page>