资源描述
1 What is JSP.
2 Why,Where and How JSP.
3 JSP Principle.
4 Base JSP(Statement,Script,Expression,Direction,Action).
5 JSP,Life cycle.
*******************************************
1 What is JSP.
1)什么是JSP
JSP: Java Server Page, Java EE组件,本质上是Servlet。
运行在Web Container.接收Http Request,生成Http Response
JSP使得我们能够分离页面的静态HTML和动态部分。
2 Why,Where and How JSP.
1)为什么需要JSP
Servlet: java class ---> out.println("<html>");
Jsp: script language ---> <html>
2)Jsp用在哪里
UI,表现层
Servlet----->Controll
图解JSP与Servlet的分工合作(比较没有JSP之前Servlet是如何唱独角戏)
a)单独使用Servlet。
b)单独使用JSP(Model 1)。
c)结合JSP和Servlet(Model 2)。
3)如何开发Jsp
Jsp文件后缀名--->.jsp
Jsp文件的组成--->html+jsp脚本元素(Java语言编写)
不用在web.xml中配置
http://localhost:8080/baseJSP/welcome.jsp
<%!String words="Welcome to our homepage,welcome to SD0702...";%>
<%=words%>
3 JSP Principle.
图解运行原理
4 Base JSP(Statement,Script,Expression,Direction,Action).
1)Jsp声明 <%! %>
声明类成员
<%!int i=100;%>
<%!String word="春田花花大学";%>
<%!private int counter=0;
public int count(){
return ++counter;
}
%>
<h1><%=count()%></h1>
2)Jsp脚本 <% %>
_jspService()中的局部代码
<%System.out.println("Hi,I like JSP.");%>
<%Connection conn=DriverManager.getConnection();
Statement st=con.createStatement();
String sql="select ...";
ResultSet rs=st.executeQuery(sql);
%>
比较
<%!int i=100;%> //成员变量
<%int i=100;%> //_jspService()方法中的局部变量
<%!public void hello(){}%>
<%public void hello(){}%> //error
3) 表达式 <%= %>
输出数据至页面的当前位置
<%="Hello,JSP world!"%>
<%=name%> //<%!String name="GiGi";%>
<%=new java.util.Date()%>
4)指令 <%@ %>
page
include
taglib
page指令---->import,session,isThreadSafe,errorPage,etc
import--->导入其它的包或类
<%@page import="java.util.Date"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*,java.io.*,.*"%>
session--->当前Jsp是否参与会话 default--->true
<%@page session="true"%> request.getSession();
<%@page session="false"%>
session="true"时,可用内建对象session直接访问会话
<%=session.getAttribute("name")%>
-----------以下属性不再使用---------------------------
isThreadSafe--->当前Jsp页面是否线程安全 default--->true
<%@page isThreadSafe="true"%> 普通的Servlet,可以并发处理用户请求
<%@page isThreadSafe="false"%> 相当于Servlet实现了SingleThreadModel
接口,不能并发处理请求(强烈要求禁止使用该属性)
-----------以上属性不再使用---------------------------
errorPage
isErrorPage--->Jsp页面中出现异常的处理方式
对于有可能出现异常的页面
<%@page errorPage="error.jsp"%>
对于处理异常的页面
<%@page isErrorPage="true"%> <%=exception%> 内建对象
contentType--->设置Jsp内容的MIME类型
<%@page contentType="text/html; charset=gbk"%>
等价于Servlet:response.setContentType("text/html; charset=gbk");
include指令--->file
把目标页面的内容包含到当前页面,产生页面叠加以后的输出效果
<%@include file="title.html"%>
<%@include file="booter.jsp"%>
在Jsp编译的时候被处理
taglib指令(放在JSTL处详细讲)
<%@ taglib uri=" prefix="tree" %>
<tree:gen/> //产生一个默认的树
自定义标签(可选)
5)动作 <jsp:actionName attributeName=attributeValue/>
jsp:forward
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
<jsp:forward page=""/>
<jsp:forward page="b.jsp"/>相当于Servlet中通过RequestDispatcher.forward()
还可以传参数
<jsp:forward page="b.jsp">
<jsp:param name="name" value="narci"/>
</jsp:forward>
<jsp:include page=""/>
<jsp:include page="b.jsp"/>相当于Servlet中通过RequestDispatcher.include()
与<%include file=""/>比较:动作在运行期处理
可以传参数
<jsp:include page="b.jsp" flush="true">
<jsp:param name="name" value="narci"/>
</jsp:include>
flush 属性
flush 指示在读入包含内容之前是否清空任何现有的缓冲区。
JSP 1.1 中需要 flush 属性,因此,如果代码中不用它,会得到一个错误。
但是,在 JSP 1.2 中, flush 属性缺省为 false。
由于清空大多数时候不是一个重要的问题,因此,
我的建议是:对于 JSP 1.1,将 flush 设置为 true;
而对于 JSP 1.2 及更高版本,将其设置为关闭。
Jsp中的注释:
a、java方格注释 编译器会忽略掉此类注释中的内容
<%--ur comments--%>
<%//ur comments%>
<%/*ur comments*/%>
<%//new java.util.Date()%>
b、html风格注释 编译器会执行此类注释中的代码
<!--ur comments-->
out.println("<!--ur comments-->")
<!--new java.util.Date()-->
例子:
1)关于外星人的问卷调查
我欢迎外星人进入我们的世界,帮助我们发展。
我害怕外星人,无法接受他们进入我们的世界。
外星人很神秘,我不知道存不存在外星人。
我喜欢听UFO的故事,但也许那只是一些很好玩的故事而已。
不要和我谈论外星人,地球人已经很复杂了。
如果有外星人,我想和他们说:
嘿嘿,我们可以做朋友么?
2)NumberGuess.jsp
猜一个数字,如果猜对显示恭喜信息,猜错则提示客户猜的数字太小还是太大了。
5 JSP,Life cycle(与Servlet的生命周期比较).
//JSP容器第一次装载jsp文件时调用一次
public void _jspInit(){
System.out.println(this.getClass()+":entering _jspInit()...");
}
//每个请求都要调用一次
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
}
//jsp文件被修改时,JSP容器会销毁旧的jsp文件对应的对象,
//重新装载一次更新后的jsp文件的内容(只调用一次)
public void _jspDestroy(){
System.out.println(this.getClass()+":entering _jspDestroy()...");
}
6.homework
1)好又多优惠政策
购买金额超过500 RMB 有90%折扣
购买金额超过1000 RMB 有85%折扣
购买金额超过1500 RMB 有80%折扣
购买金额超过2000 RMB 有75%折扣
购买金额超过10000 RMB 有70%折扣,赠送会员卡一张
2)九九乘法表
day2
1 Jsp调用JavaBean
2 异常处理
3 JAAS实现安全(可选)
**************************************************************
1 Jsp调用JavaBean
分离页面的显示代码和业务逻辑代码,将业务代码放到后台的Java Bean中。
减少了JSP中的脚本代码,便于维护和复用。
Java Bean:
1)无参数的构造方法(默认构造方法)
2)标准getter、setter方法
3)如果要支持RMI的,要实现Serializable
jsp:useBean--->在Jsp页面中使用一个JavaBean
<jsp:useBean id="" class="" scope=""/>
id:javaBean对象名
class:bean class的位置
scope:javaBean对象的共享范围(page,request,session,application)
page:当前页面范围
request:同一个请求范围 forward,include
session:同一个会话
application:同一个应用 ServletContext
JSP内建对象(直接可是使用,无需我们重新定义)
例子:Student
<jsp:useBean id="stu" class="vo.Student" scope="session"/>
等价于
<%
Student stu=(Student)session.getAttribute("stu");
if(stu==null){
stu=new Student();
session.setAttribute("stu",stu);
}
%>
可以用表达式获得bean的值
<%=stu.getName();%>
对JavaBean的属性赋值
1)<jsp:setProperty name="" property="" value=""/>
name:JavaBean对象名
property:JavaBean属性名
value:属性值
<jsp:setProperty name="stu" property="name" value="Bobo"/>
等价于
<%
stu.setName("Bobo");
%>
可以嵌套JSP表达式
<jsp:setProperty name="stu" proprty="name"
value='<%=request.getParameter("name")%>'/>
2)设置JavaBean的属性值
<jsp:setProperty name="" property="" param=""/>
param:对应着request中输入域的名
<form>
age:<input type="text" name="age"/>
...
</form>
package vo;
public class Student implements java.io.Serializable{
private String name;
public void setName(String name){this.name=name}
public void getName(){return name;}
...
}
<jsp:setProperty name="stu" property="age" param="age"/>
3)Java Bean中的属性名与form中输入域的名字保持一致的话,可以使用通配符*
一次设置所有字段的值。
<jsp:setProperty name="" property="*"/>
<form>
name:<input type="text" name="name"/>
sex:<input type="text" name="sex"/>
age:<input type="text" name="age"/>
</form>
package com;
public class Student implements java.io.Serializable{
private String name;
private String sex;
private int age;
public void setName(String name){this.name=name}
public void getName(){return name;}
...
}
<jsp:setProperty name="stu" property="*"/>
获得Java Bean的值
<jsp:getProperty name="" property=""/>
<jsp:getProperty name="abc" property="name"/>等价于 <%=abc.getName()%>
2 JSP中的异常处理
1)try/catch/finally/throws/throw
2)errorPage, isErrorPage
<%@page errorPage="error.jsp"%> 需要错误处理的页面
<%@page isErrorPage="true"%> 错误页面,有一个隐式对象exception可用
<%=exception%>
产生内建对象exception,可通过它获得异常信息
3)声明的方式处理异常
web.xml
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/MathError.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
RuntimeException:
java.lang.ArithmeticException
java.lang.NullPointerException
java.lang.ArrayIndexOutOfBoundsException
Java中的RuntimeException及其子类是不需要处理的(try/catch),因为所有的
RuntimeException总是可以通过优化代码来避免,
这种异常被称为“Unchecked Exception”。
思考:三种异常处理方式同时启动用,那个优先级高?
作用域越小,起作用的优先级越高。
Checked Exception
注意:要使得页面自动跳转到错误页面,必须关闭浏览器的“显示友好HTTP错误信息”选项
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
//只处理这两种兼容的异常
}
3 JAAS实现安全 Java EE规范之一,实现Java EE应用程序安全性的一个重要途径
Java Authentication and Authorization Service
Java认证(Authentication)与授权(Authorization)服务
(要求:会用!不要求深入理解)
Web端的认证方法有:BASIC、FORM、DIGEST、CERTIFACATE
1)在Tomcat Server中配置新用户与角色
%TOMCAT_HOME%/conf/tomcat-user.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="narci" password="11" roles="admin,manager"/>
<user username="lily" password="11" roles="manager"/>
</tomcat-users>
--------------------------------------------------------------------
为什么tomcat可以使用tomcat-user.xml作为它保存用户和角色信息的文件?
因为在server.xml中,有以下配置:
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
---------------------------------------------------------------------
2)声明安全性约束(指明受限资源)
web.xml
<security-constraint>
<display-name>Constraint-all</display-name>
<web-resource-collection>
<web-resource-name>all-resources</web-resource-name>
<description />
<url-pattern>/admin/*</url-pattern>
<url-pattern>/security/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<description />
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
3)选择认证方式(使用标准的FORM方式)
web.xml
如果是BASIC认证:5)步可以不用。
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>UserDatabaseRealm</realm-name>
</login-config>
如果是FORM认证:
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon/loginForm.jsp</form-login-page>
<form-error-page>/logon/loginErrorForm.jsp</form-error-page>
</form-login-config>
</login-config>
4)声明安全性角色及与用户的映射关系
web.xml
<security-role>
<description />
<role-name>admin</role-name>
</security-role>
5)标准的表单(FORM认证才需要)
action的值
用户名、密码字段的名称都是固定的(规范)
<form method="POST" action="j_security_check">
<input type="text" name="j_username">
<input type="password" name="j_password">
<input type="submit" value="Submit" name="B1">
</form>
标准的表单提交(固定不变):
action:j_security_check
name:j_username
password:j_password
练习:
使用JSP+Java Bean实现“学生管理系统”中的学生列表功能。
作业:
使用JSP+Java Bean完善课堂练习(CRUD),尝试使用JAAS加上访问控制
day3
1 内建对象
2 欢迎文件
3 MVC
********************************************************************
1 内建对象
JSP中的隐含对象:不用我们手工去创建的对象
// JspWriter out -- to write to the browser
// HttpServletRequest request -- the request object.
// HttpServletResponse response - the response object.
// PageContext pageContext -- the page context for this JSP
// HttpSession session -- the session object for the client (if any)
// ServletContext application -- The servlet (application) context
// ServletConfig config -- The ServletConfig for this JSP
// Object page -- the instance of this page's implementation class (i.e., 'this')
// exception <%@page isErrorPage="true"%>
四个范围对象:pageContext,request,session,application
<jsp:useBean id="stu" class="vo.Student" scope="session"/>
等价的代码
<%
Student stu=pageContext.getAttribute("stu");
if(stu==null) stu=new Student();
pageContext.setAttribute("stu",stu);
%>
//page,reqeust,session,application
<%
pageContext.setAttribute("name", "maxwell");
pageContext.setAttribute("sex", "m");
pageContext.setAttribute("age", "28");
request.setAttribute("name", "maxwell");
request.setAttribute("sex", "m");
request.setAttribute("age", "28");
session.setAttribute("name", "maxwell");
session.setAttribute("sex", "m");
session.setAttribute("age", "28");
application.setAttribute("name", "maxwell");
application.setAttribute("sex", "m");
application.setAttribute("age", "28");
%>
next.jsp
out:
<%out.println("Hello JSP!");%>
<%System.out.println("Hello JSP!");%>
getBufferSize() :tomcat default:8k
getRemaining()
flush()
clearBuffer()
request:
getProtocol()
getMethod()
getHeader("User-Agent")
getCookies() 返回的是一组Cookie
getRequestURI() --> 端口号后的路径
getRequestURL() --> http://...... 完整路径
getContextPath() --> Web的根目录
getServletPath() --> (/first.jsp)
getPathInfo()
getQueryString() --> ?后的路径(?method=list...)
isRequestedSessionIdFromCookie() -->判断sessionId师否用Cookie保存
isRequestedSessionIdFromURL() -->判断sessionId师否用URL保存
isRequestedSessionIdValid()
getLocalPort() -->服务器端口
getRemotePort() --> 本地端口
getRequestDispatcher(),setCharacterEncoding(),getInputStream()
session:
getId() -->获得sessionId
isNew() -->判断是否为第一次创建得
invalidate() -->使sessionId不生效(将sessionId销毁)
setMaxInactiveInterval(10)
response:
sendRedirect("third.jsp") 跳转到下个页面,请求发生了改变
encodeURL("second.jsp")
application:
log("some body visit our website...");
getMajorVersion()
getMinorVersion()
getServerInfo()
getRequestDispatcher(),getResourceAsStream(),getInitParameter()
pageContext:
getAttribute("name")
config:(可将JSP当成Servlet在web.xml中配置)
getInitParameter("classNo")
getServletName() -->
page:
getClass()
requestURI = contextPath + servletPath + pathInfo
a getContextPath
b getServletPath
c getPathInfo
2 欢迎文件
缺省情况下,一个Web App中的index.html,index.htm,index.jsp可作为默认的欢迎
文件.当用户请求没有指明要访问的资源时,Web Container会用欢迎文件响应客户端
请求.
手工设置欢迎文件
web.xml
找a.jsp,没找到,继续往下找
<welcome-file-list>
<welcome-file>/a.jsp</welcome-file>
<welcome-file>/b.jsp</welcome-file>
<welcome-file>/c.jsp</welcome-file>
</welcome-file-list>
3 MVC
优化Web App的结构,使用MVC模式
Model 1: JSP + JavaBean(EJB)
Model 2: Servlet + JSP + JavaBean(EJB)------>MVC
MVC: Model-View-Controller
采用MVC实现学生管理系统
day4
1 实现文件上传
2 数据验证
3 分页实现
*******************************************************************
1 实现文件上传
<form action="" method="POST" enctype="multipart/form-data">
file:<input type="file" name="file"/>
<br/>
<input type="submit"/>
</form>
观测HTTP Monitor
POST /fileUpload/upload.jsp HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: http://127.0.0.1:8082/fileUpload/
Accept-Language: zh-cn
Content-Type:multipart/form-data; boundary=---------------------------7d73e2c110626
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: 127.0.0.1
Content-Length: 234
Connection: Keep-Alive
Cache-Control: no-cache
-----------------------------7d73e2c110626
Content-Disposition: form-data; name="file"; filename="C:\Documents and Settings\Administrato
展开阅读全文