JSP学习笔记(三)

2019-12-21  本文已影响0人  dev_winner
  1. 第一类是与存取JavaBean有关的,包括<jsp:useBean><jsp:setProperty><jsp:getProperty>
  2. 第二类是JSP1.2就开始有的基本元素,包括6个动作元素:<jsp:include><jsp:forward><jsp:param><jsp:plugin><jsp:params><jsp:fallback>
  3. 第三类是JSP2.0新增的动作元素,主要与JSP Document有关,包括六个元素:<jsp:root><jsp:declaration><jsp:scriptlet><jsp:expression><jsp:text><jsp:output>
  4. 第四类是JSP2.0新增的动作元素,主要用来动态生成XML元素标签的值,包括3个动作:<jsp:attribute><jsp:body><jsp:element>
  5. 第五类是JSP2.0 新增的动作元素,主要用在Tag File中,有2个元素:<jsp:invoke><jsp:dobody>
<jsp:useBean id="标示符" class="java包名+类名" scope="作用范围" />
<jsp:setProperty name="javaBean实例名" property="*" />(跟表单关联,'*'表示根据表单中的参数和javaBean中的属性名进行一一匹配,若匹配成功,则自动赋值)
<jsp:setProperty name="javaBean实例名" property="javaBean属性名" />(跟表单关联,与*号的区别是这里对某个属性进行匹配设值)
<jsp:setProperty name="javaBean实例名" property="javaBean属性名" value="BeanValue" />(手工设置)
<jsp:setProperty name="javaBean实例名" property="propertyName" param="request对象中的参数名" />(跟request参数关联)
<jsp:getProperty name="javaBean实例名" property="属性名" />
<jsp:forward page="URL">
    <jsp:param name="参数名1" value="参数值1" />
    <jsp:param name="参数名2" value="参数值2" />
</jsp:forward>
// 公有类
public class User {
    // 私有属性
    private String username;
    private String password;
    // 公有构造方法
    public User() {
    }
    // getter、setter方法
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页面</title>
</head>
<body>
    <h1>系统登录</h1>
        <form action="userBean.jsp?mypass=77777" name="loginForm" 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>
                <%--colspan 属性规定单元格可横跨的列数--%>
                <td colspan="2" ><input type="submit" value="登录" /></td>
            </tr>
        </table>
    </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    request.setCharacterEncoding("utf-8");
%>
<html>
<head>
    <title>jsp动作元素useBean的使用</title>
</head>
<body>
    <%--scope默认值是page,id就是一个javabean实例对象--%>
    <jsp:useBean id="myUsers" class="com.zzw.po.User" scope="page"/>
    <h1>使用userBean动作标签来创建并赋值javaBean的实例</h1>
    <%--name和上面的id要相同,'*'表示自动去匹配javaBean中所有属性,若都匹配则调用set方法依次给属性赋值--%>
    <%--<jsp:setProperty name="myUsers" property="*" />--%>

    <%--name和上面的id要相同,根据表单匹配某个属性并予其赋值--%>
    <%--<jsp:setProperty name="myUsers" property="username" />--%>

    <%--name和上面的id要相同,与表单无关,通过手工给属性赋值--%>
    <%--<jsp:setProperty name="myUsers" property="username" value="lisi"/>
    <jsp:setProperty name="myUsers" property="password" value="666"/>--%>

    <%--通过URL中的参数给属性赋值--%>
    <jsp:setProperty name="myUsers" property="password" param="mypass"/>
    <jsp:setProperty name="myUsers" property="username" />
    <%--使用传统表达式的方式来获取用户名和密码的值--%>
    <%--用户名:<%=myUsers.getUsername() %><br/>
    密码:<%=myUsers.getPassword() %>--%>
    用户名:<jsp:getProperty name="myUsers" property="username"/><br/>
    密码:<jsp:getProperty name="myUsers" property="password" />
</body>
</html>
  1. page:仅在当前页面有效,作用域范围最小
  2. request:可以通过HttpRequest.getAttribute()方法取得javaBean对象
  3. session:可以通过HttpSession.getAttribute()方法取得javaBean对象
  4. application:可以通过application.getAttribute()方法取得javaBean对象,作用域范围最大
Model1的3层结构图
import com.zzw.po.User;
// 用户逻辑类
public class UserDao {
    // 用户登录方法
    public boolean userLogin(User u) {
        if("admin".equals(u.getUsername()) && "admin".equals(u.getPassword())) {
            return true;
        } else {
            return false;
        }
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="loginUser" class="com.zzw.po.User" scope="page"/>
<%--还要实例化一个用户逻辑类UserDao--%>
<jsp:useBean id="userDao" class="com.zzw.dao.UserDao" scope="page"/>
<jsp:setProperty name="loginUser" property="*" />
<%
    // 修改字符集
    request.setCharacterEncoding("utf-8");
    if(userDao.userLogin(loginUser)) {
        session.setAttribute("loginUser", loginUser.getUsername());
        request.getRequestDispatcher("login_success.jsp").forward(request, response);
    } else {
        response.sendRedirect("login_failure.jsp");
    }
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功状态</title>
</head>
<body>
    登录成功!
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录失败状态</title>
</head>
<body>
    登录失败!
</body>
</html>
登录成功
<%-- 创建Cookie对象 --%>
Cookie newCookie = new Cookie(String key, Object value);
<%-- 写入Cookie对象 --%>
response.addCookie(newCookie);
<%-- 读取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的有效时间,以秒为单位
Session和Cookie的区别
<%@ page language="java" import="java.util.*,java.net.*"
    contentType="text/html; charset=utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
</head>
<body>
    <h1>用户登录</h1>
    <hr>
    <%
        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>
</body>
</html>
<%@ page language="java" import="java.util.*,java.net.*"
    contentType="text/html; charset=utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting page</title>
</head>
<body>
    <h1>登录成功</h1>
    <hr>
    <%
        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);
            //设置最大生存期限为10天
            usernameCookie.setMaxAge(864000);
            passwordCookie.setMaxAge(864000);
            // 添加cookie实例到response对象中
            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")) {
                        //设置Cookie失效
                        c.setMaxAge(0); 
                        //重新保存。
                        response.addCookie(c);
                    }
                }
            }
        }
    %>
    <a href="perInfo.jsp" target="_blank">查看用户信息</a>
</body>
</html>
<%@ page language="java" import="java.util.*,java.net.*"
    contentType="text/html; charset=utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'perInfo.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>

<body>
    <h1>用户信息</h1>
    <hr>
    <%
        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")) {
                    // url参数解码
                    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>
</html>
实现记住登录账号和密码 记住用户信息
上一篇 下一篇

猜你喜欢

热点阅读