request常用方法:
Servlet代码:
public class RequestDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getRequestURI());
System.out.println(request.getRequestURL());
//返回请求行参数http://localhost:8080/day06/servlet/RequestDemo1?username=aaa
System.out.println(request.getQueryString());
System.out.println("=====================");
System.out.println(request.getRemoteAddr());
System.out.println(request.getRemoteHost());
System.out.println(request.getRemotePort());
System.out.println(request.getMethod());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
request获取请求头:
Servlet代码://获取请求头相关的方法
private void test1(HttpServletRequest request) {
//如果有多个该头,getHeader只能获得第一个头的值
String headValue = request.getHeader("Accept-Encoding");
System.out.println(headValue);
System.out.println("=======================");
//getHeaders可以获得所有同名该头的值
Enumeration e = request.getHeaders("Accept-Encoding");
while(e.hasMoreElements()){
String value = (String)e.nextElement();
System.out.println(value);
}
System.out.println("=======================");
//getHeaderNames可以获得所有头的名字
e = request.getHeaderNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
String value = request.getHeader(name);
System.out.println(value);
}
}
request获取请求数据:
html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>带数据给RequestDemo2</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- 向服务器提交数据的两种方式 -->
<a href="/day06/servlet/RequestDemo2?username=xxx">点点</a>
<form action="/day06/servlet/RequestDemo2" method="post">
用户名1:<input type="text" name="username"/></br>
用户名2:<input type="text" name="username"/></br>
密码:<input type="text" name="password"/></br>
<input type="submit" value="提交"/></br>
</form>
</body>
</html>
Servlet代码:
//User对象,用于封装提交的数据
public class User {
private String username[];
private String password[];
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 void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("==========获取数据方式1===========");
//常用:获取指定参数的值
String value = request.getParameter("username");
if(value!=null&&!value.trim().equals("")){
System.out.println(value);
}
System.out.println("==========获取数据方式2===========");
Enumeration e =request.getParameterNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();//username password
value = request.getParameter(name);
if(value!=null&&!value.trim().equals("")){
System.out.println(name+" = "+value);
}
}
System.out.println("==========获取数据方式3===========");
//getParameterValues得到所有同名参数的值
String[] values = request.getParameterValues("username");
for(int i =0;values!=null&&i<values.length;i++){
System.out.println(values[i]);
}
//增强for循环
// for(String v : values){
// System.out.println(v);
// }
System.out.println("==========获取数据方式4===========");
//常用:将数据封装到对象(user)中去,导入beanutils和logging包
Map<String,String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map); //username String[] 用map集合的数据填充bean
//bean的拷贝
//把表单数据封装到formbean对象中,再将formbean拷贝到user对象
//拷贝想成功,属性值必须是String或Buffer基本类型
// BeanUtils.copyProperties(user, formbean);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println((String)user.getUsername()[1]);
System.out.println("==========获取数据方式5===========");
//实际开发不常用,一般用于文件上传
InputStream in = request.getInputStream();
int len = 0;
byte buffer[] = new byte[1024];
while((len=in.read(buffer))>0){
System.out.println(new String(buffer,0,len));
}
}
request常见应用:
通过表单获取客户机数据:
html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>传数据给requestDemo3</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- url后面如果跟了中文数据,要编码后再提交 -->
<form action="/day06/servlet/RequestDemo3" method="post">
用户名:<input type="text" name="username"/></br>
密码:<input type="password" name="password"/></br>
性别:
<input type="radio" name="gender" value="male"/>男
<input type="radio" name="gender" value="female"/>女<br/>
所在地:
<select name="city">
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="cs">长沙</option>
</select>
</br>
爱好:
<input type="checkbox" name="likes" value="sing"/>唱歌
<input type="checkbox" name="likes" value="dance"/>跳舞
<input type="checkbox" name="likes" value="basketball"/>篮球
<input type="checkbox" name="likes" value="football"/>足球
</br>
备注:<textarea rows="6" cols="60" name="description"></textarea></br>
大头照:<input type="file" name="image"/></br>
<input type="hidden" name="id" value="12345"/>
<input type="submit" value="提交"/></br>
</form>
</body>
</html>
Servlet代码:
public class RequestDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(request.getParameter("username"));
System.out.println(request.getParameter("password"));
System.out.println(request.getParameter("gender"));
System.out.println(request.getParameter("city"));
String likes[] = request.getParameterValues("likes");
for(int i = 0;likes!=null&&i<likes.length;i++){
System.out.println(likes[i]);
}
System.out.println(request.getParameter("description"));
System.out.println(request.getParameter("id"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
request中文乱码问题:
html代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>中文乱码</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="/day06/servlet/RequestDemo4" method="post">
用户名:<input type="text" name="username"/></br>
<input type="submit" value="提交"/></br>
</form>
<form action="/day06/servlet/RequestDemo4" method="get">
用户名:<input type="text" name="username"/></br>
<input type="submit" value="提交"/></br>
</form>
<!-- 超链接提交的中文,服务器想不乱码,也只能手工处理,因为超链接也是get提交 -->
<a href="/day06/servlet/RequestDemo4?username=中国">点点</a>
</body>
</html>
Servlet代码:
public class RequestDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test3(request,response);
}
//测试题
private void test3(HttpServletRequest request,HttpServletResponse response)
throws IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
response.setCharacterEncoding("gb2312");
response.setHeader("Content-Type", "text/html;charset=gb2312");
response.getWriter().write(username);
}
//解决post提交的乱码
private void test2(HttpServletRequest request)
throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
System.out.println(username);
}
//解决get提交的乱码(手工处理)
private void test1(HttpServletRequest request)
throws UnsupportedEncodingException {
String username = request.getParameter("username");
username = new String(username.getBytes("iso8859-1"),"UTF-8");
System.out.println(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
request实现请求转发:
Servlet代码:
//请求转发,以及使用request域对象把数据带给转发资源
//请求转发的特点:
//1.客户端只发出一次请求,而服务器端有多个资源调用
//2.客户端浏览器地址栏没有变化
public class RequestDemo5 extends HttpServlet {
//mvc (m model(javabean) v view(jsp) c controller(servlet) )
//controller(servlet)收到请求产生数据,使用model(javabean)封装,再把javabean存到request域里面带给view(jsp),有jsp取出数据输出
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "aaaaaa";
//不同请求用不同的request域,所以不会覆盖
request.setAttribute("data", data);
//以前用ServletContext把数据转发到目标页面,但是现在不这样用,以免转发过程中,另一个请求覆盖前一个请求的数据
// this.getServletContext().setAttribute("data", data);
//request也可以实现转发
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.jsp' starting page</title>
</head>
<body>
<!-- 自动从四个域里面找到data并输出,jsp不要出现java代码 -->
${data }
<%
//和上边jsp代码一样效果
String data = (String)request.getAttribute("data");
out.write(data);
%>
</body>
</html>
请求转发的细节:
![](https://img-my.csdn.net/uploads/201304/23/1366722509_8418.png)
Servlet代码:
//forward的细节,以下代码会抛异常(forward之前,若有内容已经发送到了客户端,则报异常)
public class RequestDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "aaaaaa";
PrintWriter writer = response.getWriter();
writer.write(data);//数据写到response里
writer.close();//关闭流后,则数据真正从response写到客户端
if(true){
request.getRequestDispatcher("/index.jsp").forward(request, response);//把数据转发到jsp再发送给客户端,也一样属于此异常
return;//所以跳转后要return不执行下面转发语句,否则也会报异常
}
//以下转发会导致:java.lang.IllegalStateException:Cannot forward after response has been committed
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//forward细节:forward时,会清空response中的数据
public class RequestDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "aaaaaa";
response.getWriter().write(data);
//forward跳转之前会把response中的数据清空,所以看不到aaaaaa
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
request实现页面包含:
head.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
head<br/>
foot.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
foot<br/>
Servlet代码:
//用include实现页面包含(被包含页面不要出现全局架构标签)
public class RequestDemo8 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/public/head.jsp").include(request, response);
response.getWriter().write("hahahaha<br/>");
request.getRequestDispatcher("/public/foot.jsp").include(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
web工程中各类地址的写法:
Servlet代码:
//web工程中各类地址的写法:
//所有地址以"/"开头,
//若是给服务器用的,"/"就代表当前web应用
//若是给浏览器用的,"/"就代表网站
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.
request.getRequestDispatcher("/form1.html").forward(request, response);
//2.
response.sendRedirect("/day06/form1.html");
//3.
this.getServletContext().getRealPath("/form1.html");
//4.
this.getServletContext().getResourceAsStream("/public/foot.jsp");
//5.
/*
<a href="/day06/form1.html">点点</a>
*
<form action="/day06/form1.html">
</form>
*/
//6.
response.setHeader("refresh", "3;url='/day06/form1.html'");
/*
c:\\ 硬盘下路径用\\
http:// 浏览器网址用//
*/
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
利用referer防盗链:
首页index.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<br/>看广告<br/>
<a href="/day06/servlet/RequestDemo9">看凤姐</a>
</body>
</html>
Servlet代码:
//假设资源链接为http://localhost:8080/day06/servlet/RequsetDemo9
//防盗链
public class RequestDemo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String referer = request.getHeader("referer"); //获取客户机是从哪个资源访问服务器的
if(referer==null||!referer.startsWith("http://localhost")){//如果客户机不是从首页访问资源的
response.setStatus(302);
response.setHeader("Location", "/day06/index.jsp");
return; //用return不必用else
}
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "text/html;charset=UTF-8");
String data = "凤姐日记";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}