TariffDAO tariffDAO = new TariffDAO();
...............
tariffDAO.getTariffList(out);
............
List tariffList = MainDAO.getEntitiesList(new Tariff(), query);
Tariff tariff = new Tariff();
for (Object object : tariffList) {
tariff = (Tariff) object;
out.write(tariff.toString());
}
TariffDAO tariffDAO = new TariffDAO();
List<Tariff> tariffList = tariffDAO.getTariffList();
for (Tariff t : tariffList) {
out.write(t);
}
req.setAttribute("tariffList", tariffList);
<c:forEach items="${tariffList}" var="tariff">
<p>${tariff.name}</p>
<p>${tariff.value}</p>
...
</c:forEach>
package ua.home.web.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class RequestListener implements ServletRequestListener {
private static final ThreadLocal<String> sessionIds = new ThreadLocal<>();
public static String getCurrentSessionId() {
return sessionIds.get();
}
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest();
String id = request.getSession().getId();
sessionIds.set(id);
}
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) { }
}
<listener>
<listener-class>ua.home.web.listener.RequestListener</listener-class>
</listener>
ServletRequestListener.getCurrentSessionId()
мы сможем получать id сессии вне сервлета.package ua.home.web.log;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
import ua.home.web.listener.RequestListener;
public class CustomPatternLayout extends PatternLayout {
@Override
public String format(LoggingEvent event) {
return super.format(event).replace("%sid", RequestListener.getCurrentSessionId());
}
}
log4j.rootCategory=INFO,S
log4j.appender.S=org.apache.log4j.ConsoleAppender
log4j.appender.S.layout=ua.home.web.log.CustomPatternLayout
log4j.appender.S.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %sid %m%n
LOG.info("log message")
, то в лог у нас запишется строка:2016-08-23 12:20:18 TestServlet [INFO] 441135221F8A492364C836560BDEE15E log message
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.sql.*;
public final class PostgresDriverProxyRegister implements InvocationHandler {
static {
try {
DriverManager.registerDriver((Driver) newProxy(new org.postgresql.Driver()));
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Object newProxy(Object target) {
Class<?> clazz = defineInterface(target);
return clazz == null ? target
: Proxy.newProxyInstance(Driver.class.getClassLoader(), new Class[]{clazz}, new PostgresDriverProxyRegister(target));
}
public static Class<?> defineInterface(Object o) {
if (o == null)
return null;
if (o instanceof Driver)
return Driver.class;
if (o instanceof Connection)
return Connection.class;
if (o instanceof Statement)
return Statement.class;
if (o instanceof PreparedStatement)
return PreparedStatement.class;
if (o instanceof ResultSet)
return ResultSet.class;
return null;
}
private final Object target;
private PostgresDriverProxyRegister(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
// в этом блоки можно делать нужные изменения для возвращаемых значений методамы ResultSet
if (proxy instanceof ResultSet) {
Object invokeResult = method.invoke(target, args);
if (invokeResult != null) {
if ("getBigDecimal".equals(methodName)) {
// округляем до 2-х знаков после запятой
BigDecimal bigDecimal = (BigDecimal) invokeResult;
invokeResult = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
} else if ("getString".equals(methodName)) {
// убираем пробелы в начале и конце строки, делаем строку в верхнем регистре
String s = (String) invokeResult;
invokeResult = s.trim().toUpperCase();
}
}
return invokeResult;
}
if (proxy instanceof Driver) {
if ("acceptsURL".equals(methodName) || "connect".equals(methodName)) {
// меняем префикс на оригинал
String url = (String) args[0];
if (url.startsWith("jdbc:postgresql-proxy:")) {
args[0] = url.replace("jdbc:postgresql-proxy:", "jdbc:postgresql:");
}
}
}
return invokeAndProxy(method, args);
}
public Object invokeAndProxy(Method method, Object[] args) throws Throwable {
Object returnValue = method.invoke(target, args);
return newProxy(returnValue);
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Class.forName("ua.home.jdbc.driver.warp.postgres.PostgresDriverProxyRegister");
try(Connection connection = DriverManager
// используем отличный от оригинала прификс к url 'jdbc:postgresql-proxy:', что бы именно наш драйвер грузился
.getConnection("jdbc:postgresql-proxy://localhost:5432/test_db", "test_user", "test_password");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT 12.65456161 as testDecimal, ' tEsTsTrinG ' as testString")) {
if (rs.next()) {
System.out.printf("testDecimal = '%s'\n", rs.getBigDecimal("testDecimal"));
System.out.printf("testString = '%s'\n", rs.getString("testString"));
}
/* output in console
testDecimal = '12.65'
testString = 'TESTSTRING'
*/
}
}
}
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
<packaging>war</packaging>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<?xml version="1.0"?>
<persistence version="1.0">
<persistence-unit name="openjpa">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>tutorial.Animal</class>
<class>tutorial.Dog</class>
<class>tutorial.Rabbit</class>
<class>tutorial.Snake</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:hsqldb:tutorial_database"/>
<property name="openjpa.ConnectionDriverName" value="org.hsqldb.jdbcDriver"/>
<property name="openjpa.ConnectionUserName" value="sa"/>
<property name="openjpa.ConnectionPassword" value=""/>
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO"/>
</properties>
</persistence-unit>
</persistence>
String url = "https://www.google.com.ua/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjM6qWHxsrOAhXLNxQKHY9pBW8QFggaMAA&url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F2572566%2Fjava-jpa-version-annotation&usg=AFQjCNHo2lEs_AU2l38GU9-kO2hGaR5F9g&sig2=1TYjOkH85bUsfa7ddPgSsQ&bvm=bv.129759880,d.bGg";
int beginIndex = url.indexOf("&url=") + 5;
int endIndex = url.indexOf('&', beginIndex);
String substring = url.substring(beginIndex, endIndex);
System.out.println(substring);
// http%3A%2F%2Fstackoverflow.com%2Fquestions%2F2572566%2Fjava-jpa-version-annotation
System.out.println(URLDecoder.decode(substring, "utf8"));
// http://stackoverflow.com/questions/2572566/java-jpa-version-annotation
TreeSet<Double> doubles = new TreeSet<>(Arrays.asList(1.34, 2.34, 3.34, 1.74, 0.34));
System.out.println(doubles.last());
double max = NumberUtils.max(1.34, 2.34, 3.34, 1.74, 0.34);
System.out.println(max);
<c:set var="json_text">
[{"TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_ALL", "VALUE": 635 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "QUALITY", "VALUE": 99.84 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_ALL", "VALUE": 642 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "QUALITY", "VALUE": 99.84 }]
</c:set>
<script>
var jsonObj = ${json_text};
</script>
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
static { // статический блок
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
// остальной код опущен
}
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/sonoo","root","root");