第73节:Java中的HTTPServletReauest和HTTPServletResponse

时间:2021-07-26 06:09:02

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauestHTTPServletResponse

HTTP协议

客户端与服务器端通讯的一种规则。

request:

请求行

请求头

请求体

response:

响应行

响应头

响应体

Get:

请求的时候带上的数据,在url上拼接,数据长度有限制

POST:

以流的方式写数据,数据没有限制

Content-Type: 数据类型
Content-Length: 多少长度的数据

Servlet入门:

写一个类,实现接口Servlet
注册 web.xml
<servlet>
servlet-name: 自定义
servlet-class: 全路径
<init-params> 不必要写 -servletconfig
</servlet>
<servlet-mapping>
<servlet-name>: 上面的servlet-name
<url-patter>: 以正斜杠开头
</servlet-mapping>

servlet的生命周期:

init: 默认情况下初次访问时就会执行,服务器启动时,只能执行一次
提前:
<servlet>
servlet-name:
servlet-class:
<load-on-startup>2</load-on-startup>
</servlet> service: 可以执行多次,只要进行请求
destory:销毁的使用,销毁在从服务器中移除托管或shutdown.bat
// servlet
public class Demo implements Servlet {
@Override
void service(){
...
}
} // 优化
继承接口已有的实现类
// 抽象类一定有抽象方法,不一定,有抽象方法的,一定是抽象类
class Demo2 extends HttpServlet {
void doGet();
void doPost();
}
// 源码
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response; try{
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
}catch(ClassCastException e){
throw new ServletException("non-HTTP request or response");
}
service(request,response);
}

HttpServletRequestHttpServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

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 Demo extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("来了一个请求。。。");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ServletRegister</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>demo</servlet-name>
<servlet-class>com.dashucoding.servlet.Demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

创建Server

第73节:Java中的HTTPServletReauest和HTTPServletResponse

// 创建ServletRegister ->  选择Servlet
package com.dashucoding.servlet; import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletRegister
*/
@WebServlet("/ServletRegister")
public class ServletRegister extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public ServletRegister() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletRegister
*/
public class ServletRegister extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestRegister</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>ServletRegister</display-name>
<servlet-name>ServletRegister</servlet-name>
<servlet-class>com.dashucoding.servlet.ServletRegister</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletRegister</servlet-name>
<url-pattern>/ServletRegister</url-pattern>
</servlet-mapping>
</web-app>

第73节:Java中的HTTPServletReauest和HTTPServletResponse

Servlet配置路径方式:

* : 就是个通配符,匹配任意文字。
/a*
*.aa

ServletContext

// web.xml
// 用于配置全局的参数
<context-param>
<param-name>dashu</param-name>
<param-value>dashucoding</param-value>
</context-param> // <init-param></init-param>
// 获取对象
ServletContext context = getServletContext();
// 获取参数值
String name = context.getInitParameter("dashu");
System.out.println("name=" + name);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取对象
ServletContext context = getServletContext();
// 获取参数值
String name = context.getInitParameter("dashu");
System.out.println("name=" + name);
}

获取资源文件

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 获取ServletContext对象
ServletContext context = getServletContext();
// 获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("");
System.out.println("path=" + path); /*// 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = new FileInputStream(path);
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name=" + name);*/
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 获取ServletContext对象
ServletContext context = getServletContext();
// 获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("/file/config.properties");
System.out.println("path=" + path); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = new FileInputStream(path);
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name=" + name);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // test01();
test02();
}
// alt + shift + z
private void test02() {
try {
// 获取ServletContext对象
ServletContext context = getServletContext(); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = context.getResourceAsStream("/file/config.properties");
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name02=" + name);
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // alt + shift + m
private void test01() throws FileNotFoundException, IOException {
// 获取ServletContext对象
ServletContext context = getServletContext();
// 获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("/file/config.properties");
System.out.println("path=" + path); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = new FileInputStream(path);
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name=" + name);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo03
*/
public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { // test01();
// test02();
test03();
}
private void test03() {
// TODO Auto-generated method stub
try {
// 获取ServletContext对象
ServletContext context = getServletContext(); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name02=" + name);
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// alt + shift + z
private void test02() {
try {
// 获取ServletContext对象
ServletContext context = getServletContext(); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = context.getResourceAsStream("/file/config.properties");
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name02=" + name);
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // alt + shift + m
private void test01() throws FileNotFoundException, IOException {
// 获取ServletContext对象
ServletContext context = getServletContext();
// 获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("/file/config.properties");
System.out.println("path=" + path); // 创建属性对象
Properties properties = new Properties(); // 指定载入的数据源
InputStream is = new FileInputStream(path);
properties.load(is); // 获取属性的值
String name = properties.getProperty("name");
System.out.println("name=" + name);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

ServletContext可以获取全局配置参数,可以获取web工程中的资源,存储数据,servlet简共享数据。

使用ServletContext获取数据

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 别人把数据给你了,你就要进行获取数据 String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("usrName=" + userName + "==password==" + password );
// 校验数据 if("dashu".equals(userName)&&"123".equals(password)) {
System.out.println("登录成功");
}else {
System.out.println("登录失败");
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录</h2> <form action="LoginServlet" method="get">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

登录

package com.dashucoding.servlet;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 别人把数据给你了,你就要进行获取数据 String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("usrName=" + userName + "==password==" + password );
// 校验数据
// response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) {
// System.out.println("登录成功");
pw.write("login success");
}else {
// System.out.println("登录失败");
pw.write("login failed");
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录成功</h2>
<a href="CountSrevlet">获取网站登录成功总数 </a>
</body>
</html>
package com.dashucoding.servlet;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 别人把数据给你了,你就要进行获取数据 String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("usrName=" + userName + "==password==" + password );
// 校验数据
// response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) {
// System.out.println("登录成功");
// pw.write("login success");
// 成功跳转 login_success.html
// 设置状态码
response.setStatus(302);
response.setHeader("Location", "login_success.html");
}else {
// System.out.println("登录失败");
pw.write("login failed");
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

登录次数

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class CountServlet
*/
public class CountServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 取值
int count = (int)getServletContext().getAttribute("count"); // 输出界面
response.getWriter().write("login success count == "+count);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
package com.dashucoding.servlet;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 别人把数据给你了,你就要进行获取数据 String userName = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("usrName=" + userName + "==password==" + password );
// 校验数据
// response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) {
// System.out.println("登录成功");
// pw.write("login success");
// 成功跳转 login_success.html
// 成功次数累加 存东西 // 获取以前旧的值,然后给它赋新值
Object obj = getServletContext().getAttribute("count"); int totalCount = 0; if(obj != null) {
totalCount = (int)obj;
} System.out.println("登录成功的此时是" + totalCount); // 给count赋新值 set add put
getServletContext().setAttribute("count",totalCount+1); // 设置状态码
response.setStatus(302);
response.setHeader("Location", "login_success.html");
}else {
// System.out.println("登录失败");
pw.write("login failed");
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录成功</h2>
<a href="CountServlet">获取网站登录成功总数 </a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录</h2> <form action="LoginServlet" method="get">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

路径:

	<form action="login" method="get">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/>
</form>
  <servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
// ServletContext 销毁,服务器移除,关闭服务器
只要同一个应用程序就行

作用:

  1. 获取全局配置
  2. 获取web工程中的资源
  3. 存储数据
  4. 共享数据

HttpServletRequest获取请求头

获取所有的头信息:

package com.dashucoding.servlet;

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; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// request封装了客户端提交过来的一切数据
// 拿所有的头 得到一个枚举 List集合
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String name = (String) headerNames.nextElement();
System.out.println("name=" + name);
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

得到所有

package com.dashucoding.servlet;

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; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// request封装了客户端提交过来的一切数据
// 拿所有的头 得到一个枚举 List集合
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String name = (String) headerNames.nextElement();
String value = request.getHeader(name);
System.out.println("name=" + name + ";value=" + value);
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

第73节:Java中的HTTPServletReauest和HTTPServletResponse

获取提交的信息

package com.dashucoding.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// request封装了客户端提交过来的一切数据
// 拿所有的头 得到一个枚举 List集合
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String name = (String) headerNames.nextElement();
String value = request.getHeader(name);
System.out.println("name=" + name + ";value=" + value);
} System.out.println("----------"); // 请求体,拼接过来的数据 获取客户端提交过来的数据
String name = request.getParameter("name"); System.out.println("name=" + name);
// http://localhost:8080/RequestDemo01/Demo01?name=dashucoding
// http://localhost:8080/RequestDemo01/Demo01?name=dashucoding&address=GD System.out.println("----------");
// 获取所有参数
// Enumeration<String> parameterNames = request.getParameterNames(); Map<String, String[]> map = request.getParameterMap(); Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("key="+key+",的值总数" + map.get(key).length);
String value = map.get(key)[0];
String value1 = map.get(key)[1];
String value2 = map.get(key)[2]; System.out.println(key+" == "+value + "=" + value1 + "=" + value2);
// http://localhost:8080/RequestDemo01/Demo01?name=dashucoding&address=GD
// name=zhangsan&name=lisi
} } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

get请求过来的数据已经在url地址栏上进行过编码了,所以取到的是乱码。

getParameter默认使用ISO-8859-1去解码

username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("userName="+username+"==password="+password);

post

package com.dashucoding.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 设置请求体的文字编码
request.setCharacterEncoding("UTF-8"); String username = request.getParameter("username");
String password = request.getParameter("password");
// test01(username, password); //post过来的数据乱码处理:
System.out.println("post:userName="+username+"==password="+password);
} private void test01(String username, String password) throws UnsupportedEncodingException {
System.out.println("username" + username +"password" + password);
// 转成ISO-8859-1字节数组,再utf-8去拼接
username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
System.out.println("userName="+username+"==password="+password);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("来了一个post请求");
doGet(request, response);
} }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录</h2> <form action="login" method="post">
账号:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>

HttpServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

package com.dashucoding.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 字符流的方式
// response.getWriter().write("hello response"); response.getOutputStream().write("hello".getBytes());
// 设置当前请求的处理状态码
// response.setStatus("");
// 设置一个头
// response.setHeader(name, value);
// 设置响应内容的类型,以及编码
// response.setContentType(type); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
package com.dashucoding.servlet;

import java.io.IOException;
import java.nio.charset.Charset; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub // test01(response);
// test02(response);
// 字节流 默认是使用utf-8
// response.getOutputStream().write("我是谁".getBytes());
// 参数可以指定编码方式
String csn = Charset.defaultCharset().name(); response.setHeader("Content-Type", "text/html; charset=UTF-8");
response.getOutputStream().write("我是谁".getBytes("UTF-8"));
} void test02(HttpServletResponse response){ try {
// 中文乱码 // 默认编码ISO-8859-1
response.setCharacterEncoding("UTF-8");
// 规定浏览器用什么编码去看
response.setHeader("Content-Type", "text/html; charset=UTF-8");
response.getWriter().write("我是谁");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // Ctrl + shift + f
void test01(HttpServletResponse response) {
// 字符流的方式
// response.getWriter().write("hello response"); try {
response.getOutputStream().write("hello".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 设置当前请求的处理状态码
// response.setStatus("");
// 设置一个头
// response.setHeader(name, value);
// 设置响应内容的类型,以及编码
// response.setContentType(type);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

下载资源文件

第73节:Java中的HTTPServletReauest和HTTPServletResponse

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> 默认servlet去下载<br>
<a href="download/aa.jpg">aa.jpg</a><br>
<a href="download/bb.txt">bb.txt</a><br>
<a href="download/cc.rar">cc.rar</a><br> </body>
</html>

第73节:Java中的HTTPServletReauest和HTTPServletResponse

手动下载

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> 默认servlet去下载<br>
<a href="download/aa.jpg">aa.jpg</a><br>
<a href="download/bb.txt">bb.txt</a><br>
<a href="download/cc.rar">cc.rar</a><br> <br>手动下载<br>
<a href="Demo01?filename=aa.jpg">aa.jpg</a><br>
<a href="Demo01?filename=bb.txt">bb.txt</a><br>
<a href="Demo01?filename=cc.rar">cc.rar</a><br> </body>
</html>

用于用户下载

package com.dashucoding.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo01
*/
public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 获取要下载的文件名字
String fileName = request.getParameter("filename");
// 获取这个文件在tomcat里面的绝对路径地址
String path = getServletContext().getRealPath("download/"+fileName); // 用于用户下载
response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 转化成输入流
InputStream is = new FileInputStream(path);
OutputStream os = response.getOutputStream(); int len = 0;
byte[] buffer = new byte[1024];
while( (len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
} os.close();
is.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

小结重点

HttpServletRequest:获取请求头
HttpServletResponse:对请求作出响应

如果看了觉得不错

点赞!转发!

达叔小生:往后余生,唯独有你

You and me, we are family !

90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通

简书博客: 达叔小生

https://www.jianshu.com/u/c785ece603d1

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞

第73节:Java中的HTTPServletReauest和HTTPServletResponse的更多相关文章

  1. 第83节&colon;Java中的学生管理系统分页功能

    第83节:Java中的学生管理系统分页功能 分页功能一般可以做成两种,一种是物理分页,另一种是逻辑分页.这两种功能是有各自的特点的,物理分页是查询的时候,对数据库进行访问,只是查一页数据就进行返回,其 ...

  2. 第82节&colon;Java中的学生管理系统

    第82节:Java中的学生管理系统 学生管理系统的删除功能 删除,点击超链接,点击弹出对话框式是否进行删除,如果确定,就删除,超链接执行的是js方法,在js里访问,跳转servlet,,servlet ...

  3. 第80节&colon;Java中的MVC设计模式

    第80节:Java中的MVC设计模式 前言 了解java中的mvc模式.复习以及回顾! 事务,设置自动连接提交关闭. setAutoCommit(false); conn.commit(); conn ...

  4. 第79节&colon;Java中一些要点

    第79节:Java中一些要点 前言 一些知识点忘了没,可以通过一个点引出什么内容呢?做出自己的思维导图,看看自己到了哪一步了呢 内容 如果有人问jre,jdk,jvm是什么,你怎么回答呢? jre的英 ...

  5. 第78节&colon;Java中的网络编程&lpar;上&rpar;

    第78节:Java中的网络编程(上) 前言 网络编程涉及ip,端口,协议,tcp和udp的了解,和对socket通信的网络细节. 网络编程 OSI开放系统互连 网络编程指IO加网络 TCP/IP模型: ...

  6. 第77节&colon;Java中的事务和数据库连接池和DBUtiles

    第77节:Java中的事务和数据库连接池和DBUtiles 前言 看哭你,字数:8803,承蒙关照,谢谢朋友点赞! 事务 Transaction事务,什么是事务,事务是包含一组操作,这组操作里面包含许 ...

  7. 第76节&colon;Java中的基础知识

    第76节:Java中的基础知识 设置环境,安装操作系统,安装备份,就是镜像,jdk配置环境,eclipse下载解压即可使用,下载tomcat 折佣动态代理解决网站的字符集编码问题 使用request. ...

  8. 第71节&colon;Java中HTTP和Servlet

    第71节:Java中HTTP和Servlet 前言 哭着也要看完!!!字数: 学习xml和TomCat 会写xml,看懂xml 解析对象 SAXReader reader = new SAXReade ...

  9. 第70节&colon;Java中xml和tomcat

    第70节:Java中xml和tomcat 前言: 哭着也要看完,字数: jdbc crud - statement dao java.sql.Driver The interface that eve ...

随机推荐

  1. php正则,删除字符串中的中英文标点符号

    原理很简单,正则查找字符串,然后替换 英文标点符号,正则中有专用的模式来匹配.中文则需要一一列举 代码: <?php $str = "!@#$%^&*(中'文::﹑•中'文中' ...

  2. SQL Server 跨数据库查询

    语句 SELECT * FROM 数据库A.dbo.表A a, 数据库B.dbo.表B b WHERE a.field=b.field "DBO"可以省略 如 SELECT * F ...

  3. CodeVS 数轴染色

    #include<cstdio> #include<algorithm> using namespace std; #define lson rt<<1 #defi ...

  4. SQLite事务管理

    事务管理对数据库一致性是至关重要的.数据库实现ACID属性以确保一致性.SQLite依赖于本地文件锁和页日志来实现ACID属性.SQLite只支持扁平事务,并不支持事务嵌套和保存点能力. 1.1 事务 ...

  5. 理解MVVM模式

    1.WPF的核心是数据绑定. 2.考虑这样一个场景:界面上有一个TextBox显示Person的年龄,一个Button,点击一次Button,年龄加1. 3.做一个View,上面有TextBox和Bu ...

  6. HDU 3711 Binary Number

    Binary Number Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Tot ...

  7. hdu 1062 Text Reverse 字符串

    Text Reverse                                                                                  Time L ...

  8. Eclipse 出现项目没有错但是项目名称却有红色感叹号或者红叉的解决办法

    错误的起因是本人因为一不小心点了下面圈出来的某一个按钮,具体记不清楚了(好像是"remove from build path"),然后整个项目变得很奇怪了,所有的包都变成了一个普通 ...

  9. Java学习笔记——String与StringBuffer

    String与StringBuffer String.substring(start,end); 范围为[start,end) StringBuffer.delete(start,end) 范围也是为 ...

  10. java&lowbar;工厂模式

    定义: 初学者总是把所有的代码写在一个类里面,这样是非常危险的,因为所有错误集中在一个类里了,而且代码一长,调试就很困难 所以参照工厂流水线,分车间分模块来写代码,在实际操作中也就是说将代码模块化,封 ...