呼和浩特网站建设会员制营销方案
什么是MVC:Model View Controller 模型,视图,控制器
以前
Servlet和JSP都可以写Java代码,为了易于维护和使用;Servlet专注于处理请求,以及控制视图跳转;JSP专注于显示数据;
用户直接访问控制层,控制层就可以直接操作数据库
servlet--CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码,处理逻辑代码
架构:加一层
程序员调用
|
JDBC
|
Mysql、Oracle、Sqlserver(不同数据库)
三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD(Dao)
View
- 展示数据
- 提供链接,发起Servlet请求(a,from,img....)
Controller(Servlet)
- 接收用户的请求(req:请求参数、Session信息...)
- 交给业务层处理对应的代码
- 控制视图的跳转
登录-->接收用户的登录请求-->处理用户的请求(获取用户登录的参数,username、password)-->交给业务层处理登录业务(判断用户名密码是否正确:事务)-->Dao层查询用户名和密码是否正确-->数据库
Filter过滤器(重点)
用来过滤网站的数据;
- 处理中文乱码
- 登录验证
开发步骤:导入依赖
<dependencies><!--Servlet依赖--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><!--JSP依赖--><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version></dependency><!--JSTL表达式的依赖--><dependency><groupId>javax.servlet.jsp.jstl</groupId><artifactId>jstl-api</artifactId><version>1.2</version></dependency><!--standard依赖--><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!--连接数据库--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency>
</dependencies>
编写过滤器
- 导包
- 编写过滤器
配置过滤器
编写servlet代码测试:
监听器listener
实现一个监听器的接口;有很多种
编写一个监听器,实现监听器的接口。
//统计网站在线人数,统计Session
public class OnlineCountListener implements HttpSessionListener {//创建session监听,看你的一举一动//一旦创建Session就会触发一次这个事件public void sessionCreated(HttpSessionEvent httpSessionEvent) {ServletContext ctx = httpSessionEvent.getSession().getServletContext();Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");if (onlineCount==null){onlineCount= new Integer(1);}else {int count=onlineCount.intValue();onlineCount=new Integer(count+1);}ctx.setAttribute("OnlineCount",onlineCount);}//销毁session监听//一旦销毁Session就会触发一次这个事件public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {ServletContext ctx = httpSessionEvent.getSession().getServletContext();Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");if (onlineCount==null){onlineCount= new Integer(0);}else {int count=onlineCount.intValue();onlineCount=new Integer(count-1);}ctx.setAttribute("OnlineCount",onlineCount);}
}
在web.xml中注册监听器
<!--注册监听器--><listener><listener-class>com.serenity.listener.OnlineCountListener</listener-class></listener>
设置一个jsp页面
<body>
<h1>当前有<span><%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span>人在线</h1>
</body>