第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

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>

创建Server

// 创建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>

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);
}

获取资源文件

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);
} }

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);
} }

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);
} }

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);
} }

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

使用ServletContext获取数据

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>

登录

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);
} }

<!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);
} }

登录次数

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>

路径:

	<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);
} }

得到所有

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);
} }

获取提交的信息

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

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);
} }

下载资源文件

<!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>

手动下载

<!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节:Java中的学生管理系统分页功能

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

  2. 第82节:Java中的学生管理系统

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

  3. 第80节:Java中的MVC设计模式

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

  4. 第79节:Java中一些要点

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

  5. 第78节:Java中的网络编程(上)

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

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

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

  7. 第76节:Java中的基础知识

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

  8. 第71节:Java中HTTP和Servlet

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

  9. 第70节:Java中xml和tomcat

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

随机推荐

  1. PEP8 规范

    Python PEP8 编码规范中文版   原文链接:http://legacy.python.org/dev/peps/pep-0008/ item detail PEP 8 Title Style ...

  2. Yii2.0 解决“the requested URL was not found on this server”问题

    在你下了 Yii 框架,配置完路由 urlManager 后,路由访问页面会报错“the requested URL was not found on this server”,url类似于这种“ht ...

  3. git 提交代码操作

    1.修改1分支后 git add git commint2.切换到本地分支git checkout local-5.0git remote update 更新远程仓库3.git pull origin ...

  4. MySQL 聚合函数 控制流程函数

    常用的聚合函数 1. AVG() 求平均值 mysql> AVG([DISTINCT] expr) -- 返回 expr 的平均值 mysql> select AVG(age) from ...

  5. bittorrent 学习(二) LOG日志和peer管理连接

    代码中的log.h log.c比较简单 void logcmd() 记录命令  int logfile();运行日志的记录 int init_logfile() 开启log文件 源码比较清晰也很简单. ...

  6. docker常用操作备忘

    一.docker安装 参考资料:阿里云镜像加速1. 安装/升级Docker客户端 curl -fsSL https://get.docker.com | bash -s docker --mirror ...

  7. mysql8.0 1251错误

    ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER; ALTER USER '; FLUSH PR ...

  8. JSP·随笔

    1.简介 > HTML          - HTML擅长显示一个静态的网页,但是不能调用Java程序.       > Servlet   - Servlet擅长调用Java程序和后台进 ...

  9. Tomcat 500error: Could not initialize class

    Web 项目报错Could not initialize class ,出现500,说明服务器是起来了,可能是这个类的驱动有问题,缺少初始化需要的文件 查到有相关情况: 考虑是jar 包的问题,检查了 ...

  10. 一些简单的ajax的特点,方法、属性。以及ajax的创建 请求

    1.ajax的特点,基本原理,属性. ajax:页面的局部刷新 Asynchronous JavaScript And Xml JavaScript:更新局部的页面 XML:一般用于请求数据和响应数据 ...