Java后端

JavaWeb-不得不学习的Jsp

2018-03-13  本文已影响95人  付凯强

0. 引言

1. 安装Tomacat

2. Tomcat闪退

3. Tomcat目录结构

Tomcat目录结构.png

4. 编写第一个java web程序

<HTML>

<head> 
<title>我的第一个jsp页面</title>
</head>

<body>

<h1>欢迎大家访问我的个人主页</h1>

</body>

</HTML>

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

</web-app>
1. 在webapps下创建项目目录
2. 编写index.jsp
3. 创建WEB-INF目录
4. 测试运行

5. WEB-INF目录结构详解

1. 在WEB-INF里面创建test.html文件
2. 访问http://172.25.164.79:8080/myhome/WEB-INF/test.html
HTTP Status 404 -
type Status report

message

description The requested resource is not available.

Apache Tomcat/7.0.85
1. 访问:http://172.25.164.79:8080/myhome/ 会默认访问项目myhome文件夹下面的index.jsp
2. 修改index.jsp名字为abc.jsp 访问:http://172.25.164.79:8080/myhome/
HTTP Status 404 - /myhome/
type Status report

message /myhome/

description The requested resource is not available.

Apache Tomcat/7.0.85
3. 在web.xml中配置欢迎页面后,即可访问abc.jsp:
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <welcome-file-list>
        <welcome-file>/abc.jsp</welcome-file>
    </welcome-file-list>

</web-app>

6. IDEA 配置服务器并关联项目(创建了第一个jsp项目)

7. JSP简介

8. JSP特点

9. JSP页面元素构成

10. 指令分类

11. page指令:

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

1. language:制定JSP页面使用的脚本语言。默认值:java
2. import:通过该属性来引用脚本语言中使用到的类文件。默认值:无
3. contentType:用来指定JSP页面所采用的编码方式。默认值:text/html,ISO-8859-1

12. JSP注释

    <%--这是title标签--%> //客户端不可见的
    <!--html注释--> //客户端可见
    //单行注释
   /*
   多行注释
    */

13. JSP脚本

在JSP页面中执行的java代码
<%
   out.println("我只不过想做一个好人");
%>

这句代码在idea里面不会自动提示生成,而eclispe会。

14. JSP声明

在JSP页面中定义变量和方法
<%!
    String s = "张三丰"; //声明了一个字符串变量

    int add(int x, int y) { //声明了一个返回整形的函数,实现两个整数的求和
        return x + y;
    }
%>

15. JSP表达式

在JSP表达式中可以用到声明中声明的变量和函数
你好<%=s %>
<br>
5+6 = <%=add(5, 6)%>

16. JSP的生命周期

JSP页面的声明周期.png
JSP生命周期详述.png

17. 用脚本打印九九乘法表

<%! String printForm99() {
    String s = "";
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            s += i + "*" + j + "=" + i * j + "&nbsp;";
        }
        s += "<br>";
    }
    return s;
}
%>
<%=printForm99() %>
1*1=1 
2*1=2 2*2=4 
3*1=3 3*2=6 3*3=9 
4*1=4 4*2=8 4*3=12 4*4=16 
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 

18. JSP的内置对象简介

19.JSP九大内置对象

比如out对象:
<%
    int[] value = {1, 2, 3};
    for (int i : value) {
        out.print(i);
    }
%>

20. Web程序的请求响应模式

登录:
输入账号和密码,登录:相当于请求
服务器接收账号和密码后判断是否合法,跳转到响应页面:相当于reponse

21. 什么是缓冲区

一锅米饭一粒一粒吃——米饭一碗一碗吃——这个碗就是缓冲区

22. out对象

1. void println 向客户端打印字符串
2. void clear 清除换成从去的内容,如果在flust之后调用会抛出异常
3. void clearBuffer();清除缓冲区的内容,如果在flush之后调用不会抛出异常
4. void flush() 将缓冲区内容输出到客户端
5. int getBufferSize() 返回缓冲区以字节数的大小,如不设缓冲区则为0
6. int getRemaining()返回缓冲区还剩余多少可用
7. boolean isAutoFulsh() 返回缓冲区满时,时自动清空还是抛出异常
8. void close() 关闭输出流
<%
    int[] value = {1, 2, 3};
    for (int i : value) {
        out.print(i);
    }
%>
缓冲区大小:<%=out.getBufferSize()%>byte<br>
缓冲区剩余大小:<%=out.getRemaining()%>byte<br>
是否自动清空缓冲区:<%=out.isAutoFlush()%><br>

缓冲区大小:8192byte
缓冲区剩余大小:8101byte
是否自动清空缓冲区:true
<%
    out.println("<h2>静夜思</h2>");
    out.println("窗前明月光<br>");
    out.println("疑是地上霜<br>");
    out.println("举头望明月<br>");
    out.println("低头思故乡<br>");
%>
缓冲区大小:<%=out.getBufferSize()%>byte<br>
缓冲区剩余大小:<%=out.getRemaining()%>byte<br>
是否自动清空缓冲区:<%=out.isAutoFlush()%><br>
静夜思
窗前明月光
疑是地上霜
举头望明月
低头思故乡
缓冲区大小:8192byte
缓冲区剩余大小:8046byte
是否自动清空缓冲区:true
<%
    out.println("<h2>静夜思</h2>");
    out.println("窗前明月光<br>");
    out.println("疑是地上霜<br>");
    out.flush();
    out.println("举头望明月<br>");
    out.println("低头思故乡<br>");
%>
缓冲区大小:<%=out.getBufferSize()%>byte<br>
缓冲区剩余大小:<%=out.getRemaining()%>byte<br>
是否自动清空缓冲区:<%=out.isAutoFlush()%><br>
静夜思
窗前明月光
疑是地上霜
举头望明月
低头思故乡
缓冲区大小:8192byte
缓冲区剩余大小:8142byte
是否自动清空缓冲区:true

说明:因为执行了flush,所以缓冲区变大了
<%
    out.println("<h2>静夜思</h2>");
    out.println("窗前明月光<br>");
    out.println("疑是地上霜<br>");
    out.flush();
    out.clear();
    out.println("举头望明月<br>");
    out.println("低头思故乡<br>");
%>
缓冲区大小:<%=out.getBufferSize()%>byte<br>
缓冲区剩余大小:<%=out.getRemaining()%>byte<br>
是否自动清空缓冲区:<%=out.isAutoFlush()%><br>
静夜思
窗前明月光
疑是地上霜

说明:out.clear()不能在out.flush()之后调用否则会抛出异常,后面的代码不会执行,但是out.clearBuffer()不会抛出异常。

23. 表单提交方式get和post的区别

表单提交方式get和post的区别.png

24. request对象(上)

1. String getParameter(String name):返回name指定参数的参数值(返回单个值)
2. String[] getParameterValues(String name):返回包含参数name的所有值的数组(返回集合)
3. void setAttribute(String,Object):存储此请求中的属性。
4. object getAttribute(String name):返回指定属性的属性值。
5. String getContentType():得到请求体的MIME类型
6. String getProtocol():返回请求用的协议类型和版本号
7. String getSeverName():返回接受请求的服务器主机名
index.jsp文件:

<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: fukq
  Date: 2018/3/7
  Time: 14:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<HTML>

<head>
    <title>我的个人主页</title>
</head>

<body>
<h1>用户注册</h1>
<form name="reqForm" action="request.jsp" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td>爱好:</td>
            <td>
                <input type="checkbox" name="favorite" value="read">读书
                <input type="checkbox" name="favorite" value="music">音乐
                <input type="checkbox" name="favorite" value="movie">电影
                <input type="checkbox" name="favorite" value="internet">上网
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="提交"/></td>
        </tr>
    </table>
</form>
</body>

</HTML>
request.jsp文件:

<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: fukq
  Date: 2018/3/7
  Time: 14:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<HTML>

<head>
    <title>我的个人主页</title>
</head>

<body>
<h1>request内置对象</h1>
用户名:
<%=request.getParameter("username")%><br>
爱好:
<%
    String[] favorites = request.getParameterValues("favorite");
    if (favorites != null) {
        for (int i = 0; i < favorites.length; i++) {
            out.println(favorites[i] + "&nbsp;&nbsp;");
        }
    }
%>
</body>

</HTML>
request内置对象
用户名: ä»�å�¯å¼º
爱好: read   music   movie   internet  
获取表单数据出现中文乱码的解决办法是在体交表单的时候:
<%
    request.setCharacterEncoding("utf-8");
%>
request内置对象
用户名: 付凯强
爱好: read   music  
<a href="request.jsp?username= lisi">测试URL传递参数</a>
用户名: lisi
<a href="request.jsp?username= 中文">测试URL传递参数</a>
用户名: 中æ��
但是通过request设置参数无法解决URL传递中文出现的乱码问题
但是通过配置Tomcat服务器里面conf-server.xml文件可以解决
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="utf-8"/>

25. request对象(下)

<%
    request.setCharacterEncoding("utf-8");
    request.setAttribute("password","123456");
%>
密码:<%=request.getAttribute("password")%>
密码:<%=request.getAttribute("password")%> <br>
请求的MIME类型:<%=request.getContentType()%><br>
协议类型及版本号:<%=request.getProtocol()%><br>
服务器主机名:<%=request.getServerName()%><br>
服务器端口号:<%=request.getServerPort()%><br>
请求文件的长度:<%=request.getContentLength()%><br>
请求文件的ip地址:<%=request.getRemoteAddr()%><br>
请求的真实路径:<%=request.getRealPath("request.jsp")%><br>
请求的上下文路径:<%=request.getContextPath()%><br>
request内置对象
用户名: 您好好
爱好: music   movie   internet   密码:123456 
请求的MIME类型:application/x-www-form-urlencoded
协议类型及版本号:HTTP/1.1
服务器主机名:localhost
服务器端口号:8888
请求文件的长度:84
请求文件的ip地址:127.0.0.1
请求的真实路径:G:\javaSpace\webDemo\out\artifacts\firstweb_war_exploded\request.jsp
请求的上下文路径:/fkq

26. response对象简介

27. response对象常用方法如下:

<%@ page import="java.util.List" %>
<%@ page import="java.io.PrintWriter" %><%--
  Created by IntelliJ IDEA.
  User: fukq
  Date: 2018/3/7
  Time: 14:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    response.setContentType("text/html;charset=UTF-8"); //设置响应的MIMI类型

    out.println("<h1>reponse对象</h1>");
    out.println("<hr>");

    PrintWriter outer  = response.getWriter();
    outer.println("大家好,我是response对象生成的输出流outer对象");
%>
PrintWriter对象总是提前于内置的out对象打印
<%@ page import="java.util.List" %>
<%@ page import="java.io.PrintWriter" %><%--
  Created by IntelliJ IDEA.
  User: fukq
  Date: 2018/3/7
  Time: 14:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    response.setContentType("text/html;charset=UTF-8"); //设置响应的MIMI类型

    out.println("<h1>reponse对象</h1>");
    out.println("<hr>");
    out.flush();
    PrintWriter outer  = response.getWriter();
    outer.println("大家好,我是response对象生成的输出流outer对象");
%>
out.flush();刷新缓冲区,刷新的时候会把数据刷新到浏览器上。
<%
    response.setContentType("text/html;charset=UTF-8"); //设置响应的MIMI类型

    out.println("<h1>reponse对象</h1>");
    out.println("<hr>");

    PrintWriter outer  = response.getWriter(); //获得输出流对象
    outer.println("大家好,我是response对象生成的输出流outer对象");

    response.sendRedirect("index.jsp"); //请求重定向
%>

28. 请求重定向与请求转发

29. session简介

30. session详细介绍

31. session常用方法

Session创建时间:<%=session.getCreationTime()%><br>
Session创建时间:1520565423914
<%!
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
%>
Session创建时间:<%=simpleDateFormat.format(new Date(session.getCreationTime()))%><br>
Session创建时间:2018年03月09日 11:17:03
session.setAttribute("username","admin");
从Session中获取用户名:<%=session.getAttribute("username")%>
从Session中获取用户名:admin
session_page1: 

<%!
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
%>
<%
    session.setAttribute("username", "admin");
%>
Session创建时间:<%=simpleDateFormat.format(new Date(session.getCreationTime()))%><br>
Session的ID编号:<%=session.getId()%><br>
从Session中获取用户名:<%=session.getAttribute("username")%>

<a href="session_page2.jsp" target="_blank">跳转到Session_page2.jsp</a>
session_page2:

<body>
<h1>session内置对象</h1>
<hr>
Session的ID编号:<%=session.getId()%><br>
从Session中获取用户名:<%=session.getAttribute("username")%>
</body>
session_page1: 

Session的ID编号:866631F646E26184FB1F4FCC3AAB4AE6
session_page2:

Session的ID编号:866631F646E26184FB1F4FCC3AAB4AE6
从Session中获取用户名:admin

page1跳转到page2,id编号一致;只有关闭相关的两个页面,才表示会话结束。
<%
    session.setAttribute("username", "admin");
    session.setAttribute("password","123456");
    session.setAttribute("age","5");
%>
Session中保存的属性有:
<%
    String[] names = session.getValueNames();
    for (int i = 0; i < names.length; i++) {
        out.println(names[i] + "&nbsp;&nbsp;");
    }
%>
Session的ID编号:9E503181AE514CD3C56EDD9289DCE286
从Session中获取用户名:admin Session中保存的属性有: password   age   username  
session.setMaxInactiveInterval(10);

32. session的生命周期

33. Session对象的超时

<session-config>
<session-timeout>
10
</session-timeout>
</session-config> //单位是分

34. application对象

35. application对象的常用方法

<%
    application.setAttribute("username", "fukq");
    application.setAttribute("age", "123");
    application.setAttribute("sex", "男");
%>
名字是:<%=application.getAttribute("username")%>
application中的属性有:
<%
    Enumeration enumeration = application.getAttributeNames();
    while (enumeration.hasMoreElements()) {
        out.println(enumeration.nextElement() + "&nbsp;&nbsp");
    }
%><br>
JSP(SERVLET)引擎名及版本号:    <%=application.getServerInfo()%><br>
名字是:fukq 
application中的属性有: javax.servlet.context.tempdir   org.apache.catalina.resources   org.apache.tomcat.util.scan.MergedWebXml   org.apache.tomcat.InstanceManager   sex   org.apache.catalina.jsp_classpath   org.apache.jasper.compiler.ELInterpreter   org.apache.jasper.compiler.TldLocationsCache   org.apache.tomcat.JarScanner   javax.websocket.server.ServerContainer   age   org.apache.jasper.runtime.JspApplicationContextImpl   username   
JSP(SERVLET)引擎名及版本号Apache Tomcat/7.0.85

36. page对象

page对象.png

page对象的常用方法与object对象的常用方法是基本一致的:

当前page页面对象的字符串描述:   <%=page.toString()%>
当前page页面对象的字符串描述: org.apache.jsp.page_jsp@7c5d9ae
toString 打印的实际是对象的hashcode值

37. pageContext对象

38. pageContext对象常用方法

    session.setAttribute("username", "admin");
    session.setAttribute("password", "123456");
    session.setAttribute("age", "5");
用户名是:<%=pageContext.getSession().getAttribute("username")%><br>
用户名是:admin
//包含这个页面
    pageContext.include("index.jsp");
//跳转到其他页面
//    pageContext.forward("index.jsp");

39. Config对象

40. exception对象

41. exception常用方法

errorPage="exception.jsp"

<% System.out.print(1 / 0);%>
 isErrorPage="true"
 
 异常的消息是: <%=exception.getMessage()%> <br>
异常的字符串描述是:<%=exception.toString()%><br>

42. 用户登录小栗子

login.jsp页面:

<h1>登录小案例</h1>
<form action="dologin.jsp" method="post">
    <p class="main">
        <label>用户名: </label>
        <input name="username" value=""/>
        <label>密码: </label>
        <input type="password" name="password" value="">
    </p>
    <p class="space">
        <input type="submit" value="登录"/>
    </p>
</form>
dologin.jsp页面
<%
    String username = "";
    String password = "";
    request.setCharacterEncoding("utf-8"); //防止中文乱码

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

    //如果用户和密码都等于admin,则登录成功
    if ("admin".equals(username) && "admin".equals(password)) {
        session.setAttribute("loginUser", username);
        request.getRequestDispatcher("login_success.jsp").forward(request, response);
    } else {
        response.sendRedirect("login_failure.jsp");
    }
%>
login_success页面
    <%
        String loginUser = "";
        if (session.getAttribute("loginUser") != null) {
            loginUser = session.getAttribute("loginUser").toString();
        }
    %>

login_failure页面
    欢迎<%=loginUser%>登录成功!
<div>登录失败,请检查用户名或密码<br>
    <a href="login.jsp">返回登录</a>
</div>

43. Javabean简介

44. Javabean设计原则

45. Jsp动作元素

46. Jsp动作分类

<jsp:useBean><jsp:setProperty><jsp:getProperty>
<jsp:include><jsp:forward><jsp:param><jsp:plugin><jsp:params><jsp:fallback>
<jsp:root><jsp:declaration><jsp:scriptlet><jsp:expression><jsp:text><jsp:output>
<jsp:attribute><jsp:body><jsp:element>
<jsp:invoke><jsp:dobody>

47. 普通方式创建JavaBean

<%@ page import="com.test.User" %> 
<%
    User user = new User();
    user.setmUserName("admin"); //设置用户名
    user.setmPassword("123456");//设置密码
%>
账户名是: <%=user.getmUserName()%>
密码是:<%=user.getmPassword()%>

48. Jsp页面中使用jsp动作标签使用javabean

<jsp:userBean id="标识符" class = "java类名" scope = "作用范围"/>
<jsp:useBean id="myUser" class="com.test.User" scope="page"></jsp:useBean>
<h1>使用javabean动作创建javabean实例</h1>
账户名是: <%=myUser.getmUserName()%>
密码是:<%=myUser.getmPassword()%>
账户名是: null 密码是:null
<jsp:setProperty name ="javaBean实例名" property = "*"/>(跟表单关联)
<jsp:setProperty name = "javabean实例名" property = "javabean属性名"/>(跟表单关联)
<jsp:setProperty name = "javabean实例名" property = "javabean属性名" value = "beanvalue"/>(手工设置)
<jsp:setProperty name = "javabean实例名" property = "propertyName" param = "request对象中的参数名"/>(跟request参数关联)
第一种:备注:根据表单自动匹配所有的属性

<html>
<head>
    <title></title>
</head>
<body>
<h1>系统登录</h1>
<hr>
<form name="loginForm" action="dologin.jsp" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" value=""/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password" value=""></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"></td>
            <td></td>
        </tr>
    </table>
</form>
</body>
</html>

<html>
<head>
    <title>我的个人主页</title>
</head>
<body>
<jsp:useBean id="myUsers" class="com.test.User" scope="page"/>
<h1>setProperty动作元素</h1>
<hr>

<jsp:setProperty name="myUsers" property="*"></jsp:setProperty>
用户名:<%=myUsers.getUsername()%><br>
密码:<%=myUsers.getPassword()%>
</body>
</html>

用户名:fukaiqiang
密码:123456
第二种:备注:根据表单匹配部分的属性

<jsp:setProperty name="myUsers" property="username"></jsp:setProperty>

用户名:fukaiqiang
密码:null
第三种:备注:和表单无关,通过手工赋值给属性

<jsp:setProperty name="myUsers" property="username" value="Lisi"></jsp:setProperty>
<jsp:setProperty name="myUsers" property="password" value="654321"></jsp:setProperty>

用户名:Lisi
密码:654321
第四种:通过Url传参数给属性赋值

<jsp:setProperty name="myUsers" property="username"></jsp:setProperty>
<jsp:setProperty name="myUsers" property="password" param="myPass"></jsp:setProperty>
用户名:<%=myUsers.getUsername()%><br>
密码:<%=myUsers.getPassword()%>

<form name="loginForm" action="dologin.jsp?myPass=789456123 " method="post">

用户名:fukaiqiang
密码:789456123
<!--使用传统的表达式方式来获取用户名和密码-->
用户名:<%=myUsers.getUsername()%><br>
密码:<%=myUsers.getPassword()%>
<!--使用getProperty方式来获取用户名和密码-->
用户名:<jsp:getProperty name="myUsers" property="username"></jsp:getProperty>
用户名:<jsp:getProperty name="myUsers" property="password"></jsp:getProperty>

49. Javabean四个作用域范围

 1. page:尽在当前页面有效.
 2. request:可以用过HttpRequest.getAttribute()方法取得javabean对象.
 3. session:可以通过HttpSession.getAttribute()方法取得javabean对象.
 4.application:可以通过applicaion.getAttribute()方法取得javabean对象.
<h1>javabean的四个作用域范围</h1>
<hr>
<jsp:useBean id="myUsers" class="com.test.User" scope="application"/>
用户名:
<jsp:getProperty name="myUsers" property="username"/>
<br>
密码:
<jsp:getProperty name="myUsers" property="password"/>
<br>
<!--使用内置对象获取用户名和密码-->
<hr>
用户名:<%=((User) application.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((User) application.getAttribute("myUsers")).getPassword()%>
用户名:<%=((User) session.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((User) session.getAttribute("myUsers")).getPassword()%>
<jsp:useBean id="myUsers" class="com.test.User" scope="request"/>
<%
 request.getRequestDispatcher("testscope.jsp").forward(request,response);
%>
用户名:<%=((User) request.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((User) request.getAttribute("myUsers")).getPassword()%>
<jsp:useBean id="myUsers" class="com.test.User" scope="page"/>

<%
    String username = "";
    String password = "";
    if (pageContext.getAttribute("myUsers") != null) {
        username = ((User) pageContext.getAttribute("myUsers")).getUsername();
        password = ((User) pageContext.getAttribute("myUsers")).getPassword();
    }
%>
用户名:<%=username%>
密码:<%=password%>

50. Model1简介

51. jsp+javabean完成用户登录功能

login: 
<form name="loginForm" action="dologin.jsp" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" value=""/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password" value=""></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"></td>
            <td></td>
        </tr>
    </table>
</form>
dologin:
<jsp:useBean id="loginUser" class="com.test.User" scope="page"/>
<jsp:useBean id="userdao" class="com.test.UserDao" scope="page"/>
<jsp:setProperty name="loginUser" property="*"/>
<%
    //如果用户和密码都等于admin,则登录成功
    if (UserDao.userLogin(loginUser)) {
        session.setAttribute("loginUser", loginUser.getUsername());
        request.getRequestDispatcher("login_success.jsp").forward(request, response);
    } else {
        response.sendRedirect("login_failure.jsp");
    }
%>

<html>
<head>
    <title>Title</title>
</head>
<body>
    我是登录失败页面
</body>
</html>

<html>
<head>
    <title>Title</title>
</head>
<body>
    我是成功登录页面
</body>
</html>

52. http协议的无状态性

53. Cookie概述

54. Cookie的作用

55. Jsp页面中创建与使用Cookie

Cookie newCookie = new Cookie(String key,Object value);
response.addCookie(new Cookie);
Cookie[] cookies = request.getCookies();
1. void setMaxAge(int expiry):设置cookie的有效期,以秒为单位.
2. void setValue(String value):在cookie创建后,对cookie进行赋值.
3. String getName():获取cookie的名称.
4. String getValue():获取cookie的值.
5. int getMaxAge():获取cookie的有效时间,以秒为单位.

56. Cookie在登录中的应用

login.jsp

<body>

<%
    request.setCharacterEncoding("utf-8");
    String username = "";
    String password = "";
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie c : cookies) {
            if (c.getName().equals("username")) {
                username = URLDecoder.decode(c.getValue(), "utf-8");
            }
            if (c.getName().equals("password")) {
                password = URLDecoder.decode(c.getValue(), "utf-8");
            }
        }
    }
%>
<form name="loginForm" action="dologin.jsp" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" value="<%=username%>"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password" value="<%=password%>"/></td>
        </tr>
        <tr>
            <td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked"/>十天内记住我的登录状态</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录"/><input type="reset" value="取消"/></td>
        </tr>
    </table>
</form>
dologin.jsp

<body>

<%
    request.setCharacterEncoding("utf-8");
    //首先判断用户是否选择了记住登录状态
    String[] isUseCookies = request.getParameterValues("isUseCookie");
    if (isUseCookies != null && isUseCookies.length > 0) {
        //把用户名和密码保存在Cookie对象里面
        String username = URLEncoder.encode(request.getParameter("username"), "utf-8");
        //使用URLEncoder解决无法在Cookie当中保存中文字符串问题
        String password = URLEncoder.encode(request.getParameter("password"), "utf-8");

        Cookie usernameCookie = new Cookie("username", username);
        Cookie passwordCookie = new Cookie("password", password);
        usernameCookie.setMaxAge(864000);
        passwordCookie.setMaxAge(864000);//设置最大生存期限为10天
        response.addCookie(usernameCookie);
        response.addCookie(passwordCookie);
    } else {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (c.getName().equals("username") || c.getName().equals("password")) {
                    c.setMaxAge(0); //设置Cookie失效
                    response.addCookie(c); //重新保存。
                }
            }
        }
    }
%>
<a href="user.jsp" target="_blank">查看用户信息</a>
</body>
user.jsp

<body>
<h1>用户信息</h1>
<%
    request.setCharacterEncoding("utf-8");
    String username="";
    String password = "";
    Cookie[] cookies = request.getCookies();
    if(cookies!=null&&cookies.length>0) {
        for(Cookie c:cookies) {
            if(c.getName().equals("username")) {
                username = URLDecoder.decode(c.getValue(),"utf-8");
            }
            if(c.getName().equals("password")) {
                password = URLDecoder.decode(c.getValue(),"utf-8");
            }
        }
    }
%>
<br>
用户名:<%=username %><br>
密码:<%=password %><br>
</body>
解决Cookie中文乱码的问题:
1. request.setCharacterEncoding("utf-8");
2. URLEncoder 编码
3. URLDecoder 解码

57. Session与Cookie的对比

58. include指令

<%@ include file = "URL"%>
<%@ include file = "date.jsp"%>

59. include动作

<jsp:include page = "URL" flush = "true|false"/>
page:要包含的页面
flush:被包含的页面是否从缓冲区读取

60. include指令与include动作的区别

指令与动作.png

61. forward动作

<jsp:forward page="user.jsp"></jsp:forward>
相当于转发:
request.getRequestDispatcher("user.jsp").forward(request,response);

62. param动作

jsp:param :用于增加一个参数
<jsp:forward page="user.jsp">
    <jsp:param name="email" value="123@163.com"></jsp:param>
</jsp:forward>
jsp:param :用于修改一个参数的参数值
<jsp:forward page="user.jsp">
    <jsp:param name="password" value="88888"></jsp:param>
</jsp:forward>

63. 支持

希望阅读本篇能够让你对Jsp有更全面的理解,还请多多支持,多多关注,多多点赞,多多收藏.

上一篇 下一篇

猜你喜欢

热点阅读