jsp学习笔记day2

一、jsp基础语法

1、注释

显式注释语法:

<!--注释内容-->客户端可以看见

隐式注释语法:客户端不能看见

<%
    //单行注释
    /*多行注释*/
%>

2、
Scriptlet(脚本小程序)
  1. <%%>:主要用于定义局部变量、编写语句

  2. <%!%>:主要用于定义全局变量、方法、类,不能出现其他语句 
    尽量不要在JSP中定义类和方法

  3. <%=%>:表达式输出

<%
    String info = "www.baidu.com";
%>
<h1>website=<%=info%></h1>

3、
scriptlet标签
<jsp:scriptlet> String url="www.baidu.com"; </jsp:scriptlet> <h2><%=url%></h2>

4、page常用指令

   如下:

指令属性

描述

language

声明所使用的脚本语言,目前只有Java一种,所以可以不声明。

extends

指定JSP页面产生的Servlet继承的父类

import

指定所导入的包。(java.lang.*、javax.servlet.*、javax.servlet.jsp.*、和java.servlet.http.*几个包在程序编译时已经被导入,所以不需要特备声明)

session

指定JSP页面是否可以使用Session对象(默认值为session=”true”)。

buffer

指定缓冲区的大小,默认是8KB。如果为none,则表示不设置缓冲区。(此属性要和autoFlush一起使用)

autoFlush

指定输出缓冲区即将溢出时,是否强制输出缓冲区的内容。可以设置为true或false(默认为true)。

isThreadSafe

指定JSP是否支持多线程。可以设置为true或false,若为true,则表示该页面可以处理多个用户的请求;如果为false,则此JSP一次只能处理一个页面的用户请求。

info

设置JSP页面的相关信息。可以使用servlet.getServletInfo()方法获取到JSP页面中的文本信息。

ErrorPage

指定错误处理页面。当JSP出错时,会自动调用该指定所指定的错误处理页面。(此属性要和isErrorPage一起使用)

isErrorPage

指定JSP文件是否进行异常处理。可以设置为true或false,如果设置为true,则errorPage指定的页面出错时才能跳转到此页面进行错误处理。

contentType

指定JSP页面的编码方式和JSP页面响应的MIME类型(默认的MIME类型为text/html,默认的字符集类型为charset=ISO-8859-1)。例如:contentType=“text/html;charset=GBK”

pageEncoding

指定页面的编码方式。默认值为pageEncoding=“iso-8859-1”,若设为中文编码可以是pageEncoding=“GBK”。

isELIgnored

指定JSP文件是否支持EL表达式。

注释:对于以上属性,只有import属性可以多次出现,其他属性均只能出现一次。

 contentType设置MIME

MIME表示打开文件的应用程序类型, 
page指令中,contentType可以指定文件的显示方式 
例如:


<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@ page language="java" contentType="application/word;charset=GBK"%>

pageEncoding设置文件编码

charset是指服务器发送给客户端的内容编码,pageEncoding指的是JSP文件本身的编码。如果pageEncoding存在,那么JSP编码由pageEncoding决定,否则由charset决定,如果两个属性都不存在,则默认为ISO-8859-1 

例如:

<%@ page language="java" contengType="text/html;pageEncoding=GBK"%>

一般一个JSP页面只需要按照网页显示(text/html),则使用pageEncoding设置编码即可。

errorPage错误页的设置

错误页设置两步骤: 
1. errorPage属性指定错误出现时的跳转页; 
2. isErrorPage属性指定错误页标识

例如: 
错误页中:

<%@ page language="java" contengType="text/html;pageEncoding=GBK"%>
<%@page errorPage="error.jsp"%><!--一出现错误即跳转到错误处理页-->

错误处理页中:


<%@ page language="java" contengType="text/html;pageEncoding=GBK"%>
<%@ page isErrorPage="true"%><!--表示该页面用于处理错误-->

错误页跳转输入服务器端跳转


可以修改Web.xml文件,实现在虚拟目录指定全局的错误处理


<error-page>
    <error-code>500</error-code>
    <location>/ch05/error.jsp</location>
</error-page>

依然服务器端跳转

5、数据库操作

 1 <%@ page contentType="text/html" pageEncoding="GBK"%>
 2 <%@ page import="java.sql.*"%>
 3 <html>
 4     <head><title>www.bruce.com</title></head>
 5     <body>
 6         <%!
 7             //定义数据库驱动程序
 8             public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
 9             public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
10             public static final String DBUSER = "root";
11             public static final String DBPASS = "mysqladmin";
12         %>
13         <%
14             Connection conn = null;
15             PreparedStatement pstmt = null;
16             ResultSet rs = null;
17         %>
18         <%
19             try{
20                 Class.forName(DBDRIVER);
21                 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
22                 String sql = "SELECT empno,ename,job,sal,hiredate FROM emp";
23                 pstmt = conn.prepareStatement(sql);
24                 rs = pstmt.executeQuery();
25         %>
26         <center>
27             <table border="1" width="80%">
28                 <tr>
29                     <td>雇员编号</td>
30                     <td>雇员姓名</td>
31                     <td>雇员工作</td>
32                     <td>雇员工资</td>
33                     <td>雇员日期</td>
34                 </tr>
35                 <%
36                     while(rs.next()){
37                         int empno = rs.getInt(1);
38                         String ename = rs.getString(2);
39                         String job = rs.getString(3);
40                         float sal = rs.getFloat(4);
41                         java.util.Date date = rs.getDate(5);
42                 %>
43                     <tr>
44                     <td><%=empno%></td>
45                     <td><%=ename%></td>
46                     <td><%=job%></td>
47                     <td><%=sal%></td>
48                     <td><%=date%></td>
49                 </tr>
50                 <%
51                     }
52                 %>
53             </table>
54         </center>
55         <%
56             }catch(Exception e){
57                 e.printStack();
58             }finally{
59                 rs.close();
60                 pstmt.close();
61                 conn.close();
62             }
63         %>
64     </body>
65 </html>

6、包含指令

静态包含

语法:<%@ include file = "要包含的文件路径"%>

包含的文件可以是JSP,HTML,文本,或者是一段Java程序。包含操作实际上是将被导入的文件内容导入,一起进行编译,最后再将一份整体的内容展现给用户 
例如:

<body>

<%@include file="info.html"%>

</body>
动态包含

语法: 
1. 不传递参数: 
<jsp:include page="{要包含的文件路径\<%=表达式%>}" flush="true\false"/>

  1. 传递参数:
<jsp:include page="{要包含的文件路径\<%=表达式%>}" flush="true\false">
    <jsp:param name="参数名" value="参数内容"/>
    //可以传递多个参数
</jsp:include>

例如: 
包含页:include_demo.jsp

<jsp:include page="receive_param.jsp">
    <jsp:param name="name" value="<%=username>">
    <jsp:param name="info" value="Bruce">
</jsp:include>

被包含页:receive_param.jsp

<%@ page contentType="text/html" pageEncoding="GBK"%>
<h1>参数1:<%=request.getParameter("name")%></h1>
<h1>参数2:<%=request.getParameter("info")%></h1>

false表示完全被读进来再输出,true表示buffer满了就输出,一般都设置为true,默认为true 
动态包含是先处理再输出

7、跳转指令

语法: 
1. 不传递参数: 
<jsp:forward page="{要包含的文件路径\<%=表达式%>}"/> 
2. 传递参数:


<jsp:forward page="{要包含的文件路径\<%=表达式%>}">
    <jsp:param name="" value=""/>
    //可以传递多个参数
</jsp:forward>

上述跳转属于服务器端跳转

8、jsp九大内置对象

内置对象类型描述
pageContext javax.servlet.jsp.PageContext 页面容器
request javax.servlet.HttpServletRequest 请求
response javax.servlet.HttpServletResponse 回应
session javax.servlet.HttpSession 保存
application javax.servlet.ServletContext 共享信息
config javax.servlet.ServletConfig 服务器配置,可以取得初始化参数
out javax.servlet.jspWriter 页面输出
page java.lang.Object  
exception java.lang.Throwable

四种属性

属性名属性范围
page 只在一个页面中保存属性
request 一次请求中保存属性,服务器跳转后仍有效
session 一次会话范围中保存,任何跳转都有效,重新打开浏览器无效
application 整个服务器保存,所有用户都可以使用

 

4个内置对象都支持以下操作方法:

public void setAttribute(String name,Object o)
public Object getAttribute(String name)
public void removeAttribute(String name)

request对象

request对象主要作用是接收客户端发送来的请求,是javax.servlet.http.HttpServletRequest接口的实例化对象

常用方法描述
public String getParameter(String name) 接收请求参数
public String[] getParameterValues(String name) 接收一组请求参数
public Enumeration getParameterNames() 取得请求参数名
public String getRemoteAddr() 取得客户端IP地址
void setCharacterEncoding(String env)throws UnsupportedEncodingException 设置统一的请求编码
public boolean isUserInRole(String role) 用户身份认证
public Httpsession getSession() 取得当前的session对象
pubic StringBuffer getRequestURL() 返回正在请求的路径
pubic Enumeration getHeaderNames() 取得全部头信息的名称
pubic Enumeration getHeader(String name) 根据名称取得头信息的内容
public String getMethod() 取得用户的提交方式(get/post)
public String getServletPath() 取得访问的路径
public String getContextPath() 取得上下文资源路径
 

解决乱码

例如:

<body>
<%
    request.setCharacterEncoding("GBK");
%>
</body>

例如:接收表单全部内容 
定义表单页:request_form.html
 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 2 <html>
 3 <head>
 4 <title>request_form.html</title>
 5 </head>
 6 
 7 <body>
 8     <form action="request_demo.jsp" method="post"><!-- 用post,否则乱码 -->>
 9         姓名:<input type="text" name="uname"><br /> 兴趣:<input
10             type="checkbox" name="**inst" value="唱歌">唱歌<input
11             type="checkbox" name="**inst" value="跳舞">跳舞<input
12             type="checkbox" name="**inst" value="游泳">游泳<br /> 自我介绍:
13         <textarea cols="30" rows="3" name="note"></textarea>
14         <input type="hidden" name="uid" value="1"> <input
15             type="submit" value="提交"> <input type="reset" value="重置">
16         <br />
17     </form>
18 </body>
19 </html>

定义读取页:request_demo.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
 2 
 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4 <html>
 5 <head>
 6 <title>My JSP 'request_demo.jsp' starting page</title>
 7 </head>
 8 
 9 <body>
10     <%
11         request.setCharacterEncoding("GBK");//不能少,否则容易乱码
12     %>
13     <table border="1">
14         <tr>
15             <th>参数名称</th>
16             <th>参数内容</th>
17         </tr>
18         <%
19             Enumeration enu = request.getParameterNames();
20             while (enu.hasMoreElements()) {
21                 String paramName = (String) enu.nextElement();
22         %>
23         <tr>
24             <td><%=paramName%></td>
25             <td>
26                 <%
27                     if (paramName.startsWith("**")) {
28                             String paramValue[] = request
29                                     .getParameterValues(paramName);
30                             for (int i = 0; i < paramValue.length; i++) {
31                 %> <%=paramValue[i]%>32                 <%
33                             }
34                     } else {
35                             String paramValue = request.getParameter(paramName);
36                 %> 
37                     <%=paramValue%>
38                 <%
39                     }
40                 %>
41             </td>
42         </tr>
43         <%
44             }
45         %>
46 
47     </table>
48 </body>
49 </html>

显示全部头信息

<%@ page contextType="text/html" pageEncoding="GBK"%>
<%@ page import="java.util.*"%>
<html>
<head><title>取得头信息的名称和内容</title></head>
<body>
    <%
        Enumeration enu = request.getHeaderNames();
        while(enu.hasMoreElements()){
            String headerName = (String)enu.nextElement();
            String headerValue = request.getHeader(headerName);     
    %>
    <h5><%=headerName%>--><%=headerValue%></h5>
    <%
        }
    %>
</body>
</html>

角色验证

增加新用户需要修改conf/tomcat-user.xml文件。

<user username="10202357" password="Tu86511620" roles="admin" />

配置完之后还需要配置web.xml文件,在web.xml文件中加入对某一资源的验证操作

角色验证即在JSP页面中调用request.isUserInRole(“”)

response对象

response对象的主要作用是对客户端请求的响应,是javax.servlet.http.HttpServletResponse接口的实例

常用方法描述
public void addCookie(Cookie cookie) 给客户端增加Cookie
public void setHeader(String name,String value) 设置回应的头信息
public void sendRedirect(String location)throws IOException 页面跳转

 

设置头信息

例如: 
设置自动刷新:

<% reponse.setHeader("refresh","2") %>

定时跳转:

<% reponse.setHeader("refresh","2";URL="hello.html") %>

定时跳转(JSP response\HTML方式)都属于客户端跳转

例子
<html>
<head>
    <title>测试html页面的跳转</title>
    <META HTTP-EQUIV="refresh" CONTENT="3;URL=hello.html">
</head>
<body>
    <h3>
        3秒后跳转到hello.html页面,如果没有跳转请按<a href="hello.html">这里</a>!
    </h3>
</body>
</html>

当一个页面中没有JSP代码又想执行定时跳转的时候才使用HTML形式的设置跳转头信息

页面跳转

<% response.sendRedirect("01.html"); %>

<jsp:forward>不同,response属于客户端跳转,要在整个页面执行完以后才执行跳转。 
<jsp:forward>可以方便地进行参数传递,而且服务器端跳转要比客户端跳转更常用

操作cookie

Cookie的常用方法描述
public Cookie(String name,String value)  
public String getName()  
public String getValue()  
public void setMaxAge(int expiry) 设置Cookie的保存时间,以秒为单位

Cookie是服务器给客户端增加的,所以使用reponse对象 

例子

<%

           Cookie c1 = new Cookie("Tu","Bruce");//第一个参数是属性名,第二个参数是属性值

           c1.setMaxAge(60);//Cookie保存60秒

    response.addCoolie(c1);//向客户端增加Cookie

%>

例如:取出Cookie
<%
    Cookie c[] = request.getCookies();
    for(int x = 0; x < c.length; x++){
%>
    <h3><%=c[x].getName()%>--><%=c[x].getValue()%></h3>
<%
    }
%>  

session对象

在开发中session对象最主要的用处是完成用户的登录、注销等常见功能。

常用方法描述
public String getId() 取得Session Id
public long getCreationTime() 取得Session的创建时间
public long getLastAccessedTime() 取得Session的最后一次操作时间
public boolean isNew() 判断是否是新的Session
public void invalidate() 让Session失效
public Enumeration getAttributeNames() 得到全部属性的名称

登录与注销

实例: 
编写表单并进行验证login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>登录注销</title>
</head>

<body>
    <form action="login.jsp">
        用户名:<input type="text" name="uname" /></br>&nbsp;&nbsp;码:<input
            type="password" name="upass"> <input type="submit" value="登录">
        <input type="reset" value="重置">
    </form>
    <%
        String name = request.getParameter("uname");
        String password = request.getParameter("upass");
        if (!(name == null || "".equals(name) || password == null || ""
                .equals(password))) {
            if ("Bruce".equals(name) && "2222".equals(password)) {
                response.setHeader("refresh", "2,URL=welcome.jsp");
                session.setAttribute("userid", name);
    %>
    <h3>用户登录成功,两秒后跳转到欢迎页!</h3>
    <h3>
        如果没有跳转,请点击<a href="welcome.jsp">这里</a>
    </h3>
    <%
        } else {
    %>
    <h3>错误的用户名和密码</h3>
    <%
        }

        }
    %>
</body>
</html>

登录成功欢迎页welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>'welcome.jsp'</title>
</head>

<body>
    <%
        if (session.getAttribute("userid") != null) {
    %>
    <h3>
        欢迎<%=session.getAttribute("userid")%>光临本系统,<a href="logout.jsp">注销</a>
    </h3>
    <%
        } else {
    %>
    <h3>
        请先进行系统的<a href="login.jsp">登录</a>
    </h3>
    <%
        }
    %>
</body>
</html>

登录注销logout.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<html>
<head>
<title>'logout.jsp'</title>
</head>

<body>
    <%
        response.setHeader("refresh", "2;login.jsp");
        session.invalidate();
    %>
    <h3>你已经成功注销,两面后自动跳转回首页</h3>
    <h3>
        如果没有跳转,请点击<a href="login.jsp">这里</a>
    </h3>
</body>
</html>

判断新用户

<% session.isNew(); %>

取得用户的操作时间

<%

long start = session.getCreationTime();

long end = session.getLastAccessedTime();

long time = (end-start)/1000;//得出操作的秒

%>

application对象

常用方法描述
String getRealPath(String path) 得到虚拟目录对应的绝对路径
public Enumeration getAttributeNames() 得到所有属性的名称
public String getContextPath() 取得当前的虚拟路径名称

 

取得虚拟目录对应的绝对路径

<%

String path1 = application.getRealPath("/");

String path2 = this.getServletContext().getRealPath("/");//两个方法的结果一样

%>

 

例如:保存表单内容在Web项目的根目录中的note文件夹中

表单递交页面form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form.html</title>
</head>

<body>
    <form action="input.jsp">
        输入文件名称:<input type="text" name="filename"> 输入文件内容:
        <textarea name="filecontent" cols="30" rows="3"></textarea>
        <input type="submit" value="保存"> <input type="reset"
            value="重置">
    </form>
</body>
</html>
处理页面input.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title>My JSP 'input.jsp' starting page</title>
</head>

<body>
    <%
        String realPath = this.getServletContext().getRealPath("/");
    %>
    <h3><%=realPath%></h3>
    <%
        String name = request.getParameter("filename");
        String content = request.getParameter("filecontent");
        String fileName = this.getServletContext().getRealPath("/")
                + "note" + File.separator + name;
        File file = new File(fileName);
        if (!(file.getParentFile().exists())) {
            file.getParentFile().mkdir();
        }
        PrintStream ps = new PrintStream(new FileOutputStream(file));
        ps.println(content);
        ps.close();
    %>
</body>
</html>
类似用FileOutputStream也可以完成创建文件并写入,body体改为
<body>
    <%
        String realPath = this.getServletContext().getRealPath("/");
    %>
    <h3><%=realPath%></h3>
    <%
        String name = request.getParameter("filename");
        String content = request.getParameter("filecontent");
        String fileName = this.getServletContext().getRealPath("/")
                + "note" + File.separator + name + ".txt";
        File file = new File(fileName);
        if (!(file.getParentFile().exists())) {
            file.getParentFile().mkdir();
        }
        FileOutputStream fo = new FileOutputStream(file);
        byte b[] = content.getBytes();
        fo.write(b);
        fo.close();
    %>
</body>
结果一样。

网站计数器

<%@page import="java.io.*"%>
<%@page import="java.math.*"%>
<%@page import="java.util.*"%>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'Count.jsp' starting page</title>
</head>

<body>
    <%!BigInteger count = null;%>
    <%!//为了方便,方法直接定义放在在JSP文件中
    public BigInteger load(File file) {
        BigInteger count = null;
        try {
            if (file.exists()) {
                Scanner scan = new Scanner(new FileInputStream(file));
                if (scan.hasNext()) {
                    count = new BigInteger(scan.next());
                    scan.close();
                } 
            }else {
                    count = new BigInteger("0");
                    save(file, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }

    public void save(File file, BigInteger count) {
        try {
            PrintStream ps = null;
            ps = new PrintStream(new FileOutputStream(file));
            ps.println(count);
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }%>
    <%
        String filename = this.getServletContext().getRealPath("/")
                + "count.txt";
        File file = new File(filename);
        if (session.isNew()) {
            synchronized (this) {
                count = load(file);
                count = count.add(new BigInteger("1"));
                save(file, count);
            }
        }
    %>
    <h2>
        您是第<%=count%>位访客!
    </h2>
</body>
</html>

 











posted @ 2017-03-20 22:47  234陈壬询  阅读(184)  评论(0编辑  收藏  举报