1.JSP九大内置对象(自带的,不需要new也能使用的对象)
- out:输出对象,向客户端输出内容。
- request:请求对象,存储客户端向服务端发送的请求信息。
request对象的常见方法:
- String getParameter(String name) 根据请求的字段名key,返回字段值value。
- String[] getParameterValues(String name) 根据请求的字段名key,返回多个字段值value。
- void setCharacterEncoding(“utf-8”) 设置请求编码(tomcat7以前默认iso-8859-1,tomcat8以后默认utf-8)
- getRequestDispatcher(“b.jsp”).forward(request,response) 请求转发的方式跳转页面 A–> B
- ServletContext getServletContext() 获取项目的ServletContext对象
2.表单信息的获取
通过request对象的getParameter()方法可以获取用户提交的表单信息。
例如存在一个name属性为username的文本框,在表单提价后,要获取其value值,可通过以下代码实现:
前端的写法:
<p align="center">用户名:<input type="text" name="username"/></p>
String userName=request.getParameter(“username”);
创建用户注册的表单页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="check.jsp" method="post">
<p align="center">用户名:<input type="text" name="username"/></p>
<p align="center">密 码:<input type="password" name="pwd"/></p>
<p align="center"><input type="submit" value="登录"/></p>
</form>
</body>
</html>
创建show.jsp页面,在该页面中获取用户提交的表单信息并显示在页面中
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
%>
<%
if(username.equals("123456") && pwd.equals("123456"))
{
out.print("登录成功");
}else {
out.print("失败");
}
%>
</body>
</html>
3.请求转发和重定向
请求转发 | 重定向 | |
---|---|---|
地址栏是否改变 | 不变(check.jsp) | 改变(success.jsp) |
是否保留第一次请求时的数据 | 保留 | 不保留 |
请求的次数 | 1 | 2 |
跳转发生的位置 | 服务端 | 客户端发出的第二次跳转 |
4.Session(服务端)和Cookie(客户端,不是内置对象)
Cookie是由服务端生成的,再发送给客户端保存。
相当于本地缓存的作用:客户端(hello.mp4) —> 服务端(hello.mp4)。
作用:提高访问服务端的效率,但是安全性较差。
Cookie:key=value
javax.servlet.http.Cookie
- public Cookie(String name,String value)
- String getName() 获取name
- String getValue() 获取value
- void setMaxAge(int expiry) 最大有效期(秒)
服务端准备Cookie
response.addCookie(Cookie cookie);
页面跳转(转发、重定向)
客户端获取Cookie:
request.getCookies();
- 服务端增加cookie:response对象,客户端获取cookie:request对象。
- 不能直接获取某一个单独对象,只能一次性将全部的cookie拿到。
通过F12可以发现,除了自己设置的Cookie对象外,还有一个name为JSESSIONID的cookie。
服务端增加cookie
扫描二维码关注公众号,回复:
8830874 查看本文章
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//服务端
Cookie cookie1 = new Cookie("name","zs");
Cookie cookie2 = new Cookie("pwd","abc");
response.addCookie(cookie1);
response.addCookie(cookie2);
//页面跳转到客户端(转发,重定向)
response.sendRedirect("result.jsp");
%>
</body>
</html>
客户端获取cookie
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
out.print(cookie.getName() + " " + cookie.getValue() + "<br/>");
}
%>
</body>
</html>