前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第73节:Java中的HTTPServletReauest和HTTPServletResponse

第73节:Java中的HTTPServletReauest和HTTPServletResponse

作者头像
达达前端
发布2019-07-03 15:05:49
8800
发布2019-07-03 15:05:49
举报
文章被收录于专栏:达达前端

第73节:Java中的HTTPServletReauestHTTPServletResponse

HTTP协议

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

request: 请求行 请求头 请求体

response: 响应行 响应头 响应体

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

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

代码语言:javascript
复制
Content-Type: 数据类型
Content-Length: 多少长度的数据

Servlet入门:

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

servlet的生命周期:

代码语言:javascript
复制
init: 默认情况下初次访问时就会执行,服务器启动时,只能执行一次
提前:
<servlet>
 servlet-name:
 servlet-class:
 <load-on-startup>2</load-on-startup>
</servlet>

service: 可以执行多次,只要进行请求
destory:销毁的使用,销毁在从服务器中移除托管或shutdown.bat
代码语言:javascript
复制
// servlet
public class Demo implements Servlet {
 @Override
 void service(){
 ...
 }
}

// 优化
继承接口已有的实现类
// 抽象类一定有抽象方法,不一定,有抽象方法的,一定是抽象类
class Demo2 extends HttpServlet {
 void doGet();
 void doPost();
}
代码语言:javascript
复制
// 源码
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

效果

代码语言:javascript
复制
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);
    }
}
代码语言:javascript
复制
<?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

效果

代码语言:javascript
复制
// 创建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);
    }

}
代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
<?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配置路径方式:

代码语言:javascript
复制
* : 就是个通配符,匹配任意文字。
/a*
*.aa

ServletContext

代码语言:javascript
复制
// web.xml
// 用于配置全局的参数
<context-param>
 <param-name>dashu</param-name>
 <param-value>dashucoding</param-value>
</context-param>

// <init-param></init-param>
代码语言:javascript
复制
// 获取对象
ServletContext context = getServletContext();
// 获取参数值
String name = context.getInitParameter("dashu");
System.out.println("name=" + name);
代码语言:javascript
复制
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 获取对象
    ServletContext context = getServletContext();
    // 获取参数值
    String name = context.getInitParameter("dashu");
    System.out.println("name=" + name);
}

获取资源文件

效果

代码语言:javascript
复制
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);
    }

}

效果

效果

效果

代码语言:javascript
复制
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);
    }

}

效果

效果

代码语言:javascript
复制
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);
    }

}

效果

效果

代码语言:javascript
复制
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获取数据

效果

代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
<!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>

效果

效果

效果

效果

效果

登录

代码语言:javascript
复制
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);
    }

}

效果

效果

效果

代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>登录成功</h2>
    <a href="CountSrevlet">获取网站登录成功总数 </a>
</body>
</html>
代码语言:javascript
复制
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);
    }

}

登录次数

效果

代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>登录成功</h2>
    <a href="CountServlet">获取网站登录成功总数 </a>
</body>
</html>
代码语言:javascript
复制
<!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>

效果

效果

路径:

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

作用:

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

HttpServletRequest获取请求头

获取所有的头信息:

代码语言:javascript
复制
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);
    }

}

效果

效果

得到所有

代码语言:javascript
复制
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);
    }

}

效果

获取提交的信息

代码语言:javascript
复制
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去解码

代码语言:javascript
复制
username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("userName="+username+"==password="+password);

post

代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
<!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

效果

代码语言:javascript
复制
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);
    }

}
代码语言:javascript
复制
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);
    }

}

下载资源文件

效果

代码语言:javascript
复制
<!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>

效果

手动下载

代码语言:javascript
复制
<!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>

用于用户下载

代码语言:javascript
复制
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);
    }

}

小结重点

代码语言:javascript
复制
HttpServletRequest:获取请求头
HttpServletResponse:对请求作出响应

如果看了觉得不错

点赞!转发!

达叔小生:往后余生,唯独有你 You and me, we are family ! 90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通 简书博客: 达叔小生 https://www.jianshu.com/u/c785ece603d1

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.01.21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建Server
  • 登录
  • HttpServletRequest获取请求头
  • HttpServletResponse
  • 小结重点
  • 结语
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档