Servlet
Servlet是只运行在服务器端的java类,运行Servlet程序需要将代码部署到服务器
Servlet使用
java类继承HttpServlet类,并实现doGet()和doPost()方法,网络请求方式为GET方式时执行doGet(),否则执行doPost()
public class servlet_demo extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
每个Servlet都需要在web.xml文件中进行如下配置
(可以任意指定,但不能重复)
(servlet完整路径,包名.类名)
配置Servlet的访问路径
(servlet名称,需与上面一致)
/s(用于浏览器通过url访问,如[http://localhost:8080/](http://localhost:8080/)项目名/s)
jsp页面调用Servlet可以通过表单或者超链接
Servlet应用
①获取请求信息的头部信息
通过request.getHeaderNames()等到请求信息头部内容
request.getMethod()取出提交表单的方式,post或get
request.getProtocal()取出客户发出请求时使用的协议
request.getRemoteAddr()取出客户的IP地址
②获取参数信息
通过request.getParameter(“键名”)方法得到
③ Servlet跳转
Response.setRedirect(“目标servletname”)get方式,重定向方式,request和response对象会重新产生,数据会丢失
RequestDispatcher rd=request.getRequestDispatcher(“目标servletname”);
rd.forward(request,response);请求传递方式,请求方式由上一个请求决定
④ Cookie操作(在客户端保存信息的技术)
构造方法:public Cookie(String name(Cookie名),String value(Cookie值));
Cookie类常用方法:getName()、set/getValue()、set/getMaxAge()设置和获取Cookie在客户机的有效时间,即有效秒数……
在HttpServletResponse接口在定义了addCookie()方法来向浏览器发送Cookie对象
public class SaveCookie extends HttpServlet {
protected void service(HttpServletRequest request,HttpServletResponse
response)throws ServletException,IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
Cookie tempCookie=new Cookie("temp", "87654321");
tempCookie.setMaxAge(-1);
response.addCookie(tempCookie);
Cookie cookie=new Cookie("cookie", "6666");
cookie.setMaxAge(0);
response.addCookie(cookie);
String user=request.getParameter("user");
if (user!=null) {
Cookie userCookie=new Cookie("user", user);
userCookie.setMaxAge(60*60*24);
userCookie.setPath("/");
response.addCookie(userCookie);
}
RequestDispatcher readCookie =getServletContext().getRequestDispatcher("/servlet/ReadCookie");
readCookie.include(request, response);
}
}
在HttpServletRequest接口中定义了getCookie方法来读取浏览器发送的web服务器所在的Cookie消息
public class ReadCookie extends HttpServlet {
protected Cookie getCookieValue(Cookie[] cookies,String name)
{
if (cookies!=null)
for (Cookie c: cookies)
{
if (c.getName().equals(name))
{
return c;
}
}
return null;
}
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html; charset=UTF-8");
PrintWriter out=response.getWriter();
Cookie tempCookie=getCookieValue(request.getCookies(), "temp");
if (tempCookie!=null) {
out.println("临时Cookie值:"+tempCookie.getValue()+"
");
}
else
out.println("临时Cookie未设置!
");
Cookie cookie=getCookieValue(request.getCookies(), "cookie");
if(cookie!=null)
out.println("cookie:"+cookie.getValue()+"
");
else
out.println("cookie已经被删除!
");
Cookie userCookie=getCookieValue(request.getCookies(), "user");
if (userCookie!=null) {
out.println("user:"+userCookie.getValue());
}
else
out.println("user未设置!");
}
}
Session
Session对象用来保存每个用户的信息和会话状态,由服务器端自动创建,可以实现在一个页面多个会话中保留值
与Cookie的区别:session存储在服务端,相对安全且存储长度限制也比Cookie的存储长度限制扩大了
在Servlet中使用HttpSession对象来描述Session,使用HttpServletRequest接口的getSession方法来获得一个HttpSession对象
public class SessionServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
session.setMaxInactiveInterval(60*60*24);
if (session.isNew()) {
//向session中写入值
session.setAttribute("session", "Servlet");
out.println("新会话已经建立!");
}
else
out.println("会话属性值:"+session.getAttribute("session"));
}
}
HttpSession接口主要方法
geiId:返回当前HttpSession对象的SessionID
getCreateTime:返回创建时间
getLastAccessedTime:返回上一次被访问的时间
set/getMaxInactiveInterval:用来设置和返回当前HttpSession对象的可空闲最长时间(秒),这个时间也就是当前会话的有效间隔
isvalidate:强制当前的HttpSession对象失效,这样web服务器可以立即释放该对象
set/get/removeAttribute:将一个String类的ID和一个对象相关联,并将其保存在当前的HttpSession对象中/返回(删除)一个和String类型相关联的对象
Servlet过滤器
与过滤器相关的Servlet共包含3个简单的接口(Filter、FilterChain、FilterConfig)
实现过滤器功能,必须先实现Filter接口,包含3个方法,分别为
init()方法:实例化
doFilter():用于处理请求和响应
destroy():销毁时调用
过滤器需要在web.xml中配置
FilterName
包名.类名
用来进行参数初始化工作
ParamNamel
ParamValue
过滤器映射到JSP文件
FilterName
/path/FileName.JSP
jsp页面
<%@ page language="java" import="java.util.*" contentType="text/html;charset=gb2312"%>
欢迎来到servlet过滤器
<% for(int i=0;i<5;i++)
out.println("Hello,Filter!"+ "
");
%>
过滤器
public class CopyrightFilter implements Filter {
protected FilterConfig config;
protected String date;
public void destroy() {
this.config=null;
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
PrintWriter out=response.getWriter();
out.println("
版权所有:惠州学院 ");
if (date!=null) {
out.println("
"+date+" ");
}
out.flush();
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
this.config=fConfig;
date=fConfig.getInitParameter("date");
}
}
web.xml文件
CopyrightFilter
servlets.CopyrightFilter
date
2012.9
CopyrightFilter
/*
运行结果
Servlet监视器
①监听ServletContext信息
需要实现ServletContextListener和ServletContextAttributeListener接口
web.xml文件配置:
<%
out.println("Test ServletContextListener"+"
");
application.setAttribute("userid", "1234"); //添加一个属性
application.setAttribute("userid", "12345");//替换已经添加的属性
application.removeAttribute("userid");//删除该属性
out.println("监听器已做出反应,详情请见控制台日志");
%>
//ServletListener
public class MyServletContextListener implements
ServletContextListener,ServletContextAttributeListener{
private ServletContext context=null;
@Override
public void attributeAdded(ServletContextAttributeEvent sa) {
System.out.println("增加ServletContext对象的一个属性:attributeAdded('"+sa.getName()+"',' "+sa.getValue()+"')");
}
@Override
public void attributeRemoved(ServletContextAttributeEvent sa) {
System.out.println("删除ServletContext对象中的某一个属性:attributeRemoved('"+sa.getName()+"')");
}
@Override
public void attributeReplaced(ServletContextAttributeEvent sa) {
System.out.println("替换ServletContext对象的某一个属性值:attributeReplaced('"+sa.getName()+"','"+sa.getValue()+")");
}
@Override
public void contextDestroyed(ServletContextEvent s) {
this.context=null;
System.out.println("ServletContext被释放。。。");
}
@Override
public void contextInitialized(ServletContextEvent s) {
this.context=s.getServletContext();
System.out.println("ServletContext初始化。。。");
}
}
web.xml
servlets.MyServletContextListener
②监听HTTP会话信息(Session对象的创建、销毁、会话中属性的设置请求、会话的状态和会话的绑定信息等)
用到HttpSessionAttributeListener、HttpSessionListener、HttpSessionActivationListener这三个接口,这些接口的主要方法为:
sessionCreated(HttpSessionEvent agr0):Http会话被创建时调用
sessionDestoryed(HttpSessionEvent arg0):…..释放时
sessionDidActivate(HttpSessionEvent arg0):对Http会话处于active情况下进行监听
sessionWillPassivate(….):处于passivate监听
attributeAdded(….):对Http会话中的属性添加进行监听
attributeReplaced(…):对Http会话中的属性修改进行监听
attributeRemove(…):……删除进行监听
public class MySessionListener implements
HttpSessionAttributeListener,HttpSessionListener{
ServletContext context=null;
int users=0;
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
users++;
System.out.println("sessionCreated('"+arg0.getSession().getId()+"'),"+"目前拥有"+users+"个用户");
context.setAttribute("users", new Integer(users));
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
if(users==0)
{
users=0;
}
else {
users--;
}
System.out.println("sessionCreated('"+arg0.getSession().getId()+"'),"+"目前拥有"+users+"个用户");
context.setAttribute("users", new Integer(users));
}
@Override
public void attributeAdded(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeAdded('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeRemoved('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeReplaced('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
}
web.xml配置
servlets.MySessionListener
③对客户端请求(ServletRequest)进行监听(请求对象的创建、销毁以及其属性的添加、更改和删除)
实现ServletRequestListener和ServletRequestAttributeListener接口,主要方法为:
ServletRequestListener():监听客户端请求的创建和销毁
attributeAdded(HttpSessionBinderEvent arg0):对属性添加进行监听
attributeReplaced(…):….修改
attributeRemoved(….):….删除
public class MyRequestListener implements ServletRequestListener,ServletRequestAttributeListener{
@Override
public void attributeAdded(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeAdded('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeRemoved('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("attributeReplaced('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
System.out.println("request destoryed");
}
@Override
public void requestInitialized(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Request init");
ServletRequest sr=arg0.getServletRequest();
System.out.println(sr.getRemoteAddr());
}
}
web.xml文件配置
servlets.MyRequestListener