Servlet&jstl&el&过滤器&监听器&连接池--复习
2017-11-14 09:37
531 查看
Servlet的生命周期
加 jar @WebServlet( name="BaseControl", urlPatterns = {"/base1"}, initParams = { @WebInitParam(name="page1",value="/page1.jsp"), @WebInitParam(name="page2",value="/page2.jsp") } ) public class BaseControl extends HttpServlet { private Map<String ,String> map=new HashMap<>(); public BaseControl(){//1.创建 } @Override public void init(ServletConfig config) throws ServletException {//初始化 map.put("page1",config.getInitParameter("page1")); map.put("page2",config.getInitParameter("page2")); } @Override//3.做服务 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servlet success!"); // resp.setContentType("text/html"); // resp.setCharacterEncoding("UTF-8"); // PrintWriter out=resp.getWriter(); // out.print("haoba"); // out.flush(); // out.close(); String action=req.getParameter("action"); String path=map.get(action); RequestDispatcher dispatcher=req.getRequestDispatcher(path); dispatcher.forward(req,resp); } @Override//4.销毁 public void destroy() { super.destroy(); } }
jstl&el基础应用
加jar jstl-1.2.jar<%@ page import="java.util.Enumeration" %> <%@ page import="java.util.HashMap" %> <%@ page import="java.util.Vector" %><%-- Created by IntelliJ IDEA. User: fangjiejie Date: 2017/11/13 Time: 19:56 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="lyf" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="ff" uri="http://java.sun.com/jsp/jstl/fmt" %> <html> <head> <title>Title</title> </head> <body> <lyf:out value="helloworld"></lyf:out> <lyf:set var="xiao" value="ming"></lyf:set> <br> <lyf:out value="${xiao}"></lyf:out> <% session.setAttribute("li","yafang"); %> <lyf:out value="${sessionScope.li}"></lyf:out> ${sessionScope.li} <jsp:useBean id="person" class="com.LYF.Person"></jsp:useBean> <lyf:set target="${person}" property="username" value="xiaosi"></lyf:set> <lyf:if test="${person.username==ee}"> 她叫小四 </lyf:if> <lyf:remove var="xiao"></lyf:remove> <lyf:out value="${xiao}"/> <lyf:set value="20" target="${person}" property="age"></lyf:set> <lyf:choose> <lyf:when test="${person.age<=18}"> <span>年龄小于18</span> </lyf:when> <lyf:when test="${person.age>10&&person.age<50}"> <span>年龄在18岁到50岁</span> </lyf:when> <lyf:otherwise> <span>已经老了</span> </lyf:otherwise> </lyf:choose> <lyf:forEach var="i" begin="0" end="20" step="2"> <lyf:out value="${i}"></lyf:out> </lyf:forEach> <% Vector vector=new Vector(); vector.add("我"); vector.add("已"); vector.add("经"); vector.add("把"); vector.add("你"); vector.add("忘"); vector.add("了"); Enumeration myEnum=vector.elements(); request.setAttribute("myEnum",myEnum); HashMap hashMap=new HashMap(); hashMap.put("A","a"); hashMap.put("B","b"); hashMap.put("C","c"); hashMap.put("D","d"); request.setAttribute("myMap",hashMap); %> <lyf:forEach var="h" items="${requestScope.myMap}" varStatus="status"> <lyf:out value="${status.index}">:</lyf:out><lyf:out value="${h.key}">:</lyf:out> <lyf:out value="${h.value}"></lyf:out> </lyf:forEach> <br> <ff:formatNumber value="784523" pattern="0,000"></ff:formatNumber> <br> <jsp:useBean id="now" class="java.util.Date"></jsp:useBean> <ff:formatDate value="${now}" var="result" pattern="yyyy-MM-dd hh:mm:ss"></ff:formatDate> ${result} <br> <lyf:set var="ft" value="小*名*同*学"></lyf:set> <lyf:forTokens items="${ft}" delims="*" var="name" varStatus="status"> ${status.count}.${name} <br> </lyf:forTokens> </body> </html>
过滤器
package com.lyf.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import java.io.IOException; /** * Created by fangjiejie on 2017/11/13. */ @WebFilter(filterName = "encodingFilter", urlPatterns = "/*", initParams = @WebInitParam(name="encoder",value = "utf-8") ) public class EncodingFilter implements Filter{ String encoding; @Override public void init(FilterConfig filterConfig) throws ServletException { encoding=filterConfig.getInitParameter("encoder"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding(encoding); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
监听器
package com.lyf.listener; /** * Created by fangjiejie on 2017/11/13. */ import javax.servlet.ServletContextEvent; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener() public class OnlineListener implements HttpSessionListener { public static int count; // Public constructor is required by servlet spec public OnlineListener() { } // ------------------------------------------------------- // ServletContextListener implementation // ------------------------------------------------------- public void contextInitialized(ServletContextEvent sce) { /* This method is called when the servlet context is initialized(when the Web application is deployed). You can initialize servlet context related data here. */ } public void contextDestroyed(ServletContextEvent sce) { /* This method is invoked when the Servlet Context (the Web application) is undeployed or Application Server shuts down. */ } // ------------------------------------------------------- // HttpSessionListener implementation // ------------------------------------------------------- public void sessionCreated(HttpSessionEvent se) { ++count; /* Session is created. */ } public void sessionDestroyed(HttpSessionEvent se) { --count; /* Session is destroyed. */ } // ------------------------------------------------------- // HttpSessionAttributeListener implementation // ------------------------------------------------------- public void attributeAdded(HttpSessionBindingEvent sbe) { /* This method is called when an attribute is added to a session. */ } public void attributeRemoved(HttpSessionBindingEvent sbe) { /* This method is called when an attribute is removed from a session. */ } public void attributeReplaced(HttpSessionBindingEvent sbe) { /* This method is invoked when an attibute is replaced in a session. */ } }
连接池
作用:连接池是将已经创建好的连接保存在池中,当有请求来时,直接使用已经创建好的连接对数据库进行访问。这样省略了创建连接和销毁连接的过程。这样性能上得到了提高。
三种连接池:
1.DBCP连接池
加jar
commons-dbcp.jar
commons-pool.jar
配置文档 dbcp.ini
#连接设置 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&characterEncoding=UTF-8 username=root password=123321 #<!-- 初始化连接 --> initialSize=10 #最大连接数量 maxActive=50 #<!-- 最大空闲连接 --> maxIdle=20 #<!-- 最小空闲连接 --> minIdle=5 #<!-- 超时等待时间以毫秒为单位 60000毫秒/1000等于60秒 --> maxWait=60000 #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。 connectionProperties=useUnicode=true;characterEncoding=utf-8 #指定由连接池所创建的连接的自动提交(auto-commit)状态。 defaultAutoCommit=true #driver default 指定由连接池所创建的连接的只读(read-only)状态。 #如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix) defaultReadOnly= #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。 #可用值为下列之一:
代码:
package com.lyf.db; import org.apache.commons.dbcp2.BasicDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * Created by fangjiejie on 2017/11/13. */ public class DBCP { private static DataSource ds=null; private static Connection conn=null; static{ Properties pro=new Properties(); try { pro.load(DBCP.class.getClassLoader().getResourceAsStream("dbcp.ini")); ds= BasicDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection(){ try { conn=ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
2.C3P0连接池
Hibernate推荐使用它,自动清理不适用的Connection, Statement,ResultSet
加 jar
c3p0-0.9.1.2.jar
配置文档
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="automaticTestTable">con_test</property> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/bz?useUnicode=true&characterEncoding=utf-8 </property> <property name="user">root</property> <property name="password">123321</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">30</property> </named-config> </c3p0-config>
package com.lyf.db; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.activation.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * Created by fangjiejie on 2017/11/13. */ public class C3P0 { private static DataSource ds=null; private static Connection conn=null; static { ComboPooledDataSource cs=new ComboPooledDataSource("mysql") ; try { conn=cs.getConnection(); } catch (SQLException e) { e.printStackTrace(); } } public static Connection getConnection(){ return conn; } }
3.Druid连接池
性能更好
加jar
druid-1.0.26.jar
配置文档
druid.ini
#mysql数据库 url=jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&characterEncoding=UTF-8 username=root password=123321 #filters=stat #最大连接数量 maxActive=20 #初始化连接数量 initialSize=10 #超时等待时间以毫秒为单位 maxWait=12000 #最小空闲连接 minIdle=5 #校验连接池中限制时间超过minEvictableIdleTimeMillis的连接对象 timeBetweenEvictionRunsMillis=6000 #连接在池中保持空闲而不被空闲连接回收器线程(如果有)回收的最小时间值,单位毫秒 #minEvictableIdleTimeMillis= #SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前 validationQuery=SELECT now(); #指明连接是否被空闲连接回收器(如果有)进行检验. #如果检测失败,则连接将被从池中去除. testWhileIdle=true #指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个. testOnBorrow=false #指明是否在归还到池中前进行检验 testOnReturn=false #poolPreparedStatements=true #maxPoolPreparedStatementPerConnectionSize=20
package com.lyf.db; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * Created by fangjiejie on 2017/4/10. */ public class Druid { private static Connection conn=null; private static DataSource ds=null; static { Properties pro =new Properties(); try { pro.load(Druid.class.getClassLoader().getResourceAsStream("druid.ini")); ds= DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection(){ try { conn=ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; } }
项目—对记录增删改查(Servlet&jstl&el&过滤器&监听器&连接池)
github地址:https://github.com/stubbornA/reviewServletPro
相关文章推荐
- Java基础——Servlet(七)过滤器&监听器 相关
- Servlet&JSP 第五章 进阶API、过滤器与监听器
- javaee学习日记之Servlet,过滤器,拦截器,jstl,EL,jsp
- Servlet,JSP,过滤器和监听器,四个作用域和九个内置对象,EL表达式语言,自定义标签,JSTL
- SERVLETJSP Unit05:转发 、 JSP开发常见问题 & Unit09: EL、JSTL
- Web小结---Servlet,JSP,过滤器和监听器,四个作用域和九个内置对象,EL表达式语言,自定义标签,JSTL,国际化与汉字的编码
- Java复习第六天---EL&JSTL基础知识
- Web小结---Servlet,JSP,过滤器和监听器,四个作用域和九个内置对象,EL表达式语言,自定义标签,JSTL,国际化与汉字的编码
- jsp笔记整理(servlet&jstl&el&jsp标准动作)
- Web小结---Servlet,JSP,过滤器和监听器,四个作用域和九个内置对象,EL表达式语言,自定义标签,JSTL,国际化与汉字的编码
- Servlet的过滤器及监听器
- jstl el <%%>
- Servlet过滤器Filter和监听器
- Servlet过滤器和监听器总结
- jsp & el & jstl
- Servlet,过滤器,监听器,拦截器的区别
- 【jstl&el】jstl和EL的区别和使用
- JavaWeb过滤器.监听器.拦截器-原理&区别-个人总结(转)
- Servlet过滤器和监听器知识总结
- Servlet监听器过滤器