Servlet知识总结
1.什么是Servlet?
Servlet是运行在Web服务器和应用服务器上的Java程序。它是一个中间层,负责连接来自Web浏览器或其他HTTP客户请求和HTTP服务器上的数据或应用程序。
?
2.Servlet和JSP的区别?
简单的说就是,Servlet是含有HTML的Java程序,JSP是含有Java代码的HTML页面。一般来来说,Servlet侧重于逻辑处理,JSP侧重于显示
?
3.Servlet的基本结构
public class ServletName extends HttpServlet {?
public void doPost(HttpServletRequest request,HttpServletResponse ?response) throws?ServletException, IOException {?
}?
public void doGet(HttpServletRequest request, HttpServletResponse ?response) throws?ServletException, IOException {?
}?
? ? }
4.Servlet的生命周期:
? ? ?服务器只创建一个Servlet的单一实例,每一个请求都会引发新的线程,只有第一次访问Servlet才会实例化Servlet。其生命周期如下
突例化(new) --> 初始化(init) --> services(doGet,doPost....) --> 销毁(destory)
?
? ? Servlet初始化有两种类型
? ? ? ?1)常规初始化,只是创建或载入在Servlet生命周期内用到的一些数据或执行一次计算;
? ? ? ?2)初始化参数控制的初始化,依懒web.xml中提供的初始化参数
?
5.Servlet获取表单数据:
? ? ? ?单个值的获取:request.getParameters,如果参数存在但没有相应的值,返回空的String;如要参数不存在,则返回null;
? ? ? ?多个值的获取:request.getParamenterValues,存在返回一个数组,不存在返回null;
参数名的查找:request.getParamenterNames和request.getParameterMap。
?
6.Cookie的管理:
? ? Cookie发送的三个步骤:1)创建Cookie;2)设置最大时效 3)将Cookie放到HTTP响应头
? ??Cookie的读取:1)request.getCookieS 2)循环Cookie数组
? ? 示例:
? ? ? 发送:
? ? ??//新建
Cookie cookie=new Cookie("name1","value1");//设置最大时效cookie.setMaxAge(3600);//添加到响应头response.addCookie(cookie);?
? ?读取:
? ? ??cookie[] cookies=request.getCookies();//获取
if(cookies!=null){ Cookie cookie;//循环for(int i=0;i<cookies.length;i++){ cookie=cookies[i]; cookie.getName(); cookie.getValue();}}?
?Cookie的特点:
?
HttpSession session=request.getSession(true); Integer accessCount = (Integer)session.getAttribute("accessCount"); session.setAttribute("accessCount",accessCount);?
?
?
8?Application管理
? Application?比session更大的作用域。?访问同一个web应用程序上的各种servlet,无论是不是同一session都会访问servletContext对象,都会访问这个作用域。
??ServletContext?application=this.getServletContext();?我们写的servlet和tomcat打交道。
?
?
?
参考:http://fushengfei.iteye.com/blog/783390
?
?
?
?
?
?
?
?
?
?
?