什么是JSP

一、什么是JSP

  JSP是由Sun公司倡导、许多公司参与而建立的动态网页技术标准。它在HTML代码中嵌入java代码片段(Scriptlet)和JSP标签,构成了JSP网页。在接收到用户请求时,服务器会处理java代码片段,然后生成处理结果的HTML页面返回给客户端,客户端的浏览器将呈现最终页面效果。

二、JSP技术特征

  1、跨平台
  2、业务代码分离
  3、组件重用(javabean)
  4、继承 Java Servlet功能
  5、预编译

三、page指令

1、language属性

  用于设置JSP页面使用的语言,目前只支持java语言,以后可能会支持其他语言,该属性默认值是java

2、extends属性

  用于设置 JSP页面继承的 Java类,所有 JSP页面在执行之前都会被服务器解析成 Servlet,而 Servlet是由 Java类定义的,所以 JSP和 Servlet都可以继承指定的父类。该属性并不常用,而且有可能影响服务器的性能优化。

3、import 属性

  用于设置 JSP导入的类包。JSP 页面可以嵌入 java代码片段,这些java代码在调用 API时需要导入相应的类包。

4、pageEncoding属性

  用于定义 JSP页面的编码格式,也就是指的文件编码。 JSP页面中的所有代码都使用该属性指的的字符集,如果该数据值为ISO-8859-1,那么这个jsp页面就不支持中文字符。通常设置编码格式为 GBK 或 UTF-8

5、contentType属性

  用于设置 JSP 页面的 MIME类型和字符编码,浏览去会据此显示网页内容。

<%@ 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>  
    这是我保存的jsp页面  
</body>  
</html>  

四、include指令

 该指令用于文件包含。该指令可以在 JSP页面中包含另一个文件的内容,但是它仅仅支持静态包含,也就是说被包含文件中的所有内容都被原样包含到该 JSP 页面中;如果被包含文件中有代码,将不被执行。被包含的文件可以是一段java代码、HTML代码或者是另一个 jsp页面。

一个index.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>Insert title here</title>  
</head>  
<body>  
    当前的日期是:  
    <%@ include file="date.jsp" %>>  
</body>  
</html>  

一个date.jsp

<%@ page import="java.util.Date" %>  
<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%   
    Date now=new Date();  

    String dateStr;  
    dateStr=String.format("%tY年%tm月%td日", now, now,now);  
%>  

<%=dateStr %>  

五、taglib指令

该指令用于加载用户自定义标签,使用该指令加载后的标签可以直接在 JSP 页面中使用。其语法格式为:

  <%@ taglib prefix="view" uri="/WEB-INF/tags/view.tld">  

六、java代码块

实现九九乘法表

<%@ 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>
    <%
        long startTime=System.nanoTime();
        for(int i=1;i<=9;i++){
            for(int j=1;j<=i;j++){
                String str=j+"x"+i+"="+(i*j);
                out.print(str+"&nbsp");
            }
            out.print("<br>");

        }
        long endTime=System.nanoTime()-startTime;
        /* out.println(endTime); */
    %>
    生成九九乘法表,用时<% out.println(endTime/1000);%>毫秒
</body>
</html>

七、JSP表达式

  JSP表达式可以直接把JAVA的表达式结果输出到JSP页面中。表达式的最终运算结果将被转换为字符串类型,因为在网页中显示的文字都是字符串,JSP表达式的语法格式为:(比如圆周率)

<%= Math.PI%>

具体实例代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

 <%-- 在java中定义一个方法<%! 方法实现 %> --%>
<%! 
    public String add(int a,int b){
        return ""+(a+b);
    }

%>   

<!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>
    圆周率是:<%=Math.PI%>
    <br>

    <!-- 将上述的方法显示在页面中 -->
    <%String sum=add(10,20); %>
    <input type="text" value="<%=sum %>">

</body>
</html>

运算结果为:

八、获取请求参数值

语法:

String request.getParameter(String parameter)

实例演示:从show.jsp获取index.jsp页面中的id值
index.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>Insert title here</title>
</head>
<body>
    <a href="show.jsp?id=001">获取id的值</a>
</body>
</html>

show.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>Insert title here</title>
</head>
<body>
 id的值为:<%=request.getParameter("id") %>
 <br>
 name的值为:<%=request.getParameter("name") %>
</body>
</html>

运行结果为:
  id的值为:001
  name的值为:null

九、获取Form表单信息

语法

String[] request.getParameterValues(String parameter)

具体实例演示
index.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>Insert title here</title>
</head>
<body>
    <form action="show.jsp" method="post">
        请输入用户姓名:<input type="text" name="name"><br>
        选择性别:<input type="radio" value="男" name="sex">男
        <input type="radio" value="女" name="sex">女
        <br>
        密码提示问题
        <select name="question">
            <option value="母亲的生日">母亲的生日</option>
            <option value="父亲的名字">父亲的名字</option>
        </select>
        <br>
        请输入问题答案:<input type="text" name="key"/><br>
        请选择个人爱好:
        <input type="checkbox" value="唱歌跳舞" name="like"/>唱歌跳舞
        <input type="checkbox" value="户外登山" name="like"/>户外登山
        <input type="checkbox" value="网上冲浪" name="like">网上冲浪
        <br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

show.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>Insert title here</title>
</head>
<body>
用户名:<%=new String(request.getParameter("name").getBytes("ISO8859_1"),"UTF-8") %><!-- 就是你从request获取的的name是使用ISO8859-1编码的,你想用utf-8重新编码,主要是为了避免乱码问题 -->
<br>
性别:<%=new String(request.getParameter("sex").getBytes("ISO8859_1"),"UTF-8") %>
<br>
密码提示问题:<%=new String(request.getParameter("question").getBytes("ISO8859_1"),"UTF-8") %>
<br>
问题答案:<%=new String(request.getParameter("key").getBytes("ISO8859_1"),"UTF-8") %>
<br>
个人爱好:<%
    String[] like=request.getParameterValues("like");
    for(int i=0;i<like.length;i++){
        %>
        <%=new String(like[i].getBytes("ISO8859_1"),"UTF-8")%>
        <%
    }
%>

</body>
</html>

运行结果为:

点击提交按钮之后:

十、获取请求客户端信息

request对象获取请求客户端信息

方法 返回值 说明
getHeader(String name) String 返回指定名称的Http头信息
getMethod() String 获取客户端服务器发送请求的方法
getContextPath() String 返回请求路径
getProtocol() String 返回请求使用的协议
getRemoteAddr() String 返回客户端地址
getRemoteHost() String 返回客户端主机名称
getRemotePort() int 返回客户端发出请求的端口号
getServletPath() String 返回接受客户提交信息的页面
getRequestURI() String 返回部分客户端请求的地址,不包括请求的参数
getRequestURL() StringBuffer 返回客户端请求地址

实例演示:
创建客户端client.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>Insert title here</title>
</head>
<body>
    <ul>
        <li>客户端使用协议:<%=request.getProtocol() %>
        <li>客户端发送请求方法:<%=request.getMethod() %>
        <li>客户端请求路径:<%=request.getContextPath() %>
        <li>客户端IP地址:<%=request.getRemoteAddr() %>
        <li>客户端主机名称:<%=request.getRemoteHost() %>
        <li>客户端端口号:<%=request.getRemotePort() %>
        <li>接收客户信息的页面:<%=request.getServletPath() %>
    </ul>
</body>
</html>

运行结果为:
  客户端使用协议:HTTP/1.1
  客户端发送请求方法:GET
  客户端请求路径:/MyWebTest
  客户端IP地址:0:0:0:0:0:0:0:1
  客户端主机名称:0:0:0:0:0:0:0:1
  客户端端口号:4999
  接收客户信息的页面:/index.jsp

十一、在作用域中管理属性

request对象在作用域中管理属性
  语法

Object request.setAttribute(String name,Object value)  

比如:
  request.setAttribute(“date”,new Date());//添加一个属性

演示代码:

<%@ page import="java.util.Date" %>
<%@ 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>
    <%request.setAttribute("date", new Date()); %>
    <ul>
        <li>获取date属性:<%=request.getAttribute("date") %>
        <br>
        <!-- 删除date属性 -->
        <%request.removeAttribute("date"); %>
        <li>删除之后获取date属性:<%=request.getAttribute("date") %>
    </ul>

</body>
</html>

运行结果为:
  获取date属性:Sun May 20 10:10:39 CST 2018
  删除之后获取date属性:null

十二、cookie管理

 cookie是小段的文本信息,通过使用cookie可以标识用户身份、记录用户名及密码、跟踪重复用户。cookie在服务器生成并发送给浏览器,浏览器将cookie的key/value保存到某个指定的目录中,服务器的名称与值可以有服务器端定义。
  通过cookie的getCookies()方法可以获取到所有的cookie对象集合,然后通过cookie对象的getName()方法获取到指定名称的cookie,再通过getValue()方法即可获取到cookie对象的值。另外,将一个cookie对象发送到客户端使用了response对象的addCookie()方法。

实例演示:
  在index.jsp中读取cookie,在show.jsp中添加cookie
index.jsp

<%@ page import="java.util.Date" %>
<%@ 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>
    <!-- 读取cookie -->
    <%
        String welcome="第一次访问";
        String[] info=new String[]{"","",""};
        Cookie[] cook=request.getCookies();
        if(cook!=null){
            for(int i=0;i<cook.length;i++){
                if(cook[i].getName().endsWith("abcCookInfo")){
                    info=cook[i].getValue().split("#");
                    welcome="欢迎回来!";
                }
            }
        }
    %>
    <!-- 打印用户信息 -->
    <%=info[0]+welcome %>

    <!-- 表单信息 -->
    <form action="show.jsp" method="post">
        姓名:<input type="text" name="name" value="<%=info[0] %>"/><br>
        生日:<input type="text" name="birthday" value="<%=info[1] %>"/><br>
        邮箱:<input type="text" name="email" value="<%=info[2] %>"/><br>

        <input type="submit"  value="提交"/>
    </form>
</body>
</html>

show.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>Insert title here</title>
</head>
<body>
 <%
    String name=request.getParameter("name");
    String birthday=request.getParameter("birthday");
    String email=request.getParameter("email");

    /* 将这三个值写到cookie里,也即是添加cookie*/
    Cookie myCookie=new Cookie("abcCookInfo",name+"#"+birthday+"#"+email);
    response.addCookie(myCookie);
 %>
    <ul>
        <li>姓名:<%=name %>
        <li>生日:<%=birthday %>
        <li>邮箱:<%=email %>
        <li><a href="index.jsp">返回</a>
    </ul>
</body>
</html>

运行结果为:

十三、response对象

response对象常用方法

方法 返回值 说明
addHeader(String name,String value) void 添加HTTP文件头,如果同名的头存在,则覆盖
setHeader(String name,String value) void 设定指定名称的文件并头的值,如果存在则覆盖
addCookie(Cookie cookie) void 向客户端添加一个cookie对象
sendError(int sc,String msg) void 向客户端发送错误信息。例如:404网页找不到
sendRedirect(String location) void 发送请求到另一个指定位置
getOutputStream() ServletOutputStream 获取客户端输出流对象
setBufferSize(int size) void 设置缓冲区大小

1、重定向
  重定向是通过使用sendRedrect()方法,将响应发送到另一个指定的位置进行处理

  比如:
    response.sendRedirect(“www.baidu.com”);
2、处理HTTP文件头
  setHeader()方法通过两个参数–头名称与参数值的方法来设置HTTP头文件。
  比如:

设置网页每5秒自动刷新一次
response.setHeader("refresh","5");
设置2秒钟后自动跳转至指定的页面
response.setHeader("refresh","2;URL=welcom.jsp");

十四、session对象

 session是与请求有关的会话对象,是java.servlet.http.HttpSession对象,用于保存和存储页面的请求信息。
  session对象的setAttribute()方法可以实现将信息保存在session范围内,而通过getAttribute()方法可以获取保存在session范围内的信息。
示例:

String sessionMessage="session练习";
session.setAttribute("message",sessionMessage);


String message=(String)session.getAttribute("message");
out.print("保存在session范围内的值为:"+message);

移除指定的绑定对象
  removeAttribute(String key)
  
销毁session
  session.invalidate();

十五、application对象

  application对象可将信息保存在服务器中,直到服务器关闭,否则application对象中保存的信息会在整个应用中都有效。与session对象相比,application对象的声明周期更长,类似于“全局变量”。
  
application对象的常用方法

方法 返回值 说明
getAttribute(String name) Object 通过关键字返回保存在application对象中的信息
getAttributeNames() Enumeration 获取所有application对象使用的属性名
setAttribute(String key,Object obj) void 通过指定的名称将一个对象保存在application对象中
getMajorVersion() int 获取服务器支持的Servlet版本号
getServerInfo() String 返回JSP引擎的相关信息
removeAttribute(String name) void 删除application对象中指定名称的属性
getRealPath() String 返回虚拟路径的真实路径
getInitParameter(String name) String 获取指定name的application对象属性的初始值

程序演示:
在web.xml中配置

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyWebTest</display-name>

  <context-param>
    <param-name>url</param-name>
    <param-value>localhost:3306</param-value>
  </context-param>
  <context-param>
    <param-name>name</param-name>
    <param-value>root</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>123456</param-value>
  </context-param>


  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在index.jsp中获取application的初始值

<%@ page import="java.util.Date" %>
<%@ 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>
    <form action="show.jsp" method="post">

        <%
            String url=application.getInitParameter("url");
            String name=application.getInitParameter("name");
            String password=application.getInitParameter("password");

            out.println("URL:"+url);
            out.println("Name:"+name);
            out.println("Password:"+password);          
        %>      
    </form>
</body>
</html>

运行结果为:
  URL:localhost:3306
  Name:root
  Password:123456
  
总结:
  application对象与session对象相同,也可以在application对象中设置属性。与session对象不同的是,session只是当前客户的会话范围内有效,当超过保存时间,session对象就被收回;而application对象在整个应用区域中都有效。application对象管理应用程序环境属性的方法分别介绍如下。
实例演示

功能:
  用JSP实现用户登陆验证的功能。如果用户输入正确的账号密码,则提示文化语句,如果用户输入的错误账号密码,则提示账号密码有误。

<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
    String str=request.getParameter("username");
    String pwd=request.getParameter("pwd");
    if(str!=null){
        if(str.equals("jim") && pwd.equals("123")){
            out.println("你好,jim");
        }else{
            out.println("您输入的账号密码有误,请重新输入!");
        }
    }
%>

<!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>
    <form action="index.jsp" method="post">
        账号:<input type="text" name="username"><br>
        密码:<input type="password" name="pwd"><br>
        <input type="submit" value="登陆">
    </form>
</body>
</html>

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以加QQ(2602138376)

文章标题:什么是JSP

文章字数:4.9k

本文作者:Zevs

发布时间:2019-09-03, 22:29:18

最后更新:2019-09-04, 18:11:42

原始链接:http://zhsh666.xyz/2019/09/03/什么是JSP/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏

相册 图床 主题切换