整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

JSP中四种传递参数的方法(个人总结,简单实用)

sp中四种传递参数的方法,我觉得总结一下,挺好的,以备后用!

1、form表单

2、request.setAttribute();和request.getAttribute();

3、超链接:<a herf="index.jsp"?a=a&b=b&c=c>name</a>

1、form表单

form.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 form.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 
 <h2 style="font-family:arial;color:red;font-size:25px;text-align:center">登录页面</h2> 
 
 <form action="result.jsp" method="get" align="center"> 
 姓名:<input type="text" name="name" size="20" value="" maxlength="20"><br/> 
 
 密码:<input type="password" name="password" size="20" value="" maxlength="20"><br/> 
 
 <!--在爱好前空一个空格,是为了排版好看些--> 
 
 爱好:<input type="checkbox" name="hobby" value="唱歌">唱歌 
 <input type="checkbox" name="hobby" value="足球">足球 
 <input type="checkbox" name="hobby" value="篮球">篮球<br/><br/> 
 
 <input type="submit" name="submit" value="登录"> 
 <input type="reset" name="reset" value="重置"><br/> 
 </form> 
 
 </body> 
</html>

result.jsp:

 1 <%@page language="java" import="java.util.*" pageEncoding="GB2312"%> 
 2 <html> 
 3 <head> 
 4 <title> 
 5 result.jsp file 
 6 </title> 
 7 </head> 
 8 
 9 <body bgcolor="ffffff"> 
10 <% 
11 request.setCharacterEncoding("GB2312"); 
12 
13 String name=request.getParameter("name"); 
14 name=new String(name.getBytes("iso-8859-1"),"GB2312"); 
15 
16 String pwd=request.getParameter("password"); 
17 String[] hobby=request.getParameterValues("hobby");//注意这里的函数是getParameterValues()接受一个数组的数据 
18 
19 %> 
20 
21 <% 
22 if(!name.equals("") && !pwd.equals("")) 
23 { 
24 %> 
25 
26 您好!登录成功!<br/> 
27 姓名:<%=name%><br/> 
28 密码:<%=pwd%><br/> 
29 爱好:<% 
30 for(String ho: hobby) 
31 { 
32 ho=new String(ho.getBytes("iso-8859-1"),"GB2312"); 
33 out.print(ho+" "); 
34 } 
35 %> 
36 <% 
37 } 
38 else 
39 { 
40 %> 
41 请输入姓名或密码! 
42 <% 
43 } 
44 %> 
45 </body> 
46 </html>

注意:form表单的提交方式为get,在参数传递时会遇到中文乱码的问题,一个简单的解决方法是,将接受到的字符串先转换成一个byte数组,再用String构造一个新的编码格式的String,如:

1 String name=request.getParameter("name"); 
2 name=new String(name.getBytes("iso-8859-1"),"GB2312"); 

如果form表单的提交方式为post,解决乱码问题的简单办法是,使用 request.setCharacterEncoding("GB2312");设置request的编码方式。

为什么会出现中文乱码问题呢?因为Tomcat服务器默认的系统编码方式为iso- 8859-1,你传递参数给服务器时,使用的是默认的iso-8859-1的编码方式,但是服务器向你返回信息时,是按page指令中设置的编码方式, 如:<%@page language="java" import="java.util.*" pageEncoding="GB2312"%>,这样就混合了两种编码方式,所以会出现乱码,所以解决之道就是统一传递和接收的编码方式。

2、request.setAttribute()和request.getAttribute()

set.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 set.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 request.setAttribute("name","心雨"); 
 %> 
 <jsp:forward page="get.jsp"/> 
 </body> 
</html>

get.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 get.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 out.println("传递过来的参数是:"+request.getAttribute("name")); 
 %> 
 </body> 
</html> 

request.setAttribute()和request.getAttribute()是配合<jsp:forward>或是include指令来实现的。

3、超链接:<a herf="index.jsp?a=a&b=b&c=c">name</a>

href.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 href.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <a href="getHerf.jsp?name=心雨&password=123">传递参数</a> 
 </body> 
</html> 

getHref.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 getHref.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 String name=request.getParameter("name"); 
 name=new String(name.getBytes("iso-8859-1"),"gb2312"); 
 
 out.print("name:"+name); 
 %> 
 <br/> 
 <% 
 out.print("password:"+request.getParameter("password")); 
 %> 
 </body> 
</html> 

这种传递参数的方法和form表单的get方式类似,是通过地址栏传递的参数,其乱码解决方法也和form 的get方式一样。

4、<jsp:param>

param.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 param.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 
 <%request.setCharacterEncoding("GB2312");%> 
 
 <jsp:forward page="getParam.jsp"> 
 <jsp:param name="name" value="心雨"/> 
 <jsp:param name="password" value="123"/> 
 </jsp:forward> 
 
 </body> 
</html>

getParam.jsp:

<%@page contentType="text/html; charset=GB2312"%> 
<html> 
 <head> 
 <title> 
 getParam.jsp file 
 </title> 
 </head> 
 
 <body style="background-color:lightblue"> 
 <% 
 String name=request.getParameter("name"); 
 out.print("name:"+name); 
 %> 
 <br/> 
 <% 
 out.print("password:"+request.getParameter("password")); 
 %> 
 </body> 
</html> 

这里发现了一个奇怪的问题,还是在中文乱码的问题上,在form表单的例子中,如果传递方式为post,则只需要在接收参数的页面设置request的编 码方式就可以了,即request.setCharacterEncoding("GB2312");,注意是在接收参数的页面,如果将该句放到form 表单里,那么不起作用,仍然是乱码。而在本例中,为了使传递的参数不出现乱码,却是将 request.setCharacterEncoding("GB2312");放在发送参数的页面中,才会正常显示中文,放在接收参数的页面中,不起 作用。也许这就是<jsp:param>和form表单传递参数不同的地方。为什么会有这个不同呢?可能是因为form表单中的参数是由客户 端传送到服务端上的,需要经过一个request的打包过程,但是<jsp:param>传递的参数本身就是在服务器端的,不需要经历由客户 端到服务端这么一个过程,但是服务器里的参数传递是这么回事呢?这个问题,我不知道了!真是知识是一个扩大的圆圈,你知道的越多,那么不知道的就越多!努 力吧!

一、写在前面

二、效果图

三、实现思路

四、实现代码

1、login总界面

2、registercheck总代码

3、logoutcheck总代码

4、amendcheck总代码


相关文章

一、写在前面

哈喽~大家好,这篇呢我们来看看用 JSP 连接 MySQL 登入注册项目实践,这里就可能有人问了,唉?追桑~前些天不是写了 jsp 登入注册的项目吗?怎么这次还在写呢?哈哈,您别担心,这次呢,肯定和上次不同,我们先来看看效果吧!

二、效果图

数据库界面

感觉是不是不一样了,哈哈哈,那么接下来我们来看看是怎么实现的。

三、实现思路

首先我们这里很明显,有四个总页面分别是 login(登入界面)、logout(注销界面)、amend(修改界面)、register(注册界面),这四个总页面分别对应着检查页面(check)、成功页面(success)、失败页面(fail)。建立之好后,通过 from 的 action 来进行跳转,我们先来看看 MySQL (数据库)表名叫 login。

我们这里数据库共三列,第一列叫 name (用户名)、pass(密码)、time(注册时间),name 与 pass 都是 int(整型) 类型的,time 是 varchar (可变长类型),如图。

四、实现代码

1、login总界面

首先我们先有个页面,有基本的用户名框,密码框,两按钮,一个注册,一个注销,通过 from进行跳转,代码如下

 <form method="post" action="check.jsp">
        <input type="text" name="user" style="width: 300px;height: 50px" placeholder="请输入用户名:"
        > <br>
        <input type="password" name="pass" style="width: 300px;height: 50px" placeholder="请输入密码:" > <br>
        <button type="submit" style="width:80px;height:40px; font-size: 20px" class="clear">登录</button>
        <button type="reset" style="width:80px;height:40px; font-size: 20px" class="clear">重置</button>
        <br>
        没有账号?<a href="register.jsp">点击注册</a><br>
        不想用了?<a href="logout.jsp">点击注销</a>
    </form>

用 check 连接数据库(如何连接数据库,前面文章已经给出了,有兴趣的小伙伴可以看看前面写的文章,也放在前面了) 同样的道理,还是那五个步骤(这里就不过多的解释,可以看看上面表格给出的文章),先来看看代码。

String user = request.getParameter("user"); // getParameter  与 getAttribute  区别
        String pass = request.getParameter("pass");
        // String getParameter(String name):根据参数名称获取参数值
        // getAttribute()获取的是服务器设置的数据。getAttribute() 方法返回指定属性名的属性值。
 
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
            String user1 = "root";
            String pass1 = "123456";
            Connection connection = DriverManager.getConnection(url,user1,pass1);
            String sql = "select * from login where name=? and pass=?";
 
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user);
            ps.setString(2,pass);
            ResultSet re = ps.executeQuery();
 
            if (re.next()){
                response.sendRedirect("loginsuccess.jsp");
                session.setAttribute("user",user);
            }else {
                response.sendRedirect("loginfail.jsp");
            }
 
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

这里 response.sendRedirect 跳转了两个页面一个 loginsuccess 和 loginfail 的两个界面,下面我们来看看,这两个文件(其实很简单)

loginsuccess 代码

 <div class="form">
                <h2> <h22>登录成功</h22><br>
                </h2>
                <fon>恭喜您成功登入 <br>    欢迎使用 <br>
                    <a class="a1" href="login.jsp">返回登入界面</a>
                </fon>
            </div>

loginfail 代码:

<h2> <h22>登录失败</h22><br>
                </h2>
                <fon>宝~是不是账号或密码记错惹? <br>
                    <a class="a1" href="login.jsp">返回登入界面</a><br>
                    <p1><a href="amend.jsp">点击修改密码</a></p1>
                </fon>

这里我们点击运行看看效果

这里我们用两个升级 大装备(html)(css) 来美化一下我们的页面,这里我们页面美化的,用的是这位大佬的页面(博主名为键盘奏鸣曲),大家可以来看看,点击链接

HTML 代码

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

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="css.css">

<title>123</title>



</head>

<body>


<section>

<div class="color"></div>

<div class="color"></div>

<div class="color"></div>

<div class="box">

<div class="circle" style="--x:0"></div>

<div class="circle" style="--x:1"></div>

<div class="circle" style="--x:2"></div>

<div class="circle" style="--x:3"></div>

<div class="circle" style="--x:4"></div>

<div class="container">

<div class="form">

<h2>登录</h2>

<form method="post" action="check.jsp">

<div class="inputBox">

<input type="text" placeholder="姓名" name="user">


</div>

<div class="inputBox">

<input type="password" placeholder="密码" name="pass">


</div>

<div class="inputBox">

<input type="submit" value="登录">


</div>

<p class="forget">不想用了?<a href="logout.jsp">

点击这里

</a></p>

<p class="forget">没有账户?<a href="register.jsp">

注册

</a></p>

</form>

</div>

</div>

</div>

</section>

</body>


</html>

CSS 代码

/*.center{*/
/*    text-align:center;*/
/*    margin-top: 50px;*/
/*}*/
.fon{
    font-size: 40px;
}
/*body{*/
/*    background: url("images/image-2.jpg") no-repeat 0 0;*/
/*    background-size: 100% 100%;*/
/*    text-decoration:none;*/
/*}*/
 
/*input {*/
/*    background-color: transparent;*/
/*    outline: none;*/
/*    color: black;*/
/*}*/
/*.clear{*/
/*    opacity:0.3;*/
/*}*/
 
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
 
/* 使用flex布局,让内容垂直和水平居中 */
 
section {
    /* 相对定位 */
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    /* linear-gradient() 函数用于创建一个表示两种或多种颜色线性渐变的图片 */
    background: linear-gradient(to bottom, #f1f4f9, #dff1ff);
}
 
/* 背景颜色 */
 
section .color {
    /* 绝对定位 */
    position: absolute;
    /* 使用filter(滤镜) 属性,给图像设置高斯模糊*/
    filter: blur(200px);
}
 
/* :nth-child(n) 选择器匹配父元素中的第 n 个子元素 */
 
section .color:nth-child(1) {
    top: -350px;
    width: 600px;
    height: 600px;
    background: #ff359b;
}
 
section .color:nth-child(2) {
    bottom: -150px;
    left: 100px;
    width: 500px;
    height: 500px;
    background: #fffd87;
}
 
section .color:nth-child(3) {
    bottom: 50px;
    right: 100px;
    width: 500px;
    height: 500px;
    background: #00d2ff;
}
 
.box {
    position: relative;
}
 
/* 背景圆样式 */
 
.box .circle {
    position: absolute;
    background: rgba(255, 255, 255, 0.1);
    /* backdrop-filter属性为一个元素后面区域添加模糊效果 */
    backdrop-filter: blur(5px);
    box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.5);
    border-right: 1px solid rgba(255, 255, 255, 0.2);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    /* 使用filter(滤镜) 属性,改变颜色。
    hue-rotate(deg)  给图像应用色相旋转
    calc() 函数用于动态计算长度值
    var() 函数调用自定义的CSS属性值x*/
    filter: hue-rotate(calc(var(--x) * 70deg));
    /* 调用动画animate,需要10s完成动画,
    linear表示动画从头到尾的速度是相同的,
    infinite指定动画应该循环播放无限次*/
    animation: animate 10s linear infinite;
    /* 动态计算动画延迟几秒播放 */
    animation-delay: calc(var(--x) * -1s);
}
 
/* 背景圆动画 */
 
@keyframes animate {
    0%, 100% {
        transform: translateY(-50px);
    }
    50% {
        transform: translateY(50px);
    }
}
 
.box .circle:nth-child(1) {
    top: -50px;
    right: -60px;
    width: 100px;
    height: 100px;
}
 
.box .circle:nth-child(2) {
    top: 150px;
    left: -100px;
    width: 120px;
    height: 120px;
    z-index: 2;
}
 
.box .circle:nth-child(3) {
    bottom: 50px;
    right: -60px;
    width: 80px;
    height: 80px;
    z-index: 2;
}
 
.box .circle:nth-child(4) {
    bottom: -80px;
    left: 100px;
    width: 60px;
    height: 60px;
}
 
.box .circle:nth-child(5) {
    top: -80px;
    left: 140px;
    width: 60px;
    height: 60px;
}
 
/* 登录框样式 */
 
.container {
    position: relative;
    width: 400px;
    min-height: 400px;
    background: rgba(255, 255, 255, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(5px);
    box-shadow: 0 25px 45px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.5);
    border-right: 1px solid rgba(255, 255, 255, 0.2);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}
 
.form {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 50px;
}
 
/* 登录标题样式 */
 
.form h2 {
    text-align: center;
    position: relative;
    color: #fff;
    font-size: 40px;
    font-weight: 600;
    letter-spacing: 5px;
    margin-bottom: 30px;
    cursor: pointer;
}
 
.form h2 h22 {
    top: -40px;
    text-align: center;
    position: relative;
    color: #fff;
    font-size: 40px;
    font-weight: 600;
    letter-spacing: 5px;
    margin-bottom: 30px;
    cursor: pointer;
}
 
.form .a1, .form p1 {
    bottom: -90px;
    left: 50px;
    position: relative;
    color: #fff;
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 5px;
    /*margin-bottom: 10px;*/
    cursor: pointer;
    text-decoration: none;
}
 
.form p1 a{
 
    position: relative;
    color: #fff;
    font-size: 18px;
    font-weight: 600;
    letter-spacing: 5px;
    /*margin-bottom: 10px;*/
    cursor: pointer;
    text-decoration: none;
}
 
.form fon {
    top: -30px;
    left: 30px;
    position: relative;
    color: #fff;
    font-size: 28px;
    font-weight: 600;
    letter-spacing: 5px;
    margin-bottom: 30px;
    cursor: pointer;
}
/* 登录标题的下划线样式 */
 
.form h2::before {
    content: "";
    position: absolute;
    left: 0;
    bottom: -10px;
    width: 0px;
    height: 3px;
    background: #fff;
    transition: 0.5s;
}
 
.form h2 h22::before {
    content: "";
    position: absolute;
    /*left: 0;*/
    /*bottom: -10px;*/
    /*width: 0px;*/
    /*height: 3px;*/
    /*background: #fff;*/
    /*transition: 0.5s;*/
}
 
.form h2:hover:before {
    width: 53px;
}
 
.form .inputBox {
    width: 100%;
    margin-top: 20px;
}
 
/* 输入框样式 */
 
.form .inputBox input {
    width: 100%;
    padding: 10px 20px;
    background: rgba(255, 255, 255, 0.2);
    outline: none;
    border: none;
    border-radius: 30px;
    border: 1px solid rgba(255, 255, 255, 0.5);
    border-right: 1px solid rgba(255, 255, 255, 0.2);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    font-size: 16px;
    letter-spacing: 1px;
    color: #fff;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}
 
.form .inputBox input::placeholder {
    color: #fff;
}
 
/* 登录按钮样式 */
 
.form .inputBox input[type="submit"],.form .inputBox input[type="reset"]  {
    background: #fff;
    color: #666;
    max-width: 100%;
    margin-bottom: 20px;
    font-weight: 600;
    cursor: pointer;
}
 
.forget {
    margin-top: 6px;
    color: #fff;
    letter-spacing: 1px;
}
 
.forget a {
    color: #fff;
    font-weight: 600;
    text-decoration: none;
}

同样的道理我们来升级一下 loginsuccess 与 loginfail 。

loginsuccess 代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登入成功界面</title>
    <link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<%--<div class="center">--%>
<%--    <p class="fon">登入成功界面</p>--%>
<%--    <p class="fon1">恭喜您成功登入,欢迎使用</p>--%>
<%--    <a href="login.jsp">点击退出,返回登入界面</a>--%>
<%--</div>--%>
 
<section>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="box">
        <div class="circle" style="--x:0"></div>
        <div class="circle" style="--x:1"></div>
        <div class="circle" style="--x:2"></div>
        <div class="circle" style="--x:3"></div>
        <div class="circle" style="--x:4"></div>
        <div class="container">
            <div class="form">
                <h2> <h22>登录成功</h22><br>
                </h2>
                <fon>恭喜您成功登入 <br>    欢迎使用 <br>
                    <a class="a1" href="login.jsp">返回登入界面</a>
                </fon>
            </div>
        </div>
    </div>
</section>
 
</body>
</html>

loginfail 代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登入失败界面</title>
    <link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<%--<div class="center">--%>
<%--    <p class="fon">登入失败界面</p>--%>
<%--    <p class="fon1">对不起,您账号或密码有误,请返回登入界面</p>--%>
<%--    <a href="login.jsp">返回登入界面</a><br>--%>
<%--    忘记密码?<a href="amend.jsp">点击修改密码</a>--%>
<%--</div>--%>
 
<section>
    <div class="color"></div>
    <div class="color"></div>
    <div class="color"></div>
    <div class="box">
        <div class="circle" style="--x:0"></div>
        <div class="circle" style="--x:1"></div>
        <div class="circle" style="--x:2"></div>
        <div class="circle" style="--x:3"></div>
        <div class="circle" style="--x:4"></div>
        <div class="container">
            <div class="form">
                <h2> <h22>登录失败</h22><br>
                </h2>
                <fon>宝~是不是账号或密码记错惹? <br>
                    <a class="a1" href="login.jsp">返回登入界面</a><br>
                    <p1><a href="amend.jsp">点击修改密码</a></p1>
                </fon>
                
            </div>
        </div>
    </div>
</section>
 
</body>
</html>

点击运行,我们来看看效果

那么这里我们是完成了,login总界面的效果,同样的道理,代码都差不多,我们直接 cv 大法,这里就给出重点要改的代码。

2、registercheck总代码

里面要重点改的代码,一个是 sql 语句插入,另一个是时间格式转换。

tring sql = "insert into login(name, pass,time)VALUES(?,?,?)";

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 时间转换,要不然就会是国际时间格式

String data = formatter.format(new Date());// 记录的是当前的时间

ps.setString(3,data);

3、logoutcheck总代码

3、logoutcheck总代码

里面要重点改的代码,是 sql 语句删除。

String sql = "DELETE FROM login WHERE name =? and pass =?";

4、amendcheck总代码

里面要重点改的代码,是 sql 语句更新。

String sql = "update login set pass='"+pass+"'";

然后分别是各个总页面的 success 与 fail 页面来实现好,这里有一个小细节,我们在作抛出异常,这里可以 out.println 来打印出信息来测试,可以输出在网页上,这样可以方便知道那里有异常。


catch (ClassNotFoundException e) {
            e.printStackTrace();
            out.println("1");
            // response.sendRedirect("registerfail.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("2");
            // response.sendRedirect("registerfail.jsp");

好了,点击运行,完成总效果。



































作者:一个名叫追的程序猿

原文出处:https://blog.csdn.net/aasd23/article/details/124458396?spm=1001.2100.3001.7377&utm_medium=distribute.pc_feed_blog_category.none-task-blog-classify_tag-16-124458396-null-null.nonecase&depth_1-utm_source=distribute.pc_feed_blog_category.none-task-blog-classify_tag-16-124458396-null-null.nonecase

方微信:动力节点java学院

官方微博:动力节点

一、什么是Jsp

jsp是一种基于文本的程序,全名java server page,其特点是html和java程序共存。执行时jsp会被运行容器编译,编译后的jsp跟servlet一样,因此jsp是另一种形式的servlet。

二、jsp页面组成

jsp 页面包括以下内容:

  • 静态内容

  • 指令

  • 表达式

  • 小脚本

  • 声明

  • 注释

1.指令:

  • page指令: 通常位于jsp页面的顶端,同一个页面可以有多个page指令。

  • include指令:将一个外部文件嵌入到jsp文件中。

  • taglib指令 :使用标签定义新的自定义标签。

1.1其中page指令语法:

<%@ page 属性=“属性值”>

属性默认值
languagejava
import“”

1.2 include 指令

<%@ include file="url" %>

1.3 动作

  • include动作

    <jsp:include page="url" flush="true"/>

    include 动作和include指令区别

    描述 | include指令 | include 动作

    --- | --- | ---

    语法 | < % @ include file=""/> | < jsp:include page="url" flush="true"/>

    发生时间 | 页面转换期间 | 请求期间

    包含内容 | 文件实际内容 | 页面的输出

    转化servlet | 一个servlet | 2个servlet

    编译时间 | 较慢 | 较快

    执行时间 | 稍快 |较慢--每次资源必须被编译

    forward动作

    <jsp:forward page="url"/>

    ==request.getRequestDispatcher("/url").forward(res,resp);

    param动作

    <jsp:param name="参数名" value="参数值"/>常常与<jsp:forward>一起使用

    例子:

    <jsp:forward page="user.jsp">

    <jsp:param name="email" value="1233@154.com"/></jsp:forward>

    2.jsp注释

  • html注释

    <!-- html注释 -->//客户端可见

  • jsp 注释

    <%-- jsp注释 --%>//客户端不可见

  • jsp 脚本注释 //客户端不可见

//单行注射

/** 多行注释*/

3.jsp脚本

在jsp页面中执行的java代码,语法:

<% java 代码 %>

4.jsp声明

在jsp页面定义变量或者方法,语法

<%! java 代码 %>

举例:

<%!

String s="adele"; int add(int x,int y){ return x+y;

}

%>

5.jsp表达式

在jsp页面执行的表达式,语法:

<% =表达式 %>// 表达式不以分号结尾

举例:

<%!

String s="adele";%><h2> hello,<%=s %> </h2>

三、jsp生命周期

CC36B22A-503E-4C29-98BB-3B58038C140E.png

jspService()是用来处理客户端请求的,对于每一个请求,服务器会创建一个新的线程来处理该请求。以多线程方式执行大大降低对系统的资源需求,提高系统的并发量和缩短了响应时间,servlet是常驻在服务器内存中。

它同servlet 一样,jsp 实例初始化和销毁也会调用sevlet的init() 和destroy();

另外jsp还有自己的初始化方法_jspInit();_jspDestroy();

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

<%!

public void _jspInit(){

}public void _jspDestroy(){

}

%>

四、javaben的使用

动作元素:

动作元素为请求处理阶段提供信息。

Paste_Image.png

在jsp页面使用javaben

  • 像普通的java类一样,创建javabean;

  • 在jsp使用动作标签来使用 javaben

相关标签如下:

<jsp:useBwan id="" class="" scope="" />

<jsp:setProperty name="javabean 是例" property="*"/>(跟表单关联)

<jsp:setProperty name="javabean 是例" property="javaben 属性名"/>(跟表单关联)

<jsp:setProperty name="javabean 是例" property="javaben 属性名" value=""/>(手动设置)

<jsp:setProperty name="javabean 是例" property="javaben 属性名" param="request对象参数"/>(跟request参数关联)

<jsp:getProperty name="" property=""/>

举个例子:

首先用户 在login.jsp提交表单,然后用户在dologin.jsp 根据动作标签获取参数。

login.jsp

<form name="loginForm" action="dologin.jsp?mypass=999999" 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>

</tr>

</table>

</form>

dologin.jsp

<body>

<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>

<h1>setProperty动作元素</h1>

<hr>

<!--根据表单自动匹配所有的属性 -->

<%--

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

--%>

<!--根据表单匹配所有部分的属性 -->

<%--

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

--%>

<!--根表单无关,通过手工赋值给属性 -->

<%--

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

<jsp:setProperty name="myUsers" property="password" value="888888"/>

--%>

<!--通过URL传参数给属性赋值 -->

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

<jsp:setProperty name="myUsers" property="password" param="mypass"/>

<!-- 使用传统的表达式方式来获取用户名和密码 -->

<%--

用户名:<%=myUsers.getUsername() %><br>

密码:<%=myUsers.getPassword() %><br>

--%> <!-- 使用getProperty方式来获取用户名和密码 -->

用户名:<jsp:getProperty name="myUsers" property="username"/> <br>

密码:<jsp:getProperty name="myUsers" property="password"/><br>

<br>

<br>

<a href="testScope.jsp">测试javabean的四个作用域范围</a>

<%

request.getRequestDispatcher("testScope.jsp").forward(request, response); %>

</body>

javaben 四大作用域

  • page ,仅当前页面有效

  • request ,通过httpRequest.getAttribute()获取jvabean对象

  • session ,通过httpSession.getAttribute() 获取javabean对象

  • application,通过application.getAttribute方法获取javabean 对象。

五、cookie

1.概述:

由于http协议的无状态,无法保存用户的状态,所以需要用session和cookie.

cookie 是web服务器保存在客户端的一系列文本信息。它的作用时记录一些用户的行为,简化登陆,但是容易泄露用户信息。

2.jsp创建和使用cookie

  • 创建cookie

Cookie cookie=new Cookie(String ,Object);

  • 写入cookie

response.addCookie(cookie);

  • 读取 cookie

Cookie[] cookies=request.getCookies();

3.cookie的常用方法

  • setMaxAge();

  • setValue();

  • getName();

  • getValue();

  • getMaxAge();

举个列子: 使用cookie记住用户登陆的账号密码;

登陆界面:

<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>

处理登陆逻辑的jsp

<body>

<h1>登录成功</h1>

<hr>

<br>

<br>

<br>

<%

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="users.jsp" target="_blank">查看用户信息</a>

</body>

使用cookie获取用户信息:

<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");

}

}

} %>

<BR>

<BR>

<BR>

用户名:<%=username %><br>

密码:<%=password %><br>

</body>

3.cookie和 session的区别

sessioncookie
在服务端保存信息在客户端保存信息
保存的 object类型保存的是 string 类型
随会话结束,销毁数据可以长期保存在客户端中
重要信息不重要信息

如有问题请下方留言
来源:互联网