import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 知识点总结
* @author bruce
*
*/
public class Intro extends HttpServlet {
/**
* ServletConfig
* 该对象可以获取 web.xml中配置的初始化信息
*
*/
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
/**
* 获取ServletConfig对象
*/
ServletConfig config = this.getServletConfig();
//通过该对象获取 servlet param配置信息
config.getInitParameter("paramName");
//遍历parameter
Enumeration<String> initParameterNames = config.getInitParameterNames();
while(initParameterNames.hasMoreElements()){
String key = initParameterNames.nextElement();
String value = config.getInitParameter(key);
System.out.println("参数值为 = " + value);
}
//通过ServletConfig获取servlet Nmae
String servletName = config.getServletName();
System.out.println("Servlet Nmae = " + servletName);
/**
* 获取ServletContext
*/
ServletContext context = config.getServletContext();
context = this.getServletContext();
context = getServletContext();
//通过ServletContext 获取WebRoot下的文件路径
String webRootPath = context.getRealPath("fileName");
String webInfPath = context.getRealPath("WEB-INF/fileName");
System.out.println("路径 " + webRootPath + " / " + webInfPath);
//保存基于应用的数据
context.setAttribute("currentUser", "user");
//取除应用中的 数据
context.getAttribute("user");
Enumeration<String> attributeNames = context.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String key = attributeNames.nextElement();
System.out.println("应用中的value = " + context.getAttribute(key));
}
//获取在web.xml中配置的全局param
String initParameter = context.getInitParameter("paramName");
//遍历在web.xml中配置的全局param
Enumeration<String> initParameterNames2 = context.getInitParameterNames();
while(initParameterNames2.hasMoreElements()){
String key = initParameterNames2.nextElement();
System.out.println("value = " + context.getInitParameter(key));
}
//获取文件类型
String fileType = context.getMimeType("filePath");
System.out.println("文件类型 = " + fileType);
//获取request重定向对象
RequestDispatcher dispatcher = context.getRequestDispatcher("");
//执行重定向
dispatcher.forward(arg0, arg1);;
//获取ServerInfo
String serverInfo = context.getServerInfo();
System.out.println("获取server信息" + serverInfo);
//通过名字获取servlet 过期方法 以后版本中将会被永久的移除
context.getServlet("servletName");
//移除attribute属性值
Enumeration<String> attributeNames2 = context.getAttributeNames();
while(attributeNames2.hasMoreElements()){
String key = attributeNames2.nextElement();
if(key.equals("findKey")){
context.removeAttribute(key);
}else if(context.getAttribute(key).equals("findValue")){
context.removeAttribute(key);
}
}
}
}