第五章JSP(1)

第 1 节1-JSP概述

第 2 节2-JSP原理揭秘

第 3 节3-jsp中的page指令

第 4 节4-自定义错误页

第 5 节5-统一配置错误页

第 6 节6-JSP的几个所谓的内置对象

第 7 节7-用纯JSP实现人员列表


本章主干知识点:

1、JSP:JSP原理揭秘;JSP指令;

2、自定义错误页;全局错误页;

3、JSP内置对象;Servlet+JSP版CRUD;

4、forward和sendRedirect的区别

第 1 节1-JSP概述

 

JSP是一种“生成Servlet、简化Servlet编写”的技术,表现是“在jsp页面中写java代码”,本质是“自动生成Servlet”

 

第 2 节2-JSP原理揭秘

jsp运行原理

浏览器请求jsp页面资源——服务器接收并解析请求——jsp是否是第一次被请求

是:把jsp页面转换成.Java文件——把.Java文件编译成.class文件加载并创建对象

否:执行jsp类对象的业务逻辑方法

最后:生成响应并发送到浏览器

 

第 3 节3-jsp中的page指令

 

jsp语法

 

1.先不要写中文

2.<% ...  %>   jsp代码块 ,可以嵌入任意的有效的Java代码,一个jsp页面中可以嵌入任意多个代码块,转换时这些代码块会移动到jsp的业务逻辑方法中

<%

    int a = 0;

    System.out.print("hello hello");

    String username = (String)request.getParameter("username");

%>

3.<%= ... %>   jsp表达式 , 用来直接输出表达式的值,(没有分号),不是必须的语法<%=1+2+3+a+b %>方便我们向页面输出内容,相当于<% out.print(...); %>

 

4.新建一个简单jsp的方法:Other→MyEclipse→Web→JSP(Basictemplates)

 

5“MyEclipse Visual JSPDesigner”有可视化编辑界面,但是用不到,而且卡;换用“MyEclipse JSP Editor”,用“Open With”的方法打开。if problem...

 

JSP页面头

 

使用<%@ page language="java" import="java.util.*"pageEncoding="Utf-8"%> 声明页面编码

使用<%@page import="java.sql.ResultSet"%>在JSP中import类

如果写中文的话,必须把contentType、pageEncoding等都改成UTF-8。每次改都麻烦,一定有地方可以改,搜索Preferences。

 

探索JSP

 

查看根据jsp自动生成的Java代码的源码,查看tomcat的

work\Catalina\localhost\test2\org\apache\jsp文件夹下

明白了JSP的原理就更能明白怎么用了,不用讲都能猜出来。

 

JSP指令元素 -- page指令

 

指令元素page用来指定页面的某些特性

<%@ page   xxx="xxx" %>

language="java"

pageEncoding="UTF-8"  //指定页面保存时的编码方式   jsp文件的编码

contentType="text/html;charset=UTF-8"  //指定content-type响应头信息

         对应java文件中response.setContentType

import="java.util.*"

extends=""   //指定jsp继承的Servlet类,当继承自定义Servlet时使用

session="true"      //是否创建session

errorPage=""      //指定此jsp出错时跳转到的错误页面

isErrorPage="false"    //指定此jsp是错误处理页面

autoFlush="true"   //指定out对象的缓冲区是否自动刷新

buffer="8kb"          //指定out对象的缓冲区的大小

大部分都是直接翻译到.java中

 

第 4 节4-自定义错误页

 

1.目的:

         1、防止系统中的内部信息通过报错泄露给访问者;

         2、展示友好的报错页面,避免用户恐慌;

         3、有机会把程序中没有处理的异常记录下来,方便程序员发现错误。

 

2.在可能出错页面的page标签上errorPage="/Error.jsp"指定错误页。

3.Error.jsp的page标签中isErrorPage="true",这样才能使用exception对象,然后页面中显示“对不起出错了”,然后把异常信息保存到文件中。备注中

4.最好不要显示错误信息到页面上,避免被黑客恶意利用。

 

注意:是服务器内部把Error.jsp显示出来的,浏览器是不知道的。

 

【my1.jsp】

<%@ page language="java" 
import="java.io.FileOutputStream" errorPage="error.jsp"%>
<%@page contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8" %>
<%@page import="com.rupeng.web2.JdbcUtils"%>
<!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>111111111</title>
</head>
<body>
<%
JdbcUtils.executeQuery("select * from aaa");
%>
<br/>
<%=1+3+5*6 %>
</body>
</html>

【error.jsp】

<%@ page language="java" contentType="text/html; charset=UTF-8"
 isErrorPage="true" pageEncoding="UTF-8"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.OutputStreamWriter"%>
<%@page import="java.io.BufferedWriter"%>
<!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> 
对不起,系统处理出错,我们已经把错误信息发送给管理员!您 不用担心您的资金安全!
<%
FileOutputStream fos = new FileOutputStream("d:/error.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter bf = new BufferedWriter(osw);
bf.write(exception.toString());
bf.close();
osw.close();
fos.close();
 %>
</body>
</html>

第 5 节5-统一配置错误页

 

1.每个页面中都设置errorPage太麻烦,可以在web.xml中统一配置;可以写多组error-page,不同的异常由不同的页面处理。

         <error-page>

                  <exception-type>java.lang.Throwable</exception-type>

                  <location>/Error.jsp</location>

         </error-page>

2.还可以对不同的状态码由自定义页面进行处理,一般都是针对404.

         <error-page>

         <error-code>404</error-code>

         <location>/404.html</location>

         </error-page>

3.Location必须以/开头。

 

 

第 6 节6-JSP的9个所谓的内置对象

 

HttpServletRequest request

HttpServletResponse response

PageContext pageContext

HttpSession session

ServletContext application

ServletConfig config

JspWriter out
 page

Throwable exception

 

request、response、session、pageContext、session等,本质上都只是_jspService方法中的局部变量。NoMagic!

 

pageContext

页面上下文以得到任何你想要的

此页面可以访问的对象以及数据

setAttribuet(name, value)

getAttribute(name)

findAttribute(name)  //依次从pageContext ,request , session , application

                  //四个web域中查找name属性的值

 

【my1.jsp】

<%@ page language="java" 
import="java.io.FileOutputStream" isErrorPage="true"
    %>
<%@page contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8" %>
<%@page import="com.rupeng.web2.JdbcUtils"%>
<!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>111111111</title>
</head>
<body>

<%
request.setAttribute("a1","requestabc");
String v1 =  (String)request.getAttribute("a1");
out.println(v1+"<br/>");

pageContext.setAttribute("a2","pageContextabc");
//pageContext.setAttribute("a1","pageContexta1");
String v2 = (String)pageContext.getAttribute("a2");
out.println(v2+"<br/>");

//String v4 = (String)pageContext.getAttribute("a1");
//out.println(v4+"<br/>");

session.setAttribute("a3","sessionabc");
String v3 = (String)session.getAttribute("a3");
out.println(v3+"<br/>");

out.println("1:"+pageContext.findAttribute("a2")+"<br/>");
out.println("2:"+pageContext.findAttribute("a1")+"<br/>");
out.println("3:"+pageContext.findAttribute("a3")+"<br/>");

%>
<br/>
<%=1+3+5*6 %>
</body>
</html>

第 7 节7-用纯JSP实现人员列表

PersonList1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="com.rupeng.web2.JdbcUtils"%>
<!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>
<table>
	<thead>
		<tr><td>Id</td><td>姓名</td><td>年龄</td></tr>
	</thead>
	<tbody>
	<%
		ResultSet rs = JdbcUtils.executeQuery("select * from T_Persons2");
		while(rs.next())
		{
			int id = rs.getInt("Id");
			String name = rs.getString("Name");
			int age = rs.getInt("Age");
			//out.println("<tr><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>");
%>
	<tr><td><%=id %></td><td><%=name %></td><td><%=age %></td></tr>
<%
		}
	%>
</tbody>
</table>

</body>
</html>

总结:实际上是不会把访问数据等业务逻辑写在jsp上的

查看jsp的java代码明白原理。

 

自动生成的java    

【PersonList1_jsp.java】

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.sql.ResultSet;
import com.JdbcUtils2;

public final class PersonList1_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>人员列表</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("<table>\r\n");
      out.write("<thead>\r\n");
      out.write("\t<tr><td>Id</td> <td>姓名</td><td>年龄</td></tr>\r\n");
      out.write("</thead>\r\n");
      out.write("<tbody>\r\n");

	ResultSet  rs = com.JdbcUtils2.executeQuery("select * from T_Persons");
	while(rs.next())
	{
		int id = rs.getInt("Id");
		String name = rs.getString("Name");
		int age = rs.getInt("Age");
		//out.println("");

      out.write("\r\n");
      out.write(" \r\n");
      out.write(" <tr><td>");
      out.print(id );
      out.write("</td><td>");
      out.print(name );
      out.write("</td><td>");
      out.print(age );
      out.write("</td></tr>\t\r\n");
      out.write(" \r\n");

	}
	
      out.write("\r\n");
      out.write("\t\r\n");
      out.write("</tbody>\r\n");
      out.write("</table>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值