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接口及实现其接口函数:

 package com.dx.hello;

 import java.io.IOException;
import java.util.*; import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; public class LoginServlet implements Servlet { public LoginServlet() {
// TODO Auto-generated constructor stub
} @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
} @Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
} @Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub } @Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("LoginService's service ... ");
// ServletRequest的getParameter(String argo)
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:" + username);
System.out.println("password:" + password); // ServletRequest的getParameterNames()
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
System.out.println("--->" + name);
String value = request.getParameter(name);
System.out.println("--->" + value);
} // ServletRequest的getParameterValues(String argo)
String[] checkboxs = request.getParameterValues("checkBox");
for (String value : checkboxs) {
System.out.println("key:checkBox,value:" + value);
} // ServletRequest的getParameterMap()
Map<String, String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> item : map.entrySet()) {
System.out
.println("getParameterMap()---->key:" + item.getKey() + ",value:" + Arrays.asList(item.getValue()));
} // 强制转化为 HttpServletRequest
HttpServletRequest httpRequest = (HttpServletRequest) request; // 获取request URI
String requestURI = httpRequest.getRequestURI();
System.out.println("HttpServletRequest的getRequestURI():"+requestURI); // 获取request Method
String method = httpRequest.getMethod();
System.out.println("HttpServletRequest的getMethod():"+method); // 获取资源文件在服务器上的物理路径
String relaPath = httpRequest.getRealPath("/WEB-INF/classes/jdbc.properties");
System.out.println("HttpServletRequest的getRealPath():"+relaPath); // 获取请求过程中,通过uri传递的参数
String queryString = httpRequest.getQueryString();
System.out.println("HttpServletRequest的getQueryString():"+queryString); // 获取servlet配置路径
String servletPath = httpRequest.getServletPath();
System.out.println("HttpServletRequest的getServletPath():"+servletPath); // 获取servlet服務名稱。
String servletName = httpRequest.getServerName();
System.out.println("HttpServletRequest的getServerName():"+servletName); } }

修改web.xml注册LoginServlet servlet:

     <servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dx.hello.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</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:\java\workset\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MyServlet001\WEB-INF\classes\jdbc.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()方法时传入。

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

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

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

2、ServletRequest相关函数:

  • ServletRequest的getParameter(String argo)
 String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:" + username);
System.out.println("password:" + password);
  • ServletRequest的getParameterNames()
 Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
  String name = names.nextElement();
  System.out.println("--->" + name);
  String value = request.getParameter(name);
  System.out.println("--->" + value);
}
  • ServletRequest的getParameterValues(String argo)
 String[] checkboxs = request.getParameterValues("checkBox");
for (String value : checkboxs) {
System.out.println("key:checkBox,value:" + value);
}
  • ServletRequest的getParameterMap()
 Map<String, String[]> map = request.getParameterMap();
for (Map.Entry<String, String[]> item : map.entrySet()) {
System.out
.println("getParameterMap()---->key:" + item.getKey() + ",value:" + Arrays.asList(item.getValue()));
}
  • HttpServletRequest强制转化为 HttpServletRequest
 HttpServletRequest httpRequest = (HttpServletRequest) request;
  • HttpServletRequest 获取request URI
 String requestURI = httpRequest.getRequestURI();
System.out.println("HttpServletRequest的getRequestURI():"+requestURI);
  • HttpServletRequest获取request Method
 String method = httpRequest.getMethod();
System.out.println("HttpServletRequest的getMethod():"+method);
  • HttpServletRequest获取资源文件在服务器上的物理路径
 String relaPath = httpRequest.getRealPath("/WEB-INF/classes/jdbc.properties");
System.out.println("HttpServletRequest的getRealPath():"+relaPath);
  • HttpServletRequest获取请求过程中,通过uri传递的参数
 String queryString = httpRequest.getQueryString();
System.out.println("HttpServletRequest的getQueryString():"+queryString);
  • HttpServletRequest获取servlet配置路径
 String servletPath = httpRequest.getServletPath();
System.out.println("HttpServletRequest的getServletPath():"+servletPath);
  • HttpServletRequest获取servlet服務名稱。
String servletName = httpRequest.getServerName();
System.out.println("HttpServletRequest的getServerName():"+servletName);

3.ServletResponse对象

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

  • getWriter()方法:

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

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

setContentType(string arg0):

设置相应内容类型:

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

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

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

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

上一篇:转一篇OpenSSL的例子:简单的TLS服务器


下一篇:SSH限制与更改端口、限制ROOT方式登录