Application of dynamic Agent in web and JDBC Development (JDBC Chapter)

Source: Internet
Author: User
Tags static class throwable

Background description

If you've seen the application of dynamic Proxy in web and JDBC Development (Web page), this article can be used as an advanced example of another application, and there's really not much improvement in the implementation. Let's take a look at the problems facing the project and the desired solution. In the project contacted by the author, the direct use of the original JDBC technology, java.sql.PreparedStatement and Java.sql.ResultSet almost occupied the data access layer, there is no slightest or mapping signs, it seems not very sad to urge? Oh, life. In the project development to half of the time, suddenly found to support the Japanese characters, and in the past has been used in English test. Well, here's the question, how does a database encoded as 8859_1 receive UTF-8 in Java? And a lot of CRUD functionality has been completed, each implementation of the number of fields involved is quite large, is not for each field adjustment?

Problem analysis

For the scenario described above, let's start with a simple analysis. Currently facing problems can be categorized into two types, the first type is garbled, this can be resolved by recoding, the second class is faced with a large number of code implementation, if all the content is adjusted, many functions will have to re-test, high cost, but it is feasible.

In view of the problem of garbled characters, from the angle of implementation, we can encode and convert the input data and output data separately. When using PreparedStatement, encode conversions for all calls to SetString, and for data reads, the resulting string returned by resultset.getstring can be encoded. The following is an example of UTF-8 to 8859_1, which enables the conversion of the code (reverse conversion simply exchanges the location of the encoded name):

New String (New string ("abc"). GetByte ("UTF-8"), "8859_1")
If each call of preparedstatement.setstring and resultset.getstring is encoded and converted in this way, the workload is not only onerous, but also not conducive to the maintenance and porting of code. From the API, in fact, we can setstring and getstring for "HOOK", the use of proxy mode is more suitable, dynamic agent is most appropriate.

Solution Solutions

Coding problem solved, the use of dynamic Agent Unified setstring and GetString interface to self-control, so that all the calls in our controls and how worry can not unified Jiangshan!

public static ResultSet Createresultsetjpwrapper (ResultSet rs) {return (ResultSet) (Proxy.newproxyinstance ( ResultSet.class.getClassLoader (), new class[] {resultset.class}, new Resultsetjpwrapper (RS));}    private static class Resultsetjpwrapper implements Invocationhandler {private ResultSet wrappedresultset;    Public Resultsetjpwrapper (ResultSet rs) {wrappedresultset = rs;  public object invoke (object proxy, Method method, object[] args) throws Throwable {Object result =        Method.invoke (Wrappedresultset, args); if ("GetString". Equals (Method.getname ()) && null! = result) {result = Commonutils.convertcharset ((String) R        Esult, Isaconstants.charset_8859_1, isaconstants.charset_utf_8);    } return result; }}public static PreparedStatement Createpreparedstatementjpwrapper (PreparedStatement pstmt) {return ( PreparedStatement) (Proxy.newproxyinstance (PreparedStatement.class.getClassLoader (), New ClaSs[] {Preparedstatement.class}, new Preparedstatementjpwrapper (PSTMT));} private static class Preparedstatementjpwrapper implements Invocationhandler {private PreparedStatement    Wrappedstatement;    Public Preparedstatementjpwrapper (PreparedStatement pstmt) {wrappedstatement = pstmt; public object invoke (object proxy, Method method, object[] args) throws Throwable {if ("setString" . Equals (Method.getname ()) && args.length = = 2 && null! = Args[1] && String.class.equals (args[1]. GetClass ())) {Args[1] = Commonutils.convertcharset ((String) args[1], Isaconstants.charset_utf_8, Isaconstants.chars        Et_8859_1);    } return Method.invoke (Wrappedstatement, args); }}
The next step is to refactor in places where you need to use PreparedStatement and resultset.
Refactoring before PreparedStatement stmt = conn.preparestatement (sql);//refactoring PreparedStatement stmt = Dbutils.createpreparedstatementjpwrapper (conn.preparestatement (SQL));//refactoring before resultset rs = Stmt.executequery ();// After reconstruction resultset rs = Dbutils.createresultsetjpwrapper (Stmt.executequery ());

After refactoring, both stmt and rs,setstring and GetString are hijacked by our defined dynamic proxies, re-encoded before or after data entry, all of which are transparent to developers and do not pollute existing logic.

Postscript

What we're talking about here is a dynamic proxy application case, and it doesn't mean that you have to use dynamic proxy as the only solution to the problem in this case. In fact, dynamic agents here is not necessarily the best implementation, if possible, it is best to re-set the database to modify the default encoding, or in the application layer of uniform coding, but these often do not apply to a more than 10 years, dozens of people, and different styles and "rotten" smelly project. In fact, the actual database varchar type stored in a variety of string encoding, Euc-jp/shiftjis/utf-8/8859_1, and these codes may exist in a table, to the life!

Application of dynamic Agent in web and JDBC Development (JDBC Chapter)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.