HTTPServletResponse对象
HttpServletResponse是一个接口,它的父接口是ServletResponse,在开发中通常使用HttpServletResponse
响应信息分为三部分:响应行、响应头、响应正文(响应体)
1.1 发送状态码的相关方法:
>>>1.设置状态码
setStatus(int sc) :参数就是状态码。
setStatus(int sc, String sm) :第一个参数表示状态码,第二个参数 就状态码的描述。
常见的状态码:200 响应成功
302 重定向
404 请求资源找不到
500 服务器代码出异常。
package cn.itcast.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet02 {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
ServletConfig config=this.getServletconfig();
String name=config.getServletName();
System.out.println("servlet name:"+name);
Enumeration<String> er =config.getInitParameterNames();
while(er.hasMoreElements()) {
String name1=er.nextElement();
String valule2=config.getInitParameter(name1);
System.out.println("全局初始化参数名称:"+name1);
System.out.println("全局初始化参数的值:"+valule2);
}
System.out.println("————————+——————————————");
ServletContext context=this.getServletContext();
Enumeration<String> er1=context.getInitParameterNames();
while(er.hasMoreElements()) {
String name1=er1.nextElement();
String valule2=context.getInitParameter(name1);
System.out.println("全局初始化参数名称:"+name1);
System.out.println("全局初始化参数的值:"+valule2);
}
}
private ServletConfig getServletconfig() {
// TODO Auto-generated method stub
return null;
}
private ServletContext getServletContext() {
// TODO Auto-generated method stub
return null;
}
}
HTTPServletRequest对象
HttpServletRequest它是一个接口,它的父接口ServletRequest,在开发中,常用的是带协议的请求对象。
请求消息:请求行,请求头,请求参数。
1.1 HttpServletRequest请求对象
1.获取请求行消息的相关方法:
常用的请求行方法:
>>> 1.获取请求提交的方式: getMethod();
>>> 2.获取请求的协议: getProtocol();
>>> 3.获取项目名称:getContextPath();
>>> 4.获取servlet路径:getServletPath();
>>> 5.获取请求路径: getRequsetURI(),getRequestURL();
uri对应的值:/项目名称/servlet路径
url对应的值:http://localhost:8080/uri
package cn.itcast.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet03 extends httpservlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
ServletContext context=this.getServletContext();
Enumeration<String> er =context.getInitParameterNames();
while(er.hasMoreElements()) {
String name1=er.nextElement();
String valule2=context.getInitParameter(name1);
System.out.println("全局初始化参数名称:"+name1);
System.out.println("全局初始化参数的值:"+valule2);
}
}
protected void dopost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doGet(request,response);
}
}