Servlet-Service参数
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { }
ServletRequest:封装了请求信息,可以从中获取到任何的请求信息
ServletResponse:封装了响应信息,如果想给用户什么响应,具体可以使用该接口的方法实现。
这两个接口的实现类是服务器给予实现的,并在服务器调用service方法时传入。
1、Servlet-ServletRequest
1)获取请求参数:
> String getParameter(String name):根据请求参数的名字,返回参数值
若请求参数有多个值(例如:checkbox),该方法只能获取到第一个提交的值
>String getParameterValues(String name):根据请求参数的名字,返回请求参数对应的字符串数组
>Enumeration getParameterNames():返回参数名对应的Enumeration对象,类似于ServletConfig(或ServletContext)的getInitParameterNames()方法
>Map getParameterMap():返回请求参数的键值对: key:参数名,value:参数值,String数组类型
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("请求来了。。。"); String user = servletRequest.getParameter("username"); System.out.println(user); String interesting = servletRequest.getParameter("interesting"); System.out.println("__"+interesting); String[] param = servletRequest.getParameterValues("interesting"); /* atguigu __111*/ for (String interes:param ) { System.out.println("<>"+interes); } /* <>111 <>222*/ Enumerationnames = servletRequest.getParameterNames(); while (names.hasMoreElements()){ String name = names.nextElement(); String value = servletRequest.getParameter(name); System.out.println("- _ -"+name +" "+value); } /* - _ -username atguigu - _ -password 123 - _ -interesting 111*/ Map map = servletRequest.getParameterMap(); for (Map.Entry m:map.entrySet() ) { System.out.println(" _ " + m.getKey()+ ":" + Arrays.asList( m.getValue())); } /* _ username:[atguigu] _ password:[123] _ interesting:[111, 222]*/ HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String requestURI = httpServletRequest.getRequestURI(); System.out.println(requestURI); String method = httpServletRequest.getMethod(); System.out.println(method); String queryString = httpServletRequest.getQueryString(); System.out.println(queryString); String servletPath = httpServletRequest.getServletPath(); System.out.println(servletPath); /* /loginServlet POST null /loginServlet*/
/loginServlet
GET username=atguigu&password=123&interesting=111&interesting=222 /loginServlet}
获取请求方式:
HttpServletRequest:是ServletRequest的子接口,针对于HTTP请求所定义,里面包含了大量获取HTTP请求相关的方法
2.Servlet-ServletResponse
1)getWriter():返回PrintWriter对象,调用该对象的print()方法,将把print()中的参数直接打印到客户的浏览器上
PrintWriter printWriter = servletResponse.getWriter();
printWriter.print("HelloWorld...");
2)设置响应的内容类型
servletResponse.setContentType("application/msword");
3)void sendRedirect(String location):请求的重定向(此方法为HttpServletResponse中定义)