Servlet監聽器在開發中的應用案例

案例:顯示登錄用戶列表,並實現踢人功能。
 

登錄的jsp頁面------------------------ html

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
    <head>  
        <title>My JSP 'login.jsp' starting page</title>  
    </head>  
    <body>  
        <form action="${pageContext.request.contextPath}/LoginServlet" method="post">  
            用戶名:  
            <input type="text" name="username"><br>  
            密    碼:  
            <input type="text" name="password"><br>  
            <input type="submit" value="登錄">  
        </form>  
    </body>  
</html>


 

處理登錄請求的servlet--------------------------- java

package com.hbsi.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hbsi.domain.User; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String password=request.getParameter("password"); User user=new User(); user.setUsername(username); user.setPassword(password); request.getSession().setAttribute("user",user); response.sendRedirect("/ListenerKicking/index.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } 


 
顯示登錄成功與否的jsp頁面------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <title>My JSP 'index.jsp' starting page</title>  
  </head>  
    
  <body>  
    歡迎您:${user.username} <br>  
  </body>  
</html>

 

顯示用戶列表的jsp頁面----------------- web

<span style="font-size:12px;color:#000000;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'userJsp.jsp' starting page</title> </head> <body> 當前在線用戶爲: <br /> <c:forEach items="${map}" var="me"> <c:url value="/KickUserServlet" var="url"> <c:param name="username" value="${me.key}"></c:param> </c:url> ${me.key}<a href="${url}">剔出去</a> <br /> </c:forEach> </body> </html> </span>

 
處理踢人請求的servlet-----------------------------
package com.hbsi.servlet;  
  
import java.io.IOException;  
import java.util.Map;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
  
public class KickUserServlet extends HttpServlet {  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        String username=request.getParameter("username");  
        username=new String(username.getBytes("iso8859-1"),"Utf-8");  
        Map map=(Map) this.getServletContext().getAttribute("map");  
        HttpSession session=(HttpSession) map.get(username);  
        if(session!=null){  
            session.invalidate();  
            map.remove(username);  
        }  
        request.getRequestDispatcher("/userJsp.jsp").forward(request, response);  
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doGet(request, response);  
    }  
  
}

servlet監聽器------------ session

package com.hbsi.listener; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import com.hbsi.domain.User; public class SessionListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent se) { Object obj=se.getValue(); if(obj instanceof User){ User user=(User) obj; HttpSession session=se.getSession(); Map map=(Map) session.getServletContext().getAttribute("map"); if(map==null){ map=new HashMap(); session.getServletContext().setAttribute("map",map); } map.put(user.getUsername(),session); } } @Override public void attributeRemoved(HttpSessionBindingEvent se) { } @Override public void attributeReplaced(HttpSessionBindingEvent se) { // TODO Auto-generated method stub } } 


實體類------------------------
<span style="font-size:12px;color:#000000;">package com.hbsi.domain;  
  
public class User {  
  private String username;  
  private String password;  
public String getUsername() {  
    return username;  
}  
public void setUsername(String username) {  
    this.username = username;  
}  
public String getPassword() {  
    return password;  
}  
public void setPassword(String password) {  
    this.password = password;  
}  
    
}  
</span>


處理亂碼的過濾器----------------
package com.hbsi.filter;  
  
import java.io.IOException;  
  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
  
public class CharseterEncodingFilter implements Filter {  
      
    private FilterConfig config = null;  
    private String defaultCharset = "UTF-8";  
  
    @Override  
    public void destroy() {  
        // TODO Auto-generated method stub  
  
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
          
          
        String charset = config.getInitParameter("charset");  
        if(charset==null){  
            charset = defaultCharset;  
        }  
        request.setCharacterEncoding(charset);  
          
        response.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html;charset="+charset);  
          
        chain.doFilter(request, response);  
          
  
    }  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
        this.config = filterConfig;  
  
    }  
  
}

配置文件-----------
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4"   
    xmlns="http://java.sun.com/xml/ns/j2ee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
    
  <filter>  
    <filter-name>CharseterEncodingFilter</filter-name>  
    <filter-class>com.hbsi.filter.CharseterEncodingFilter</filter-class>  
    <init-param>  
       <param-name>charset</param-name>  
       <param-value>UTF-8</param-value>  
    </init-param>  
  </filter>  
  <filter-mapping>  
     <filter-name>CharseterEncodingFilter</filter-name>  
     <url-pattern>/*</url-pattern>  
  </filter-mapping>  
  <listener>  
     <listener-class>com.hbsi.listener.SessionListener</listener-class>  
  </listener>  
    
  <servlet>  
    <servlet-name>LoginServlet</servlet-name>  
    <servlet-class>com.hbsi.servlet.LoginServlet</servlet-class>  
  </servlet>  
  <servlet>  
    <servlet-name>KickUserServlet</servlet-name>  
    <servlet-class>com.hbsi.servlet.KickUserServlet</servlet-class>  
  </servlet>  
  
  
  <servlet-mapping>  
    <servlet-name>LoginServlet</servlet-name>  
    <url-pattern>/LoginServlet</url-pattern>  
  </servlet-mapping>  
  <servlet-mapping>  
    <servlet-name>KickUserServlet</servlet-name>  
    <url-pattern>/KickUserServlet</url-pattern>  
  </servlet-mapping>  
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
</web-app>


項目所導的包------------
相關文章
相關標籤/搜索