HTTP之request请求(注册)
HTTP之request请求
request:请求
作用:获取浏览器发送过来的数据
组成部分:请求行 请求头 请求体
操作请求行
格式: 请求方式 请求资源 协议/版本
常用方法:HttpServletRequest
掌握
String getMethod():获取请求方式
String getRemoteAddr():获取ip地址
String getContextPath() :在java中获取项目名称 (/day10)
了解:
getRequestURI():获取的是 从项目名到参数之前的内容 /day10/regist
getRequestURL():获取的带协议的完整路径 http://localhost/day10/regist
String getQueryString():get请求的所有参数 username=tom&password=123
String getProtocol():获取协议和版本
例如:请求行
GET /day10/row?username=tom&password=123 HTTP/1.1
案例1:请求头的方法
web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <servlet> <servlet-name>RowServlet</servlet-name> <servlet-class>com.hjh.servlet.request.RowServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RowServlet</servlet-name> <url-pattern>/row</url-pattern> </servlet-mapping> </web-app>
RowServlet.java源码:
package com.hjh.servlet.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 RowServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求方式
String method = request.getMethod();
System.out.println("请求方式:"+method);
//获取请求资源
String uri = request.getRequestURI();
String url = request.getRequestURL().toString();
System.out.println("uri:"+uri+" "+" url:"+url);
//获取请求参数的字符串
String query = request.getQueryString();
System.out.println("请求参数字符串:"+query);
//获取协议版本
String protocol = request.getProtocol();
System.out.println("协议版本:"+protocol);
System.out.println("---------------------------以下为重要方法----------------------------");
//获取请求IP
String addr = request.getRemoteAddr();
System.out.println("请求IP:"+addr);
//获取项目名
String contextPath = request.getContextPath();
System.out.println("项目名:"+contextPath);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
启动项目,浏览器输入url“http://localhost:8080/Servlet/row?username=hjh&password=12345”,回车,eclipse中console输出为:
请求方式:GET
uri:/Servlet/row url:http://localhost:8080/Servlet/row
请求参数字符串:username=hjh&password=12345
协议版本:HTTP/1.1
---------------------------以下为重要方法----------------------------
请求IP:0:0:0:0:0:0:0:1
项目名:/Servlet
操作请求头
格式:key/value(value可以是多个值)
常用方法:
★String getHeader(String key):通过key获取指定的value (一个)
了解:
Enumeration getHeaders(String name) :通过key获取指定的value(多个)
Enumeration getHeaderNames() :获取所有的请求头的名称
int getIntHeader(String key):获取整型的请求头
long getDateHeader(String key):获取时间的请求头
重要的请求头:
user-agent:浏览器内核 msie firefox chrome
referer:页面从那里来 防盗链
案例2:请求头
web.xml配置:
<servlet>
<servlet-name>HeaderServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.HeaderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HeaderServlet</servlet-name>
<url-pattern>/header</url-pattern>
</servlet-mapping>
HeaderServlet.java源码:
package com.hjh.servlet.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 HeaderServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取浏览器内核
String user_agent = request.getHeader("user-agent");
System.out.println("浏览器内核:"+user_agent);
//获取referer
String referer = request.getHeader("referer");
if(referer==null) {
System.out.println("直接在地址栏输入的");
}else if(referer.contains("localhost")) {
System.out.println("本机输入");
}else if(referer.contains("192.167.23.156")) {
System.out.println("其他人的");
}else {
System.out.println("兄弟,盗链可耻");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
启动项目,在浏览器中输入url “http://localhost:8080/Servlet/header”,回车,在eclipse中查看console输出为:
浏览器内核:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
直接在地址栏输入的
操作请求参数 ★
username=tom&password=123&hobby=drink&hobby=sleep
常用方法:
String getParameter(String key):获取一个值
String[] getParameterValues(String key):通过一个key获取多个值
Map<String,String[]> getParameterMap():获取所有的参数名称和值
案例3:请求参数
web.xml配置:
<servlet>
<servlet-name>ParamServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.ParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParamServlet</servlet-name>
<url-pattern>/param</url-pattern>
</servlet-mapping>
ParamServlet.java源码:
package com.hjh.servlet.request;
import java.io.IOException;
import java.util.Arrays;
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 ParamServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取username
String username = request.getParameter("username");
System.out.println("用户名:"+username);
//获取爱好hobby,多个
String[] hobby = request.getParameterValues("hobby");
System.out.println("爱好hobby:"+Arrays.toString(hobby));
//获取所有的请求参数
Map<String, String[]> map = request.getParameterMap();
for (String key : map.keySet()) {
System.out.println(key+":"+Arrays.toString(map.get(key)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
浏览器中输入以下url,回车:
http://localhost:8080/Servlet/param?username=hjh&password=8888&hobby=swimming&hobby=sport
eclipse中console输出为:
用户名:hjh
爱好hobby:[swimming, sport]
username:[hjh]
password:[8888]
hobby:[swimming, sport]
请求的中文乱码
对于get请求:参数追加到地址栏,会使用utf-8编码,服务器(tomcat7)接受到请求之后,使用iso-8859-1解码,所以会出现乱码
对于post请求,参数是放在请求体中,服务器获取请求体的时候使用iso-8859-1解码,也会出现乱码
通用的方法:
new String(参数.getBytes("iso-8859-1"),"utf-8");
针对于post请求来说:只需要将请求流的编码设置成utf-8即可
request.setCharacterEncoding("utf-8");
案例1:乱码问题
web.xml配置:
<servlet>
<servlet-name>MessyCodeServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.MessyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MessyCodeServlet</servlet-name>
<url-pattern>/mcode</url-pattern>
</servlet-mapping>
MessyCodeServlet.java源码
package com.hjh.servlet.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 MessyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+":"+password);
}
}
messyCode.html页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/Servlet/mcode" method="post">
用户名:<input name="username"><br/>
密码:<input name="password"><br/>
<input type="submit">
</form>
</body>
</html>
启动项目,浏览器中输入如下url,页面显示如下,输入“hjh 88888”,回车
点击提交按钮,eclipse中console打印如下:
浏览器中输入如下url,页面显示如下,输入“王大锤 12345”,回车
点击提交按钮,eclipse中console打印如下,中文出现乱码:
解决方式:在方法第一行加入以下代码:
//设置编码 request.setCharacterEncoding("utf-8");
域对象:
request:
创建:一次请求来的时候
销毁:响应生成的时候
作用:
一次请求里面的数据
请求转发(请求链,请求串)
request.getRequestDispatcher("内部路径").forward(request,response);
案例:请求转发,url不变
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>TransmitServlet1</servlet-name>
<servlet-class>com.hjh.servlet.request.TransmitServlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>TransmitServlet2</servlet-name>
<servlet-class>com.hjh.servlet.request.TransmitServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TransmitServlet2</servlet-name>
<url-pattern>/transmit2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TransmitServlet1</servlet-name>
<url-pattern>/transmit1</url-pattern>
</servlet-mapping>
</web-app>
TransmitServlet1.java源码:
package com.hjh.servlet.request;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 请求转发:浏览器需某个资源,访问这个servlet 中没有,但是这个servlet知道哪里有;
* 这个servlet将路径告诉浏览器,浏览器根据这个路径再次访问资源
*
*/
public class TransmitServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//将请求者的姓名放入username
request.setAttribute("username", "hjh");
System.out.println(request.getServletPath()+":我这没你要的东西,去找XXX");
//请求转发
request.getRequestDispatcher("/transmit2").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
TransmitServlet2.java源码:
package com.hjh.servlet.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 TransmitServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getServletPath()+":是谁在找资源呀?是:"+
request.getAttribute("username")+";来来来,我给你");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
浏览器中输入以下url,回车:
http://localhost:8080/Servlet/transmit1
eclipse中console输出为:
/transmit1:我这没你要的东西,去找XXX
/transmit2:是谁在找资源呀?是:hjh;来来来,我给你
web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>TransmitServlet1</servlet-name>
<servlet-class>com.hjh.servlet.request.TransmitServlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>TransmitServlet2</servlet-name>
<servlet-class>com.hjh.servlet.request.TransmitServlet2</servlet-class>
</servlet>
<servlet>
<servlet-name>MsgServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.MsgServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MsgServlet</servlet-name>
<url-pattern>/msg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TransmitServlet2</servlet-name>
<url-pattern>/transmit2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TransmitServlet1</servlet-name>
<url-pattern>/transmit1</url-pattern>
</servlet-mapping>
</web-app>
注册案例:
例2-步骤分析:
1.数据库和表(day09)
2.页面(表单)
给每个字段添加name属性
还需修改表单提交的路径 method=post
3.表单提交到一个servlet(RegistServlet)
4.RegistServlet:
操作:
接受数据,封装成一个user
调用UserSerivce完成保存操作 int regist(User user)
判断结果是否符合我们预期
若int=1; 插入成功
若int!=1; 插入失败
相应的提示信息在当前的servlet不做处理,将信息转发给另一个servlet展示(MsgServlet);
5.UserService
调用dao
6.userdao 通过dbutils在数据库中插入一条记录.
建表:
DataSourseUtils.java源码:
package com.hjh.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourseUtils {
//建立连接池ds
private static ComboPooledDataSource ds = new ComboPooledDataSource();
//获取数据源
public static DataSource getDataSourse() {
return ds;
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void closeResourse(Connection conn,Statement st) {
try {
if(st!=null) {
st.close();
}else {
st = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(conn,ps)*/
public static void closeResourse(Connection conn,PreparedStatement ps) {
try {
if(ps!=null) {
ps.close();
}else {
ps = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}else {
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**释放资源closeResourse(rs)*/
public static void closeResourse(ResultSet rs) {
try {
if(rs!=null) {
rs.close();
}else {
rs = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
c3p0-config.xml,根据实际连接数据库配置,jdbcUrl加“?characterEncoding=UTF-8”是为了解决插入数据库数据中文乱码的问题:
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<!-- 基本配置 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost/hejh?characterEncoding=UTF-8</property>
<property name="user">root</property>
<property name="password">root</property>
<!--扩展配置-->
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!-- 命名的配置 -->
<named-config name="XXX">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
<property name="user">root</property>
<property name="password">1234</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatements">20</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
register.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
</head>
<body>
<form action="/Servlet/register" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="register"><br/>
</form>
</body>
RegisterServlet.java源码:
package com.hjh.servlet.request;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 com.hjh.domain.User;
import com.hjh.service.UserService;
/**
* 用户注册
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码,防止中文乱码
request.setCharacterEncoding("utf-8");
//2.封装数据
//推荐使用beanutils封装对象
User user = new User();
try {
BeanUtils.populate(user, request.getParameterMap());
//3.调用userService.register(user)方法,返回int
int i = new UserService().register(user);
//4.判断int,将信息转发答msgServlet类,交由它处理
if(i==1) {
request.setAttribute("msg", "注册成功");
request.getRequestDispatcher("/msg").forward(request, response);
}else {
request.setAttribute("msg", "注册失败");
request.getRequestDispatcher("/msg").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
MsgServlet.java源码:
package com.hjh.servlet.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 MsgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、设置编码
response.setContentType("text/html;charset=utf-8");
//2.从request域中获取msg信息
String msg = (String)request.getAttribute("msg");
//3.将msg打印到浏览器页面上
response.getWriter().print(msg);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
UserService.java
package com.hjh.service;
import java.sql.SQLException;
import com.hjh.dao.UserDao;
import com.hjh.domain.User;
public class UserService {
public User login(String username, String password) {
User user = null;
try {
user = new UserDao().findUserByUsernameAndPassword(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public int register(User user) throws Exception {
//调用UserDao
UserDao dao = new UserDao();
return dao.register(user);
}
}
UserDao.java源码
package com.hjh.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.hjh.domain.User;
import com.hjh.util.DataSourseUtils;
public class UserDao {
public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
//创建QueryRunner对象,操作sql语句
QueryRunner qr = new QueryRunner(new DataSourseUtils().getDataSourse());
//编写sql语句
String sql = "select * from user where username=? and password=?";
//执行sql BeanHandler, 将查询结果的第一条记录封装成指定的bean对象,返回
User user = qr.query(sql, new BeanHandler<User>(User.class),username,password);
//返回user对象
return user;
}
public int register(User user) throws Exception {
//创建QueryRunner对象,操作sql语句
QueryRunner qr = new QueryRunner(new DataSourseUtils().getDataSourse());
//编写sql语句
String sql = "insert into user(username,password) values(?,?)";
//执行sql
int i = qr.update(sql,user.getUsername(),user.getPassword());
return i;
}
}
User.java源码
package com.hjh.domain;
public class User {
private int id;
private String username;
private String password;
public User() {}
public User(int id,String username,String password) {
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
web.xml配置:
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.hjh.servlet.request.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MsgServlet</servlet-name>
<url-pattern>/msg</url-pattern>
</servlet-mapping>
浏览器中输入以下url:
输入框输入:王大锤,12345
点击register按钮,url显示:
查看数据库表数据:
请求转发和重定向区别:
重定向发送两次请求,请求转发一次请求
重定向地址栏发生该表,请求转发不变
重定向是从浏览器发送,请求转发是服务器内部
重定向不存在request域对象,请求转发可以使用request域对象
重定向是response的方法,请求转发是request的方法
重定向可以请求站外资源,请求转发不可以