美文网首页
Servlet:request常见方法

Servlet:request常见方法

作者: KaveeDJ | 来源:发表于2019-04-08 22:23 被阅读0次

request对象的类是HttpServletRequest,提供了很多有实用价值的方法

request的常见方法

  • request.getRequestURL():浏览器发出请求时的完整URL
  • request.getRequestURI():浏览器发出请求的资源名部分
  • request.getQueryString():请求行中的参数部分
  • request.getRemoteAddr():浏览器所处于的客户机的IP地址
  • request.getRemoteHost():浏览器所处于的客户机的主机名
  • request.getRemotePort():浏览器所处于的客户机使用的网络端
  • request.getLocalAddr():服务器的IP地址
  • request.getLocalName():服务器的主机名
  • request.getMethod:得到客户机请求方式,Get或者是Post
  • 重写LoginServlet
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;
    
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        
        System.out.println("浏览器发出请求时的完整URL" + req.getRequestURL());
        System.out.println("浏览器发出请求的资源名部分" + req.getRequestURI());
        System.out.println("请求行中的参数部分" + req.getQueryString());
        System.out.println("浏览器所处于的客户机的IP地址" + req.getRemoteAddr());
        System.out.println("浏览器所处于的客户机的主机名" + req.getRemoteHost());
        System.out.println("浏览器所处于的客户机使用的网络端" + req.getRemotePort());
        System.out.println("服务器的IP地址" + req.getLocalAddr());
        System.out.println("服务器的主机名" + req.getLocalName());
        System.out.println("得到客户机请求方式,Get或者是Post" + req.getMethod());
        
        String html = null;
        
        if ("admin".equals(name) && "123".equals(password)) {
            html = "<div style='color:green'>登录成功</div>";
        } else {
            html = "<div style='color:red'>登录失败</div>";
        }
        
        resp.setContentType("text/html; charset=UTF-8");
        resp.getWriter().println(html);
    }
}
  • 测试结果如下


    image.png

获取参数

  • request.getParameter():获取单值得参数
  • request.getParameterValues():获取多值参数
  • request.getParameterMap():遍历所有的参数,并返回Map类型
  • 准备一个注册页面
<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>注册页面</title>
    </head>
    
    <body>
        <form action="register" method="get">
            账号:<input type="text" name="name"> <br>
            爱好:LOL<input type="checkbox" name="hobits" value="lol">
                DOTA<input type="checkbox" name="hobits" value="dota"> <br>
            <input type="submit" value="注册">
        </form>
    </body>

</html>
  • 准备一个RegisterServlet
import java.io.IOException;
import java.util.Arrays;
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;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("获取单值参数name:" + request.getParameter("name"));
        
        String[] hobits = request.getParameterValues("hobits");
        System.out.println("获取具有多值的参数hobits:" + Arrays.asList(hobits));
        
        System.out.println("通过 getParameterMap 遍历所有的参数:  ");
        Map<String, String[]> parameters = request.getParameterMap();
        
        Set<String> paramNames = parameters.keySet();
        for (String param : paramNames) {
            String[] value = parameters.get(param);
            System.out.println(param + ":" + Arrays.asList(value));
        }
    }
}
  • 修改一下web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>

    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
        <load-on-startup>10</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>RegisterServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>
    
</web-app>
  • 测试的效果


    image.png

获取头信息

  • request.getHeader():获取浏览器传递过来的头信息
  • request.getHeaderNames():获取浏览器所有的头信息名称
  • 修改HelloServlet,如下
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("init of Hello Servlet");
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse responce) {
        
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            String value = request.getHeader(header);
            System.out.printf("%s\t%s%n", header, value);
        }
        
        
        try {
            responce.getWriter().println("<h1>Hello Servlet!</h1>");
            responce.getWriter().println(new Date().toLocaleString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
  • 运行效果


    image.png

服务端传参

  • setAttribute和getAttribute可以用来在进行服务端跳转的时候,在不同的Servlet之间进行数据共享

相关文章

网友评论

      本文标题:Servlet:request常见方法

      本文链接:https://www.haomeiwen.com/subject/irgpiqtx.html