• Java Servlet(四):Servlet接口service工作(ServletRequest,ServletResponse对象)(jdk7+tomcat7+eclipse)


    本篇将会记录,Servlet接收客户端传递来的参数信息,并返回信息使用的对象,及这些对象的函数相关用法。

    还是在java ee工程中进行操作,在WebContent目录下创建一个login.jsp文件,并修改文件内容为:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        <form id="form1" method="POST" action="LoginServlet">
            用户名称:<input id="username" name="username" type="text" />
            用户 密码:<input id="password" name="password" type="password" />
            <br/>
            <input name="checkBox" type="checkbox" value="000"/>000
            <br/>
            <input name="checkBox" type="checkbox" value="001"/>001
            <br/>
            <input name="checkBox" type="checkbox" value="002"/>002
            <br/>
            <input name="checkBox" type="checkbox" value="003"/>003
            <br/>
            <input type="submit" name="submit" value="submit"/>
        </form>
    </body>
    </html>

    在src目录下创建一个LoginServlet类,并实现Servlet接口及实现其接口函数:

      1 package com.dx.hello;
      2 
      3 import java.io.IOException;
      4 import java.util.*;
      5 
      6 import javax.servlet.Servlet;
      7 import javax.servlet.ServletConfig;
      8 import javax.servlet.ServletException;
      9 import javax.servlet.ServletRequest;
     10 import javax.servlet.ServletResponse;
     11 import javax.servlet.http.HttpServletRequest;
     12 
     13 public class LoginServlet implements Servlet {
     14 
     15     public LoginServlet() {
     16         // TODO Auto-generated constructor stub
     17     }
     18 
     19     @Override
     20     public void destroy() {
     21         // TODO Auto-generated method stub
     22 
     23     }
     24 
     25     @Override
     26     public ServletConfig getServletConfig() {
     27         // TODO Auto-generated method stub
     28         return null;
     29     }
     30 
     31     @Override
     32     public String getServletInfo() {
     33         // TODO Auto-generated method stub
     34         return null;
     35     }
     36 
     37     @Override
     38     public void init(ServletConfig arg0) throws ServletException {
     39         // TODO Auto-generated method stub
     40 
     41     }
     42 
     43     @Override
     44     public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
     45         System.out.println("LoginService's service ... ");
     46         // ServletRequest的getParameter(String argo)
     47         String username = request.getParameter("username");
     48         String password = request.getParameter("password");
     49         System.out.println("username:" + username);
     50         System.out.println("password:" + password);
     51 
     52         // ServletRequest的getParameterNames()
     53         Enumeration<String> names = request.getParameterNames();
     54         while (names.hasMoreElements()) {
     55             String name = names.nextElement();
     56             System.out.println("--->" + name);
     57             String value = request.getParameter(name);
     58             System.out.println("--->" + value);
     59         }
     60 
     61         // ServletRequest的getParameterValues(String argo)
     62         String[] checkboxs = request.getParameterValues("checkBox");
     63         for (String value : checkboxs) {
     64             System.out.println("key:checkBox,value:" + value);
     65         }
     66 
     67         // ServletRequest的getParameterMap()
     68         Map<String, String[]> map = request.getParameterMap();
     69         for (Map.Entry<String, String[]> item : map.entrySet()) {
     70             System.out
     71                     .println("getParameterMap()---->key:" + item.getKey() + ",value:" + Arrays.asList(item.getValue()));
     72         }
     73 
     74         // 强制转化为 HttpServletRequest
     75         HttpServletRequest httpRequest = (HttpServletRequest) request;
     76         
     77         // 获取request URI
     78         String requestURI = httpRequest.getRequestURI();
     79         System.out.println("HttpServletRequest的getRequestURI():"+requestURI);
     80 
     81         // 获取request Method
     82         String method = httpRequest.getMethod();
     83         System.out.println("HttpServletRequest的getMethod():"+method);
     84         
     85         // 获取资源文件在服务器上的物理路径
     86         String relaPath = httpRequest.getRealPath("/WEB-INF/classes/jdbc.properties");
     87         System.out.println("HttpServletRequest的getRealPath():"+relaPath);
     88         
     89         // 获取请求过程中,通过uri传递的参数
     90         String queryString = httpRequest.getQueryString();
     91         System.out.println("HttpServletRequest的getQueryString():"+queryString);
     92         
     93         // 获取servlet配置路径
     94         String servletPath = httpRequest.getServletPath();
     95         System.out.println("HttpServletRequest的getServletPath():"+servletPath);
     96         
     97         // 获取servlet服務名稱。
     98         String servletName = httpRequest.getServerName();
     99         System.out.println("HttpServletRequest的getServerName():"+servletName);
    100         
    101     }
    102 
    103 }

    修改web.xml注册LoginServlet servlet:

    1     <servlet>
    2         <servlet-name>LoginServlet</servlet-name>
    3         <servlet-class>com.dx.hello.LoginServlet</servlet-class>
    4     </servlet>
    5     <servlet-mapping>
    6         <servlet-name>LoginServlet</servlet-name>
    7         <url-pattern>/LoginServlet</url-pattern>
    8     </servlet-mapping>

    运行tomcat服务,在浏览器中输入http://localhost:8080/MyServlet001/login.jsp,填写表单信息提交,查看到console输出信息:

    LoginService's service ... 
    username:111
    password:2222
    --->username
    --->111
    --->password
    --->2222
    --->checkBox
    --->001
    --->submit
    --->submit
    key:checkBox,value:001
    key:checkBox,value:002
    getParameterMap()---->key:username,value:[111]
    getParameterMap()---->key:password,value:[2222]
    getParameterMap()---->key:checkBox,value:[001, 002]
    getParameterMap()---->key:submit,value:[submit]
    HttpServletRequest的getRequestURI():/MyServlet001/LoginServlet
    HttpServletRequest的getMethod():POST
    HttpServletRequest的getRealPath():D:javaworkset.metadata.pluginsorg.eclipse.wst.server.core	mp0wtpwebappsMyServlet001WEB-INFclassesjdbc.properties
    HttpServletRequest的getQueryString():null
    HttpServletRequest的getServletPath():/LoginServlet
    HttpServletRequest的getServerName():localhost

    代码示例已经完成,接下来进行分析service接收参数的原理及相关对象:

    如何在Servlet中获取请求信息?

    1、Servlet中的service()方法用于应答请求,每次请求都会调用service()方法。(service方法是服务器调用的)

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {。。。}

    ServletRequest :封装了请求信息,可以从中获取到任何的请求信息;

    ServletResponse :封装了响应信息,可以使用该接口的方法实现用户响应的信息。

    这两个(ServletRequest 和ServletResponse )接口的实现都是服务器实现的,并在服务器调用service()方法时传入。

    可以通过以下操作去查证下:

    1 System.out.println(request);
    2 //执行上边语句将会输出如下信息:
    3 //org.apache.catalina.connector.RequestFacade@d952d1

    而这个服务器可能是tomcat,也可能是其他servlet容器。

    2、ServletRequest相关函数:

    • ServletRequest的getParameter(String argo)
    1 String username = request.getParameter("username");
    2 String password = request.getParameter("password");
    3 System.out.println("username:" + username);
    4 System.out.println("password:" + password);
    • ServletRequest的getParameterNames()
    1 Enumeration<String> names = request.getParameterNames();
    2 while (names.hasMoreElements()) {
    3   String name = names.nextElement();
    4   System.out.println("--->" + name);
    5   String value = request.getParameter(name);
    6   System.out.println("--->" + value);
    7 }
    • ServletRequest的getParameterValues(String argo)
    1 String[] checkboxs = request.getParameterValues("checkBox");
    2 for (String value : checkboxs) {
    3     System.out.println("key:checkBox,value:" + value);
    4 }
    • ServletRequest的getParameterMap()
    1 Map<String, String[]> map = request.getParameterMap();
    2 for (Map.Entry<String, String[]> item : map.entrySet()) {
    3     System.out
    4 .println("getParameterMap()---->key:" + item.getKey() + ",value:" + Arrays.asList(item.getValue()));
    5 }

    • HttpServletRequest强制转化为 HttpServletRequest
    1 HttpServletRequest httpRequest = (HttpServletRequest) request;
    • HttpServletRequest 获取request URI
    1 String requestURI = httpRequest.getRequestURI();
    2 System.out.println("HttpServletRequest的getRequestURI():"+requestURI);
    • HttpServletRequest获取request Method
    1 String method = httpRequest.getMethod();
    2 System.out.println("HttpServletRequest的getMethod():"+method);
    • HttpServletRequest获取资源文件在服务器上的物理路径
    1 String relaPath = httpRequest.getRealPath("/WEB-INF/classes/jdbc.properties");
    2 System.out.println("HttpServletRequest的getRealPath():"+relaPath);
    • HttpServletRequest获取请求过程中,通过uri传递的参数
    1 String queryString = httpRequest.getQueryString();
    2 System.out.println("HttpServletRequest的getQueryString():"+queryString);
    • HttpServletRequest获取servlet配置路径
    1 String servletPath = httpRequest.getServletPath();
    2 System.out.println("HttpServletRequest的getServletPath():"+servletPath);
    • HttpServletRequest获取servlet服務名稱。
    String servletName = httpRequest.getServerName();
    System.out.println("HttpServletRequest的getServerName():"+servletName);

     3.ServletResponse对象

    封装了响应信息,如果需要给用户什么响应,具体可以使用该接口的方法实现。

    • getWriter()方法:

    可以返回一个PrintWriter对象,调用该对象的print()方法,将把print()中的参数直接打印到客户端浏览器上。

    1         // 返回PrintWriter对象,如果想给用户什么响应,具体可以使用该接口的方法实现。
    2         PrintWriter out = response.getWriter();
    3         out.println("hello");

    setContentType(string arg0):

    设置相应内容类型:

            // 设置相应的内容类型
            response.setContentType("miscrosoft/word");

    内容类型可以参考:/tomcat/config/web.xml中设置信息。

    可以通过response对象强制转化为:HttpServletResponse对象。

    该对象比ServletResponse接口内容更多。

  • 相关阅读:
    SVN版本库修改URL路径或者IP地址
    ES-PHP向ES批量添加文档报No alive nodes found in your cluster
    ansible IP
    ansible ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6 转为数字比大小
    Centos下Yum安装PHP5.5,5.6,7.0
    centos6.8上yum安装zabbix3.2
    线性筛的理解及应用
    5分钟使用docker搭建一个WordPress
    使用 Docker-Compose 编排容器
    Bootstrap基础
  • 原文地址:https://www.cnblogs.com/yy3b2007com/p/5225183.html
Copyright © 2020-2023  润新知