1 Request 的简介和运行环境

1.HttpServletRequest 概述

我们在创建 Servlet 时会覆盖 service()方法,或 doGet()/doPost(),这些
方法都有两个参数,一个为代表请求的 request 和代表响应 response。
service 方法中的 request 的类型是 ServletRequest,而 doGet/doPost 方
法 的 request 的 类 型 是 HttpServletRequest , HttpServletRequest 是
ServletRequest 的 子 接 口 , 功 能 和 方 法 更 加 强 大 , 今 天 我 们 学 习
HttpServletRequest。

2.request 的运行流程

2 通过 request 获得【请求行】

1 通过抓包工具抓取 Http 请求

因为 request代表请求,所以我们可以通过该对象分别获得 Http请求的请求行,请求头和请求体

2 通过 request 获得请求行

html部分代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/WEBTest13/line" method="get">
<input type="text" name="username"><br> <input
type="password" name="password"><br> <input
type="submit" value="提交"><br>
</form>
</body>
</html>

servlet代码:

package p5.request;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LineServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先解决respone中文乱码
response.setContentType("text/html;charset=UTF-8"); // 1 获取客户端的请求方法
String method = request.getMethod();
System.out.println("method:"+method);
// 2 获得请求的资源相关的内容
String requestURI = request.getRequestURI();
StringBuffer requestURL = request.getRequestURL();
System.out.println("requestURI:"+requestURI);
System.out.println("requestURL:"+requestURL); // 3 获取web应用的名称
String contextPath = request.getContextPath();
System.out.println("contextPath:"+contextPath); // 4 获取地址后的参数字符串
String queryString = request.getQueryString();
System.out.println("queryString:"+
queryString); // 5 获得请求的协议版本
        String protocol = request.getProtocol();
        System.out.println("protocol:"+protocol);

} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

运行结果:

3 Resquest 获得客户机的信息

4 通过 request 获得【请求头】

servlet代码:

package header;

import java.io.IOException;
import java.util.Enumeration; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HeaderServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //1、获得指定的头
String header = request.getHeader("User-Agent");
System.out.println(header);
//2、获得所有的头的名称
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println(headerName+":"+headerValue);
} } protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/WEB15/referer">访问 headerServlet 资源</a>
<form action="/WEBTest13/line" method="get">
<input type="text" name="username"><br> <input
type="password" name="password"><br> <input
type="submit" value="提交"><br>
</form>
</body>
</html>

演示做防盗链代码实现

html部分代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/WEB15/referer">奥运会金牌100块</a>
</body>
</html>

servlet代码

package header;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class RefererServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决乱码问题
response.setContentType("text/html;charset=UTF-8"); //对该新闻的来源的进行判断
String header = request.getHeader("referer");
if(header!=null&&header.startsWith("http://localhost")){
//是从我自己的网站跳转过来的 可以看新闻
response.getWriter().write("中国确实已经拿到100块金牌....");
}else{
response.getWriter().write("你是盗链者,可耻!!"
);
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

5 通过 request 获得【请求体】

html部分的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/WEBTest13/referer">访问headerServlet资源</a>
<form action="/WEBTest13/line" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" value="提交"><br>
</form>
<hr/>
<form action="/WEBTest13/content" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="zq">足球
<input type="checkbox" name="hobby" value="pq">排球
<input type="checkbox" name="hobby" value="ppq">乒乓球<br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>

servlet部分代码:

package cotnet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ContentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //1、获得单个表单值
String username = request.getParameter("username");
System.out.println(username);
String password = request.getParameter("password");
System.out.println(password);
//2、获得多个表单的值
String[] hobbys = request.getParameterValues("hobby");
for(String hobby:hobbys){
System.out.println(hobby);
}
//3、获得所有的请求参数的名称
Enumeration<String> parameterNames = request.getParameterNames();
while(parameterNames.hasMoreElements()){
System.out.println(parameterNames.nextElement());
}
System.out.println("------------------");
//4、获得所有的参数 参数封装到一个Map<String,String[]>
Map<String, String[]> parameterMap = request.getParameterMap();
for(Map.Entry<String, String[]> entry:parameterMap.entrySet()){
System.out.println(entry.getKey());
for(String str:entry.getValue()){
System.out.println(str);
}
System.out.println("---------------------------");
} }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

6 Resquest 域对象和请求转发

1 request 是一个域对象

2 request 完成请求转发

servlet1代码:

package forward;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Servlet1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //想request域中存储数据
request.setAttribute("name", "tom"); //servlet1 将请求转发给servlet2
RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");
//执行转发的方法
dispatcher.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

servlet2代码:

package forward;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Servlet2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //从request域中取出数据
Object attribute = request.getAttribute("name"); response.getWriter().write("hello haohao..."+attribute);
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

运行结果:

3 ServletContext 域与 Request 域的生命周期比较?

4转发与重定向的区别?

5 客户端地址与服务器端地址的写法?

7 注册分析

8 注册的基本实现

1 创建user表

CREATE TABLE `user` (
`uid` varchar(50) NOT NULL,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`email` varchar(30) DEFAULT NULL,
`telephone` varchar(20) DEFAULT NULL,
`birthday` varchar(20) DEFAULT NULL,
`sex` varchar(10) DEFAULT NULL,
`state` int(11) DEFAULT NULL,
`code` varchar(64) DEFAULT NULL,
PRIMARY KEY (`uid`)
)

2 Servlet代码

package register;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner; import com.ithiema.utils.DataSourceUtils; public class RegisterServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置request的编码---只适合post方式
request.setCharacterEncoding("UTF-8"); //get方式乱码解决
//String username = request.getParameter("username");//乱码
//先用iso8859-1编码 在使用utf-8解码
//username = new String(username.getBytes("iso8859-1"),"UTF-8"); //1、获取数据
//String username = request.getParameter("username");
//System.out.println(username);
//String password = request.getParameter("password");
//..... //2、将散装的封装到javaBean
//User user = new User();
//user.setUsername(username);
//user.setPassword(password); //使用BeanUtils进行自动映射封装
//BeanUtils工作原理:将map中的数据 根据key与实体的属性的对应关系封装
//只要key的名字与实体的属性 的名字一样 就自动封装到实体中
Map<String, String[]> properties = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, properties);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} //现在这个位置 user对象已经封装好了
//手动封装uid----uuid---随机不重复的字符串32位--java代码生成后是36位
user.setUid(UUID.randomUUID().toString()); //3、将参数传递给一个业务操作方法
try {
regist(user);
} catch (SQLException e) {
e.printStackTrace();
} //4、认为注册成功跳转到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp"); } //注册的方法
public void regist(User user) throws SQLException{
//操作数据库
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)"; runner.update(sql,user.getUid(),user.getUsername(),user.getPassword(),user.getName(),
user.getEmail(),null,user.getBirthday(),user.getSex(),null,null);
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

2 User类

package register;

public class User {

    private String uid;
private String username;
private String password;
private String name;
private String email;
private String sex;
private String birthday;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email="
+ email + ", sex=" + sex + ", birthday=" + birthday + "]";
} }

9 注册的乱码解决

10 用户登录失败的信息回显

1 LoginServlet 代码 :

package login;

import java.io.IOException;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; import com.ithiema.register.User;
import com.ithiema.utils.DataSourceUtils; public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //1、获得用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2、调用一个业务方法进行该用户查询
User login = null;
try {
login = login(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3、通过user是否为null判断用户名和密码是否正确
if(login!=null){
//用户名和密码正确
//登录成功 跳转到网站的首页
response.sendRedirect(request.getContextPath());
}else{
//用户名或密码错误
//跳回当前login.jsp
//使用转发 转发到login.jsp 向request域中存储错误信息
request.setAttribute("loginInfo", "用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
} } public User login(String username,String password) throws SQLException{
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
User user = runner.query(sql, new BeanHandler<User>(User.class), username,password);
return user;
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

2 login.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>会员登录</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="css/style.css" type="text/css" /> <style>
body {
margin-top: 20px;
margin: 0 auto;
} .carousel-inner .item img {
width: 100%;
height: 300px;
} .container .row div {
/* position:relative;
float:left; */ } font {
color: #666;
font-size: 22px;
font-weight: normal;
padding-right: 17px;
}
</style>
</head>
<body> <!-- 引入header.jsp -->
<jsp:include page="/header.jsp"></jsp:include> <div class="container"
style="width: 100%; height: 460px; background: #FF2C4C url('images/loginbg.jpg') no-repeat;">
<div class="row">
<div class="col-md-7">
<!--<img src="./image/login.jpg" width="500" height="330" alt="会员登录" title="会员登录">-->
</div> <div class="col-md-5">
<div
style="width: 440px; border: 1px solid #E7E7E7; padding: 20px 0 20px 30px; border-radius: 5px; margin-top: 60px; background: #fff;">
<font>会员登录</font>USER LOGIN
<div><%=request.getAttribute("loginInfo")==null?"":request.getAttribute("loginInfo")%></div>
<form class="form-horizontal" action="/WEB15/login" method="post">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="username" name="username"
placeholder="请输入用户名">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="col-sm-6">
<input type="password" class="form-control" id="inputPassword3" name="password"
placeholder="请输入密码">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="inputPassword3"
placeholder="请输入验证码">
</div>
<div class="col-sm-3">
<img src="./image/captcha.jhtml" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label> <input type="checkbox"> 自动登录
</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <label> <input
type="checkbox"> 记住用户名
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" width="100" value="登录" name="submit"
style="background: url('./images/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;">
</div>
</div>
</form>
</div>
</div>
</div>
</div> <!-- 引入footer.jsp -->
<jsp:include page="/footer.jsp"></jsp:include> </body>
</html>

11 知识点总结

12 Xmind_总结

Request笔记的更多相关文章

  1. Servlet&Http&Request笔记

    # 今日内容:     1. Servlet     2. HTTP协议     3. Request ## Servlet:     1. 概念     2. 步骤     3. 执行原理      ...

  2. request笔记记录

    1.https请求报错解决方法,添加verify=False参数 r = requests.get(json=payload, headers=headers,verify=False) 1)由于这里 ...

  3. [原创]java WEB学习笔记47:Servlet 监听器简介, ServletContext(Application 对象), HttpSession (Session 对象), HttpServletRequest (request 对象) 监听器,利用listener理解 三个对象的生命周期

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  4. jmeter笔记(9)--JDBC Request的使用

    JDBC Request可以向数据库发送一个JDBC(Java Data Base Connectivity)请求(sql语句),获取返回的数据库数据进行操作.它需要和JDBC Connection ...

  5. python网络爬虫学习笔记(一)Request库

    一.Requests库的基本说明 引入Rquests库的代码如下 import requests 库中支持REQUEST, GET, HEAD, POST, PUT, PATCH, DELETE共7个 ...

  6. [原创]java WEB学习笔记15:域对象的属性操作(pageContext,request,session,application) 及 请求的重定向和转发

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  7. python自动化测试学习笔记-6urllib模块&request模块

    python3的urllib 模块提供了获取页面的功能. urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capat ...

  8. python request接口测试笔记(1)

    python request接口测试笔记(1) 涉及到的功能说明: 需要登录拿到token,才能进行下一个接口的请求 读取csv文件中的信息,作为接口的参数 将接口响应结果,写入csv文件,以便分析统 ...

  9. 搭建代理服务器时的笔记,request使用笔记

    request 请求笔记: 1.opation中使用form字段传参 对应 content-type': 'application/x-www-form-urlencoded',如果想要content ...

随机推荐

  1. 团体程序设计天梯赛L1-027 出租 2017-03-23 23:16 40人阅读 评论(0) 收藏

    L1-027. 出租 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 下面是新浪微博上曾经很火的一张图: 一时间网上一片求救声, ...

  2. C# 调用带输入输出参数的存储过程

    //调用存储过程执行类似于2//select count(*) from userinfo where username=username and pwd=pwd and grade=grade3// ...

  3. windows游戏开发中一个关于Visual Studio的编译链接成功,输出窗口却显示线程已退出。无法运行项目的问题

    可能是显卡驱动程序版本太高了,退回到以前的版本就ok了. 第一次遇见这个问题可把我给整疯了!! 后来又遇到一次,参考之前的解决方法,很快就搞定了!! 可见,经验可是很重要的一个东西啊.

  4. cxgrid取消过滤下拉框

    选择tableview1.optionscustomize.columnfiltering=fasle;

  5. leetcode 23. 合并K个排序链表 JAVA

    题目: 合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: ...

  6. bzoj1009GT考试

    题目链接 没啥好说的,矩阵优化+$kmp$字符串匹配 上代码: /************************************************************** Prob ...

  7. AutoCAD.Net圆弧半径标注延长线

    #region 注册RegApp public static void CheckRegApp(string regapptablename) { Database db = HostApplicat ...

  8. 常用博客 API地址

    新浪博客 http://upload.move.blog.sina.com.cn/blog_rebuild/blog/xmlrpc.php 网易博客 http://os.blog.163.com/ap ...

  9. JMeter—系统性能分析思路

    系统在工作负载中的性能受到许多因素影响,处理器速度.内存容量.网络或磁盘I/O控制器的数量以及磁盘的容量和速度是所以工作负荷的重要性能特征组件.还有其他应用程序自身的性能特征.工作负荷的特性.应用程序 ...

  10. angular的一些思考

    来公司做的第一个产品就是用angularjs来写的 我对整体这个产品架构的理解: 这套系统做的做的目的是实现所有的功能可配置化,使用MVC模型,有model层,view层,和controller层,m ...