Java Web学习笔记,显示面板loadonstartup servlet实操,缓存,监听器【诗书画唱】



学习笔记:
一、监听器Listener:
其实就是一个java类。
1、监听Session、request和application的创建和销毁
HttpSessionListener,ServletContextListener,ServletRequestListener
2、监听对象属性变化
HttpSessionAttributeListener,ServletContextAttributeListener,ServletRequestAttributeListener
3、监听Session内的对象
HttpSessionBindingListener,HttpSessionActivationListener
监听器Listener跟js中的事件一样:
项目一启动就要打印一句Hello world
方法一:使用loadonstartup servlet可以实现
方法二:使用Listener实现,当项目启动时马上运行代码
ServletContextListener用来监控application对象的创建和销毁的监听器
当启动一个javaweb项目时,会创建唯一的一个application对象
servlet,filter和listener都需要在web.xml文件中进行配置。
创建listener的步骤:
1、创建listener类
2、在web.xml文件中进行配置
代码缓存时可以使用监听器:ServletContextListener
统计本网页的访问次数。
统计在线人数。(必须使用HttpSessionListener,用来监视session对象的创建和销毁的)
"ServletRequestAttributeListener:当调用request对象的setAttribute方法时,会
运行这个监听器中的代码"
角色和权限:
不同的角色登录到系统中看到的内容是不一样的,这个就叫权限问题。
实际操作例子记录:
创建Java Web和loadonstartup servlet的方法:







创建Java Web和Listener监听器的方法:


































综合效果的例子:

package com.jy.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
@WebServlet("/ts")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//往request对象中添加了一个act属性
request.setAttribute("act", "admin");
request.setAttribute("pwd", 123);
//将request对象中的act属性移除掉
//request.removeAttribute("act");
request.setAttribute("act", "Tom");
}
}


package com.jy.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//专门用来监视application对象的创建和销毁的类
public class CtxListener implements ServletContextListener {
//当application对象被创建出来时调用的方法
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
//进行代码的缓存
String html = "<select><option>请选择</option><option>高中</option><option>大专</option><option>本科</option></select>";
//获取application对象
ServletContext application = arg0.getServletContext();
//将下拉框数据存到application对象中
application.setAttribute("edu", html);
String sex = "<input type='radio' name='sex' value='男' />男<input type='radio' name='sex' value='女' />女";
application.setAttribute("sex", sex);
}
//当application对象被销毁时调用的方法
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}


package com.jy.listener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
public class ReqAttrListener implements ServletRequestAttributeListener {
//当往request对象中添加一个属性时会执行这个方法
@Override
public void attributeAdded(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
//获取修改的属性的名字
String name = arg0.getName();
//获取修改的属性的具体的值
Object value = arg0.getValue();
System.out.println("你往request对象中添加了一个属性,属性名是:" + name);
}
//当移除掉request对象中的一个属性时会执行这个方法
@Override
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("你移除掉了reuqest对象中的一个属性");
}
//当替换掉request对象中的一个属性时会执行这个方法
@Override
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("你替换掉了request对象中的一个属性");
}
}


package com.jy.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SsListener implements HttpSessionListener {
//当创建session对象时调用
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("有用户上线啦");
//设置session在多久以后会失效,也就是多久以后会被销毁
//设置3秒以后被销毁掉
arg0.getSession().setMaxInactiveInterval(3);
ServletContext application = arg0.getSession().getServletContext();
//尝试从application对象中取出在线人数
Object objTotal = application.getAttribute("total");
if(objTotal == null) {//第一个上线的用户
application.setAttribute("total", 1);
}else {
Integer total = Integer.parseInt(objTotal.toString());
total ++;
application.setAttribute("total", total);
}
}
//当销毁session对象时调用
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
//System.out.println("这个用户下线啦");
ServletContext application = arg0.getSession().getServletContext();
Object objTotal = application.getAttribute("total");
if(objTotal != null) {
Integer total = Integer.parseInt(objTotal.toString());
total --;
application.setAttribute("total", total);
}
}
}


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>listenerJavaWeb</display-name>
<listener>
<listener-class>com.jy.listener.CtxListener</listener-class>
</listener>
<listener>
<listener-class>com.jy.listener.SsListener</listener-class>
</listener>
<listener>
<listener-class>com.jy.listener.ReqAttrListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>


<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()+path+"/";
//尝试从application中获取访问次数
Object objCt = application.getAttribute("ct");
if(objCt == null) {//第一次访问本页面
application.setAttribute("ct", 1);
}else {
Integer count = Integer.parseInt(objCt.toString());
count ++;
application.setAttribute("ct", count);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>首页,访问次数:${ct }</h1>
${edu }
${sex }
<h1>当前在线人数:${total }</h1>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>登录页面</h1>
${edu }
</body>
</html>




作业:
1、通过监听器实现在线人数统计。


package com.SSHC.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent arg0) {
arg0.getSession().setMaxInactiveInterval(3);
ServletContext application =
arg0.getSession().getServletContext();
Object objTotal = application.getAttribute("total");
if(objTotal == null) {
application.setAttribute("total", 1);
}else {
Integer total = Integer.parseInt(objTotal.toString());
total ++;
application.setAttribute("total", total);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
ServletContext application =
arg0.getSession().getServletContext();
Object objTotal = application.getAttribute("total");
if(objTotal != null) {
Integer total = Integer.parseInt(objTotal.toString());
total --;
application.setAttribute("total", total);
}
}
}


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JavaWebListener</display-name>
<listener>
<listener-class>com.SSHC.listener.OnlineListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>


<%@ page language="java" contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()+path+"/";
//尝试从application中获取访问次数
Object objCt = application.getAttribute("ct");
if(objCt == null) {//第一次访问本页面
application.setAttribute("ct", 1);
}else {
Integer count = Integer.parseInt(objCt.toString());
count ++;
application.setAttribute("ct", count);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base hreff="<%=basePath%>">
<title></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>诗书画唱提醒你!</h1>
<h1>当前在线人数:${total }</h1>
</body>
</html>


2、在项目启动时将下拉框中的数据缓存起来,必须连接数据库,在不同的jsp页面创建下拉框载入缓存数据。

create table studentInfo(
sid int primary key auto_increment,
sname varchar(100) not null,
sgender varchar(100) default '男' not null,
sage int not null,
saddress varchar(100) ,
semail varchar(100) );
insert into studentInfo(
sname ,
sgender ,
sage ,
saddress ,
semail
) values ("诗书画唱1",'男','19','北京市朝阳区','SSHC1@163. com'),
("诗书画唱2",'男','20','北京市朝阳区','SSHC2@163. com'),
("诗书画唱3",'男','30','北京市朝阳区','SSHC3@163. com');
--drop table studentDB
--select * from studentDB




package bean;
public class studentInfo {
private Integer sid ;
private String sname;
private String sgender ;
private Integer sage ;
private String saddress;
private String semail;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSgender() {
return sgender;
}
public void setSgender(String sgender) {
this.sgender = sgender;
}
public Integer getSage() {
return sage;
}
public void setSage(Integer sage) {
this.sage = sage;
}
public String getSaddress() {
return saddress;
}
public void setSaddress(String saddress) {
this.saddress = saddress;
}
public String getSemail() {
return semail;
}
public void setSemail(String semail) {
this.semail = semail;
}
}

package com.SSHC.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import bean.studentInfo;
import DAO.Dao;
@WebServlet("/FirstPageServletStart")
public class FirstPageServletStart extends HttpServlet {
private static final long serialVersionUID = 1L;
public FirstPageServletStart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Dao gd = new Dao();
List<studentInfo>list = gd.selectAll();
StringBuilder html = new StringBuilder();
boolean panDuan=true;
//奇数行为class='false'
for(studentInfo g : list) {
Integer Sid= g.getSid();
String Sname= g.getSname();
String Saddress= g.getSaddress();
String Sgender= g.getSgender();
String Semail= g.getSemail();
Integer Sage= g.getSage();
panDuan=!panDuan;
html.append("<tr class='"+panDuan+"'>");
html.append("<td ><a href='IDSelectServlet?Osid="
+Sid+"'>"
+ Sid + "</a></td>");
html.append("<td >" + Sname + "</td>");
html.append("<td >" + Sgender+ "</td>");
html.append("<td>" + Sage + "</td>");
html.append("<td >" +Saddress + "</td>");
html.append("<td >" + Semail + "</td>");
html.append("</tr>");
}
request.setAttribute("html", html);
request.getRequestDispatcher("firstPage.jsp")
.forward(request, response);
}
}

package com.SSHC.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;
import javax.servlet.annotation.WebFilter;
@WebFilter("/*")
public class CodeFilter implements Filter {
public CodeFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}

package com.SSHC.listener;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import DAO.Dao;
import bean.studentInfo;
public class huanCunListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent arg0) {
Dao gd = new Dao();
List<studentInfo>list = gd.selectAll();
StringBuilder html = new StringBuilder();
html.append("<select><option>请选择</option>");
boolean panDuan=true;
//奇数行为class='false'
for(studentInfo g : list) {
String Sname= g.getSname();
html.append("<option>"+Sname+"</option>"
);
}
html.append("</select>");
ServletContext application = arg0.getServletContext();
System.out.println(html);
application.setAttribute("XLK", html);
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}

package DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import utils.DBUtils;
import bean.studentInfo;
public class Dao {
public List<studentInfo>selectAll(){
String sql = "select * from studentInfo";
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<studentInfo>list = new ArrayList<studentInfo>();
try {
conn = DBUtils.getConn();
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
while(rs.next()) {
Integer sid = rs.getInt("sid");
String Saddress = rs.getString("Saddress");
String Sname = rs.getString("Sname");
String Sgender= rs.getString("Sgender");
String semail = rs.getString("semail");
Integer sage = rs.getInt("sage");
studentInfo g = new studentInfo();
g.setSid(sid);
g.setSage(sage);
g.setSgender(Sgender);
g.setSemail(semail);
g.setSname(Sname);
g.setSaddress(Saddress);
list.add(g);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}

package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class DBUtils {
private static String driverName;
private static String url;
private static String userName;
private static String pwd;
//静态块,随着类加载而运行的
static{
//读取db.properties文件中的内容:
Properties prop = new Properties();
InputStream is = DBUtils.class.getClassLoader()
.getResourceAsStream("db.properties");
try {
prop.load(is);
driverName = prop.getProperty("dn");
url = prop.getProperty("url");
userName = prop.getProperty("un");
pwd = prop.getProperty("up");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn(){
Connection conn = null;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,userName,pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs,
PreparedStatement pstm
,Connection conn){
try {
if(rs != null) {
rs.close();
}
if(pstm != null) {
pstm.close();
}
if(conn != null) {
conn.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

dn=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=UTF-8
un=root
up=root

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>JavaWebListener</display-name>
<listener>
<listener-class>com.SSHC.listener.OnlineListener</listener-class>
</listener>
<listener>
<listener-class>com.SSHC.listener.huanCunListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>诗书画唱</title>
</head>
<body>
${XLK}
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>诗书画唱</title>
</head>
<body>
${XLK}
</body>
</html>

