Servlet编程-步步为营

时间:2022-06-13 13:59:35

【环境】
eclipse j2ee;
Tomcat 7.0;

【模型1】

package com.zhiqi;

import ...;

public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType ("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>test Servlet</title></head>");
out.println("<body>");
out.println("欢迎使用Servlet编程");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet- class>com.zhiqi.TestServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/fun</url-pattern>
</servlet-mapping>
</web-app>

  【模型2】getInitParameter("repeat")

package com.zhiqi;

import ...;

public class SecondServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
int repeat=Integer.parseInt (getInitParameter("repeat"));
resp.setContentType ("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>test2 Servlet</title></head>");
out.println("<body>"); for(int i=0;i<repeat;i++){
out.println("<table border= \"1\"><tr>");
out.println("<td>"+(i +1)+"</td><td>");
out.println("欢迎使用Servlet");
out.println ("</td></tr></table>");
out.println("<br>");
}
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>SecondServlet</servlet- name>
<servlet- class>com.zhiqi.SecondServlet</servlet-class> <init-param>
<param-name>repeat</param-name>
<param-value>5</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>SecondServlet</servlet- name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>

  

  【模型3】获取服务器的运行参数

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ThirdServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
doPost(req,resp);
} public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>test3 Servlet</title></head>");
out.println("<body>");
fun(req,out);
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
public void fun(HttpServletRequest req,PrintWriter out) throws IOException{
out.println("<ul>");
out.println("<li>服务器IP->"+req.getRemoteAddr()+"</li>");
out.println("<li>服务器名->"+req.getServerName()+"</li>");
out.println("<li>服务器端口->"+req.getServerPort()+"</li>");
out.println("<li>协议名->"+req.getScheme()+"</li>");
out.println("<li>协议版本->"+req.getProtocol()+"</li>");
out.println("<li>请求的方法->"+req.getMethod()+"</li>");
out.println("<li>请求的URL->"+req.getRequestURL()+"</li>");
out.println("<li>上下文路径->"+req.getContextPath()+"</li>");
out.println("<li>Servlet路径->"+req.getServletPath()+"</li>"); out.println("</ul>");
}
}

  

<?xml version="1.0" encoding="UTF-8"?>

<web-app>
<servlet>
<servlet-name>ThirdServlet</servlet-name>
<servlet-class>com.zhiqi.ThirdServlet</servlet-class> </servlet> <servlet-mapping>
<servlet-name>ThirdServlet</servlet-name>
<url-pattern>/third</url-pattern>
</servlet-mapping>
</web-app>

  Servlet编程-步步为营

【模型4】获得头信息

package com.zhiqi;

import ...

public class FourthServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
fun(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
fun(req,resp);
}
public void fun(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
String headers=null;
Enumeration e=req.getHeaderNames();
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>test4 Servlet</title></head>");
out.println("<body>");
out.println("<ul>"); while(e.hasMoreElements()){
headers=(String) e.nextElement();
if(headers!=null){
out.println("<li>"+headers+" -> "+req.getHeader(headers)+"</li>");
//out.println("->");
//out.println("<li>"+req.getHeader(headers)+"</li>");
}
}
//out.println("<li>"+"</li>");
out.println("</ul>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}

  

<?xml version="1.0" encoding="UTF-8"?>

<web-app>
<servlet>
<servlet-name>FourthServlet</servlet-name>
<servlet-class>com.zhiqi.FourthServlet</servlet-class> </servlet> <servlet-mapping>
<servlet-name>FourthServlet</servlet-name>
<url-pattern>/fourth</url-pattern>
</servlet-mapping>
</web-app>

 Servlet编程-步步为营

 【模型5】Servlet处理表单

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>login</title></head>");
out.println("<body>");
out.println("<h2>请输入登录信息</h2>");
out.println("<form method='post' action='"+req.getContextPath()//上下文路径
+"/f'"
+"'>");
out.println("<div>用户名:</div>");
out.println("<div><input type='text' name='userName' id='userName' /></div>"); out.println("<div>密码:</div>");
out.println("<div><input type='password' name='password' id='password' /></div>"); out.println("<div><input type='submit' value='提交' /></div></form>"); out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");//解决提交的表单数据中文乱码
out.println("<html>");
out.println("<head><title>login info</title></head>");
out.println("<body>");
String userName=req.getParameter("userName");
String password=req.getParameter("password");
if(userName==null || userName.length()==0 || password==null || password.length()==0){
out.println("<h2>输入用户名和密码</h2>");
out.println("<br><a href='"
+req.getContextPath()+"/f'"
+">登录</a>");
}else{
out.println("<h2>用户信息</h2>");
out.println(userName);
out.println(password);
}
out.println("</body>");
out.println("</html>");
out.flush();
out.close(); }
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app> <servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.zhiqi.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/f</url-pattern>
</servlet-mapping> </web-app>

  

  Servlet编程-步步为营

Servlet编程-步步为营

通过Servlet处理表单是非常麻烦的,1、需要调用out对象输出。2、双引号的转义

所以需要对此进行改造

模型【6】处理HTML页面的表单

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login page</title>
</head>
<body>
<h3>请输入用户名和密码</h3>
<div>
<form method="post" action="/LoginServlet2/f"><!-- 上下文路径+url-pattern -->
用户名:<input type="text" name="userName" ><br><br>
密码:<input type="password" name="password" ><br><br>
<input type="submit" value="登录">
</form>
</div> </body>
</html>

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>login</title></head>");
out.println("<body>");
out.println("<h2>请输入登录信息</h2>");
out.println("<form method='post' action='"+req.getContextPath()//上下文路径
+"/f'"
+"'>");
out.println("<div>用户名:</div>");
out.println("<div><input type='text' name='userName' id='userName' /></div>"); out.println("<div>密码:</div>");
out.println("<div><input type='password' name='password' id='password' /></div>"); out.println("<div><input type='submit' value='提交' /></div></form>"); out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");//解决提交的表单数据中文乱码
out.println("<html>");
out.println("<head><title>login info</title></head>");
out.println("<body>");
String userName=req.getParameter("userName");
String password=req.getParameter("password");
if(userName==null || userName.length()==0 || password==null || password.length()==0){
out.println("<h2>输入用户名和密码</h2>");
out.println("<br><a href='"
+req.getContextPath()+"/f'"
+">登录</a>");
}else{
out.println("<h2>用户信息</h2>");
out.println(userName);
out.println(password);
}
out.println("</body>");
out.println("</html>");
out.flush();
out.close(); }
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app> <servlet>
<servlet-name>LoginServlet2</servlet-name>
<servlet-class>com.zhiqi.LoginServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet2</servlet-name>
<url-pattern>/f</url-pattern>
</servlet-mapping> </web-app>

  Servlet编程-步步为营

Servlet编程-步步为营

【模型7】实例-网络调查表

  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>网络调查表</title>
</head>
<body>
<h2>潜在用户调查</h2>
<div>
<form method="post" action="/Example1/f">
<div>
<div style="float:left;margin-left:50px;">姓名:</div>
<div style="float:left;margin-left:20px;"><input type="text" name="name"></div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">Email:</div>
<div style="float:left;margin-left:20px;margin-top:5px;"><input type="text" name="email"></div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">年龄:</div>
<div style="float:left;margin-left:20px;margin-top:5px;">
<input type="radio" name="age" value="小于18">小于18
<input type="radio" name="age" value="18-25">18-25
<input type="radio" name="age" value="26-40">26-40
<input type="radio" name="age" value="大于40">大于40
</div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">编程时间:</div>
<div style="float:left;margin-left:50px;margin-top:5px;">
<select name="seltime">
<option value="1-2年">1-2年</option>
<option value="2-5年">2-5年</option>
<option value="5-10年">5-10年</option>
</select>
</div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">使用操作系统:</div>
<div style="float:left;margin-left:20px;margin-top:5px;">
<select name="selos">
<option value="Win XP">Win XP</option>
<option value="Linux">Linux</option>
<option value="Mac OS">Mac OS</option>
</select>
</div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">使用编程语言:</div>
<div style="float:left;margin-left:20px;margin-top:5px;">
<input type="checkbox" name="lan" value="C">C
<input type="checkbox" name="lan" value="C++">C++
<input type="checkbox" name="lan" value="JAVA">JAVA
<input type="checkbox" name="lan" value="C#">C#
<input type="checkbox" name="lan" value="Python">Python
</div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;">建议:</div>
<div style="float:left;margin-left:20px;margin-top:5px;">
<textarea name="ta"></textarea>
</div>
</div>
<div style="clear:both;">
<div style="float:left;margin-left:50px;margin-top:5px;"></div>
<div style="float:left;margin-left:20px;margin-top:5px;">
<input type="reset" name="" value="重置">
<input type="submit" name="" value="提交">
</div>
</div> </form>
</div>
</body>
</html>

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Example1 extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");
out.println("<html>");
out.println("<head><title>网络调查</title></head>");
out.println("<body>"); out.println("<h3>用户出入了以下信息</h3>"); String name=req.getParameter("name");
out.println("<p>用户姓名:"+name+"</p>");
String email=req.getParameter("email");
out.println("<p>用户邮箱:"+email+"</p>");
String age=req.getParameter("age");
out.println("<p>用户年龄:"+age+"</p>");
String seltime=req.getParameter("seltime");
out.println("<p>编程时间:"+seltime+"</p>");
String selos=req.getParameter("selos");
out.println("<p>使用平台:"+selos+"</p>"); String [] lan=req.getParameterValues("lan");//获取数组
out.println("<p>使用编程语言</p><ul>");
for(int i=0;i<lan.length;i++){
out.println("<li>"+lan[i]+"</li>");
}
out.println("</ul>"); String ta=req.getParameter("ta");
out.println("<p>建议:"+ta+"</p>");
out.println("</body>");
out.println("</html>");
}
}

  

<?xml version="1.0" encoding="UTF-8"?>

<web-app>

	<servlet>
<servlet-name>Example1</servlet-name>
<servlet-class>com.zhiqi.Example1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Example1</servlet-name>
<url-pattern>/f</url-pattern>
</servlet-mapping> </web-app>

  运行

Servlet编程-步步为营

Servlet编程-步步为营

【模型8】枚举类型获取参数以及参数值

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>满意度调查</title>
</head>
<body>
<h3>枚举类型获取参数以及参数值</h3>
<h3>你对本网站提供的内容满意吗?</h3> <form method="post" action="/Example2/f">
<input type="hidden" name="reach_reco" value="满意度调查">
<input type="submit" name="subm_cho" value="满意">
<input type="submit" name="subm_cho" value="不满意">
</form> </body>
</html>

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Example2 extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");
out.println("<html>");
out.println("<head><title>网络调查</title></head>");
out.println("<body>");
out.println("<h3>信息如下</h3>"); //获取枚举类型,可在不知道参数名的情况下输出
Enumeration e=req.getParameterNames();
while(e.hasMoreElements()){
String str=(String) e.nextElement();
out.println("<p>"+str+"</p>"); String [] s=req.getParameterValues(str);
for(int i=0;i<s.length;i++){
out.println("<p>"+s[i]+"</p>");
}
} out.println("</body>");
out.println("</html>");
}
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app> <servlet>
<servlet-name>Example2</servlet-name>
<servlet-class>com.zhiqi.Example2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Example2</servlet-name>
<url-pattern>/f</url-pattern>
</servlet-mapping> </web-app>

  

  Servlet编程-步步为营Servlet编程-步步为营

【模型9】Cookie的使用

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Cookie</title>
</head>
<body> <h3>Test Cookie</h3>
<form method="post" action="/Example8/set">
用户名:<input type="text" name="userName" id="userName" />
<br><br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form>
</body>
</html>

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Test_setCookie extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");
out.println("<html>");
out.println("<head><title>Test Cookie</title></head>");
out.println("<body>"); out.println("<h3>测试set</h3>"); String userName=req.getParameter("userName");
Cookie coo1=new Cookie("userName",userName);
coo1.setMaxAge(24*60*60*30);
resp.addCookie(coo1); out.println("<a href='"
+req.getContextPath()
+"/get'>"
+"查看Cookie</a>"); out.println("<p>上下文路径->"+req.getContextPath()+"</p>"); out.println("</body>");
out.println("</html>");
} }

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class Test_getCookie extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
req.setCharacterEncoding("utf-8");
out.println("<html>");
out.println("<head><title>Test Cookie</title></head>");
out.println("<body>"); out.println("<h3>测试get</h3>"); Cookie[] cos=req.getCookies();
Cookie c=null;
for(int i=0;i<cos.length;i++){
c=cos[i];
if(c.getName().equals("userName")){
out.println("用户名"+c.getValue());
}
} out.println("</body>");
out.println("</html>");
} }

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Test_setCookie</servlet-name>
<servlet-class>com.zhiqi.Test_setCookie</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Test_setCookie</servlet-name>
<url-pattern>/set</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>Test_getCookie</servlet-name>
<servlet-class>com.zhiqi.Test_getCookie</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Test_getCookie</servlet-name>
<url-pattern>/get</url-pattern>
</servlet-mapping> </web-app>

  Servlet编程-步步为营

Servlet编程-步步为营

Servlet编程-步步为营

【模型10】Session会话

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body> <form method="post" action="/Example9/f">
<input type="submit" value="点击" />
</form> </body>
</html>

  

package com.zhiqi;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration; import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; public class TestSession extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException{
doPost(req,resp);
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out=resp.getWriter();
out.println("<html>");
out.println("<head><title>Test Session</title></head>");
out.println("<body>"); HttpSession session=req.getSession();//创建Session
Integer count=(Integer)session.getAttribute("count");
if(count==null){
count=new Integer(1);
}else{
count=new Integer(count.intValue()+1);
}
session.setAttribute("count", count);
session.setMaxInactiveInterval(3600);
//访问次数
out.println("您已经访问了  "+count+"  次<br>");
if(session.isNew()){
out.println("这是一个新的Session<br>");
}else{
out.println("这不是一个新的Session<br>");
}
//返回一个包含分配给该 session 会话的唯一标识符的字符串
out.println("getID<br>"+session.getId()+"<br>");
//返回客户端最后一次发送与该 session 会话相关的请求的时间
out.println("getLastAccessedTime<br>"+session.getLastAccessedTime()+"<br>");
out.println("格式化后的getLastAccessedTime<br>"+new Date(session.getLastAccessedTime())+"<br>");
//返回该 session 会话被创建的时间
out.println("getCreationTime<br>"+session.getCreationTime()+"<br>");
out.println("格式化后的getCreationTime<br>"+new Date(session.getCreationTime())+"<br>");
//返回 Servlet 容器在客户端访问时保持 session 会话打开的最大时间间隔,以秒为单位。
out.println("getMaxInactiveInterval<br>"+session.getMaxInactiveInterval()+"<br>");
//返回 String 对象的枚举,String 对象包含所有绑定到该 session 会话的对象的名称
Enumeration e=session.getAttributeNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
out.println("name<br>"+name+"<br>");
//返回在该 session 会话中具有指定名称的对象
out.println("getAttribute(name)<br>"+session.getAttribute(name)+"<br>");
} out.println("</body>");
out.println("</html>");
}
}

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>TestSession</servlet-name>
<servlet-class>com.zhiqi.TestSession</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>TestSession</servlet-name>
<url-pattern>/f</url-pattern>
</servlet-mapping>
</web-app>

  Servlet编程-步步为营

【模型11】Filter过滤器

	@Override
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain fc)
throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)sreq;
HttpSession session=request.getSession();
Object o=session.getAttribute("userNames");
String path=request.getServletPath();
if(o==null && path.indexOf("login.jsp")<0){
RequestDispatcher rd=request.getRequestDispatcher("login.jsp");
rd.forward(sreq, sresp);
}else{
fc.doFilter(sreq, sresp);
}
}

  

	<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.zhiqi.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

  此时如果获取不到session对象啊会把主页mian.jsp转发

【模型12】HttpSessionAttributeListener监听

package com.zhiqi.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent; public class SessionAttributeListener implements HttpSessionAttributeListener { @Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("添加的属性名"+httpSessionBindingEvent.getName()+"添加的属性值"+httpSessionBindingEvent.getValue()); } @Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("删除的属性名"+httpSessionBindingEvent.getName()+"删除的属性值"+httpSessionBindingEvent.getValue()); } @Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
// TODO Auto-generated method stub } }

  

	<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.zhiqi.web.Logout</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>