Life Cycle of Servlet
plus 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. create
}
@Override
public void init(ServletConfig config) throws ServletException {//Initialization
map.put("page1",config.getInitParameter("page1"));
map.put("page2",config.getInitParameter("page2"));
}
@Override//3. do services
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. destruction
public void destroy() {
super.destroy();
}
}
Basic application of JSTL & El
Add 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}">
//Her name is Xiao Si.
</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>Age less than 18</span>
</lyf:when>
<lyf:when test="${person.age>10&&person.age<50}">
<span>Age ranges from 18 to 50</span>
</lyf:when>
<lyf:otherwise>
<span>It's getting old.</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("I");
vector.add("already");
vector.add("through");
vector.add("hold");
vector.add("you");
vector.add("forget");
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="Small*name*with*learn"></lyf:set>
<lyf:forTokens items="${ft}" delims="*" var="name" varStatus="status">
${status.count}.${name} <br>
</lyf:forTokens>
</body>
</html>
Filter
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() {
}
}
Monitor
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.
*/
}
}
Connection pool
Effect:
Connection pool is to store the created connections in the pool, and when a request comes, access the database directly using the created connections. This omits the process of creating and destroying connections. This improves the performance.
Three connection pools:
1.DBCP connection pool
Add jar
commons-dbcp.jar
commons-pool.jar
Configuration document dbcp.ini
#connections setting up
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&characterEncoding=UTF-8
username=root
password=123321
#<!-- Initialize connection -->
initialSize=10
#Maximum number of connections
maxActive=50
#<!-- Maximum idle connection -->
maxIdle=20
#<!-- Minimum idle connection -->
minIdle=5
#<!-- The timeout waiting time is 60,000 milliseconds in milliseconds/1000 Equal to 60 seconds. -->
maxWait=60000
#The format of the join attribute attributes attached to the JDBC driver when establishing a connection must be as follows: [Property name = property;]
#Note that the attributes "user" and "password" will be passed explicitly, so there is no need to include them here.
connectionProperties=useUnicode=true;characterEncoding=utf-8
#Specifies the auto-commit state of the connection created by the connection pool.
defaultAutoCommit=true
#driver default specifies the read-only state of the connection created by the connection pool.
#If this value is not set, the "setReadOnly" method will not be invoked. (Some drivers do not support read-only mode, such as Informix)
defaultReadOnly=
#driver default specifies the transaction level (Transaction Isolation) of the connection created by the connection pool.
#Available values are one of the following:
Code:
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 Connection Pool
Hibernate recommends using it to automatically clean up inappropriate Connections, Statements, ResultSets
Add jar
c3p0-0.9.1.2.jar
Configuration document
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 connection pool
Better performance
Add jar
druid-1.0.26.jar
Configuration document
druid.ini
#mysql database
url=jdbc:mysql://127.0.0.1:3306/bz?useUnicode=true&characterEncoding=UTF-8
username=root
password=123321
#filters=stat
#Maximum number of connections
maxActive=20
#Number of Initialized Connections
initialSize=10
#The timeout waiting time is in milliseconds
maxWait=12000
#Minimum idle connection
minIdle=5
#Check connection objects in connection pools that limit time beyond minEvictableIdleTime Millis
timeBetweenEvictionRunsMillis=6000
#The minimum time value, in milliseconds, that a connection remains idle in the pool without being reclaimed by the idle connection reclaimer thread (if any).
#minEvictableIdleTimeMillis=
#SQL query, used to validate connections taken from connection pools before returning connections to callers
validationQuery=SELECT now();
#Indicates whether the connection is checked by the idle connection reclaimer (if any).
#If the detection fails, the connection will be removed from the pool.
testWhileIdle=true
#Indicates whether the connection is checked before it is removed from the pool, and if the check fails, removes the connection from the pool and attempts to remove another.
testOnBorrow=false
#Indicate whether to inspect before returning to the pool
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;
}
}
Item - Record Addition and Deletion Check (Servlet & JSTL & EL & Filter & Listener & Connection Pool)
github address:
https://github.com/stubbornA/reviewServletPro