servlet,filter,sessionListener,cookie,session操作

不設限發表於2011-12-15

servlet配置:


過程:程式根據客戶端傳送過來的請求,獲取客戶端要訪問的url裡面代表訪問檔案的那一部分,之後去web.xml裡面去查詢,根據所匹配的<servlet-mapping>來獲取對應的servlet-name,根據servlet-name去查詢對應的servlet-class所在的位置,根據servlet-class的位置去呼叫它裡面的方法,呼叫的時候是由apache來實現的.

web.xml中的配置:

<servlet>
<!--servlet的名字-->
<servlet-name>test</servlet-name>
<!--servlet所對應的class所在的位置-->
<servlet-class>dada.test.FirstServlet</servlet-class>
<init-param>
<!--servlet的初始化引數-->
<param-name>name</param-name>
<!--servlet的初始化引數的值-->
<param-value>dada</param-value>
</init-param>
</servlet>

<servlet-mapping>
<!--servlet的名字與servlet對應-->
<servlet-name>test</servlet-name>
<!--出發此servlet的url-->
<url-pattern>/test</url-pattern>
</servlet-mapping>

servlet檔案中處理:

private String name;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {}

@Override
public void init(ServletConfig config) throws ServletException {
name = config.getInitParameter("name");
System.out.println(name);
}

filter配置:

web.xml中的配置:

<filter>
<description>filter</description>
<filter-name>encoding</filter-name>
<filter-class>dada.test.EncodingFilter</filter-class>
<init-param>
<description>param</description>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


filter檔案中處理:

//定義初始化的字元編碼
private String encoding="ISO-8859-1";
@Override
public void destroy() {
this.encoding = null;
}

@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
request.setCharacterEncoding(encoding);
System.out.println("當前的編碼:"+request.getCharacterEncoding());
chain.doFilter(req, resp);
}


@Override
public void init(FilterConfig config) throws ServletException {
//獲取初始化的引數
String encoding1 = config.getInitParameter("encoding");
System.out.println(encoding1);
this.encoding = encoding1==null||encoding1.equals("")?encoding:encoding1;
}

session配置:
web.xml

<listener>
<listener-class>
dada.CounterListener
</listener-class>
</listener>

CounterListener類:

public class CounterListener implements HttpSessionListener {
private static long onlineNumber = 0;


//開放獲取線上人數的方法
public static long getOnlineNumber() {
return onlineNumber;
}
//當session建立時執行的方法
public void sessionCreated(HttpSessionEvent arg0) {
System.out.println("created");
onlineNumber++;
}
//當session銷燬是執行的方法
public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("created");
onlineNumber--;
}
}

呼叫監聽器輸出:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="dada.CounterListener"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <body>
本網站目前訪問人數:<%=CounterListener.getOnlineNumber()%>
  </body>
</html>

Cookie操作:

setCookie:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
Cookie cookie1 = new Cookie("username", username);
//cookie的有效期為1個月
cookie1.setMaxAge(24 * 60 * 60 * 30);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Cookie cookie2 = new Cookie("lastTime", sdf.format(new Date()));
cookie2.setMaxAge(24 * 60 * 60 * 30);
response.addCookie(cookie1);
response.addCookie(cookie2);
}

getCookie:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if (cookie.getName().equals("username")) {
out.println("使用者名稱:" + cookie.getValue());
out.println("<br>");
}
if (cookie.getName().equals("lastTime")) {
out.println("上次登入時間:" + cookie.getValue());
out.println("<br>");
}
}
}


session操作:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Integer counter = (Integer) session.getAttribute("counter");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}
session.setAttribute("counter", counter);
session.setMaxInactiveInterval(3600);

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (session.isNew()) {
out.println("這是一個新建的Session.<br><br>");
} else {
out.println("這不是一個新建的Session.<br><br>");
}
out.println("jsessionid: " + session.getId() + "<br><br>");
out.println("LastAccessedTime: " + session.getLastAccessedTime() + "<br>");
out.println("格式轉換以後的LastAccessedTime: " + new Date(session.getLastAccessedTime()) + "<br><br>");
out.println("CreationTime: " + session.getCreationTime() + "<br>");
out.println("格式轉換以後的CreationTime: " + new Date(session.getCreationTime()) + "<br><br>");
out.println("MaxInactiveInterval: " + session.getMaxInactiveInterval() + "秒<br>");
out.println("<br>使用Session物件的getAttributeNames<br>");
Enumeration enumer = session.getAttributeNames();
String name = null;
while (enumer.hasMoreElements()) {
name = (String) enumer.nextElement();
out.println("Session name:" + name + "<br>");
out.println("Session value:" + session.getAttribute(name) + "<br>");
}
// session.removeAttribute("counter");
// session.invalidate();
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}


相關文章