乐者为王

Do one thing, and do it well.

如何显示Hibernate的SQL参数值-P6Spy

英文原文:http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-solution/

问题

有许多开发者问及Hibernate的SQL参数值问题。如何显示Hibernate传递给数据库的SQL参数值?Hibernate只会把所有的参数值显示为问号(?)。使用show_sql属性,Hibernate会显示所有生成的SQL语句,但不显示SQL参数值。

例如:

1
2
Hibernate: insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME)
values (?, ?, ?, ?, ?, ?)

有没有办法记录或显示确切的Hibernate的SQL参数值呢?

解决方案-P6Spy

好吧,如果有问题那么肯定就会有答案~

P6Spy是一个可以在SQL语句和参数值被发送到数据库之前把它们都记录下来的实用库。P6Spy是免费的,它拦截并记录所有数据库SQL语句到一个日志文件中,它适用于任何使用JDBC驱动的应用程序。

1. 下载P6Spy库

获取p6spy-install.jar,你可以从以下地址下载:

  1. P6Spy官方网站
  2. P6Spy在Sourceforge.net

2. 解压

解压p6spy-install.jar文件,查找p6spy.jar和spy.properties。

3. 添加库依赖

把p6spy.jar添加到项目库依赖中。

4. 修改P6Spy属性文件

修改数据库配置文件。你需要把现有的JDBC驱动替换为P6Spy的JDBC驱动——com.p6spy.engine.spy.P6SpyDriver。

原来的是MySQL的JDBC驱动——com.mysql.jdbc.Driver:

1
2
3
4
5
6
7
8
9
<session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
</session-factory>

把它改成P6Spy的JDBC驱动——com.p6spy.engine.spy.P6SpyDriver:

1
2
3
4
5
6
7
8
9
<session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.driver_class">com.p6spy.engine.spy.P6SpyDriver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
</session-factory>

5. 修改P6Spy属性文件

修改P6Spy属性文件——spy.properties。

用现有的MySQL的JDBC驱动替换“real driver”:

1
2
3
4
5
6
realdriver=com.mysql.jdbc.Driver

#specifies another driver to use
realdriver2=
#specifies a third driver to use
realdriver3=

修改logfile属性中的日志文件位置,所有的SQL语句将会被记录到这个文件里。

Windows

1
logfile     = c:/spy.log

*nix

1
logfile     = /srv/log/spy.log

6. 把spy.properties复制到项目的classpath

把spy.properties复制到项目根目录,确保项目可以定位到spy.properties,否则它会提示spy.properties文件没有找到。

7. 完成

运行应用程序并做一些数据库事务,你会注意到所有从应用程序发送到数据库的SQL语句将被记录到你在spy.properties中指定的一个文件中。

示例日志文件如下:

1
2
3
4
insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME)
values (?, ?, ?, ?, ?, ?)|
insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME)
values (10.0, 1.1, '2009-12-30', 1.2, 11, 1000000)

总结

坦率地说,P6Spy在减少开发者的调试时间方面非常有用。只要你的项目是使用JDBC驱动来连接,P6Spy就能够为你记录所有的SQL语句和参数值。

对于Maven用户

你可以在pom.xml中添加以下内容来下载P6Spy依赖:

1
2
3
4
5
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>1.3</version>
</dependency>

不过下载下来的包中并没有spy.properties文件,你必须自己创建它。或者你可以下载这里的——spy.properties模板。

参考资料

  1. P6Spy configuration

实现用户注册功能

已经两个星期没有更新代码了,这次来给加上用户注册的功能。

先在User.java中添加confirmPassword字段。然后在UserDao.java中添加保存用户的代码:

1
2
3
4
5
6
7
8
9
10
11
public void addUser(User user) {
    Session session = sessionFactory.openSession();
    Transaction ts = null;
    try {
        ts = session.beginTransaction();
        session.save(user);
        ts.commit();
    } finally {
        session.close();
    }
}

在UserService.java中添加以下代码:

1
2
3
4
5
6
7
public void addUser(User user) throws UserAlreadyExistsException {
    User u = getUser(user.getUsername());
    if (u != null) {
        throw new UserAlreadyExistsException();
    }
    userDao.addUser(user);
}

其中UserAlreadyExistsException.java代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.codemany.account.service;

public class UserAlreadyExistsException extends Exception {
    private static final long serialVersionUID = -7518737598462419360L;

    public UserAlreadyExistsException() {
        super();
    }

    public UserAlreadyExistsException(String message) {
        super(message);
    }

    public UserAlreadyExistsException(String message, Throwable cause) {
        super(message, cause);
    }

    public UserAlreadyExistsException(Throwable cause) {
        super(cause);
    }
}

在applicationContext.xml中加上一个bean:

1
2
3
<bean id="registerAction" class="com.codemany.account.action.RegisterAction" scope="prototype">
    <property name="userService" ref="userService" />
</bean>

然后在account.xml中添加register动作,并修改login动作相应的页面:

1
2
3
4
5
6
7
8
9
<action name="login" class="loginAction">
    <result name="success">/index.jsp</result>
    <result name="input">/login.jsp</result>
</action>

<action name="register" class="registerAction">
    <result name="success">/index.jsp</result>
    <result name="input">/register.jsp</result>
</action>

建立RegisterAction.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.codemany.account.action;

import com.codemany.account.model.User;
import com.codemany.account.service.UserAlreadyExistsException;
import com.codemany.account.service.UserService;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
    private static final long serialVersionUID = 7021982816578678150L;

    private User user;

    private UserService userService;

    public String execute() throws Exception {
        try {
            userService.addUser(user);
        } catch (UserAlreadyExistsException e) {
            return INPUT;
        }
        return SUCCESS;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}

新建校验配置文件。先是对应RegisterAction类的RegisterAction-validation.xml配置:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
    <field name="user">
        <field-validator type="visitor">
            <param name="appendPrefix">true</param>
            <message />
        </field-validator>
    </field>
</validators>

这里的校验使用了visitor类型,它是用于检测action里的复合属性的。这里的复合属性是User对象,所以要在User.java同一个目录下建立校验配置文件User-validation.xml,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>Username is required</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="minLength">2</param>
            <param name="maxLength">20</param>
            <message>Username must be between ${minLength} and ${maxLength} characters</message>
        </field-validator>
    </field>

    <field name="password">
        <field-validator type="requiredstring">
            <message>Password is required</message>
        </field-validator>
        <field-validator type="stringlength">
            <param name="minLength">6</param>
            <param name="maxLength">50</param>
            <message>Password must be between ${minLength} and ${maxLength} characters</message>
        </field-validator>
    </field>

    <field name="confirmPassword">
        <field-validator type="fieldexpression">
            <param name="expression">confirmPassword.equals(password)</param>
            <message>Password does not match the confirm password</message>
        </field-validator>
    </field>
</validators>

修改index.jsp,将登录表单移到单独的login.jsp页面中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JBookShelf</title>
</head>

<body>
    <s:if test="#session.logined">
        Welcome, you have logined. <a href="<%= request.getContextPath() %>/logout.action">Logout</a>
    </s:if>
    <s:else>
        <a href="<%= request.getContextPath() %>/login!input.action">Login</a> |
        <a href="<%= request.getContextPath() %>/register!input.action">Register</a>
    </s:else>
</body>
</html>

这里是登录页面login.jsp,首页index.jsp中的登录表单就是被移到这个文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Login</title>
</head>

<body>
    <p>User: test/test</p>
    <s:form action="login">
        <s:textfield key="username" label="Username" />
        <s:password key="password" label="Password" />
        <s:submit value="Login" />
    </s:form>
</body>
</html>

注册页面register.jsp,负责生成注册时的表单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registration</title>
</head>

<body>
    <s:form action="register">
        <s:textfield key="user.username" label="Username" />
        <s:password key="user.password" label="Password" />
        <s:password key="user.confirmPassword" label="Password Confirmation" />
        <s:submit value="Register" />
    </s:form>
</body>
</html>

代码下载:https://github.com/dohkoos/JBookShelf

使用Struts 2 Validation框架校验登录

Struts 2有三种校验方式:

  1. 使用Annotation进行校验。
  2. 使用XML配置校验。
  3. 使用覆盖validate方法校验。

使用XML配置时validation.xml的命名规则和放置路径:

1
<ActionClassName>-validation.xml

<ActionClassName>就是要验证的Action类的名字,将此文件放在与Action类文件相同的目录下即可。如果该Action类在struts.xml配置中有多个action实例,那么对应某个action实例的校验文件命名规则如下:

1
<ActionClassName>-<aliasName>-validation.xml

例如:UserAction-login-validation.xml。注意,这里的<aliasName>并不是方法名,而是struts.xml中配置的action实例的名字。

既然用框架来校验了,那么在LoginAction.java中判断用户名和密码是否为空的代码就可以删除了。还要记得加上username和passowrd的getter方法,不然校验器(validator)会因为取不到field而报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String execute() throws Exception {
    User u = userService.getUser(username);
    if (u == null || !password.equals(u.getPassword())) {
        return INPUT;
    }

    ActionContext.getContext().getSession().put("logined", true);
    return SUCCESS;
}

public String getUsername() {
    return username;
}

public String getPassword() {
    return password;
}

同时在LoginAction.java相同目录下创建LoginAction-validation.xml,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
    <field name="username">
        <field-validator type="requiredstring">
            <message>Username is required</message>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring">
            <message>Password is required</message>
        </field-validator>
    </field>
</validators>

message提供了校验出错的信息,在其中可以使用${}来引用被校验的对象。如果未出现异常,则转入用户请求的处理方法;出现异常则转入input所指定的视图。所以,对于校验的action实例,必须要在配置文件中为其指定input视图。

代码下载:https://github.com/dohkoos/JBookShelf

Struts 2 + Spring 3 + Hibernate 4登录实例

在pom.xml中添加Spring的依赖包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<!-- 注意:没有这个plugin包会导致Spring无法注入bean到Struts 2的Action中 -->
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-spring-plugin</artifactId>
    <version>2.3.4.1</version>
</dependency>

配置web.xml文件,加上Spring的监听器:

1
2
3
4
5
6
7
8
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

删除hibernate.cfg.xml,添加applicationContext.xml,内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- DriverManagerDataSource在每个连接请求时都新建一个connection。
         与DBCP的BasicDataSource不同,DriverManagerDataSource提供的连接没有进行池管理 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/jbookshelf" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.pool_size">1</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
                <prop key="show_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/codemany/account/model/User.hbm.xml</value>
            </list>
        </property>
    </bean>

    <bean id="userDao" class="com.codemany.account.dao.UserDao">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Struts 2的action是有状态的,必须显式设置scope为prototype,这样每次请求过来都会创建新的action -->
    <bean id="loginAction" class="com.codemany.account.action.LoginAction" scope="prototype">
        <property name="userDao" ref="userDao" />
    </bean>
</beans>

删除HibernateUtil.java,修改UserDao.java为以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.codemany.account.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.codemany.account.model.User;

public class UserDao {
    // Spring 3集成Hibernate 4不再需要HibernateDaoSupport或HibernateTemplate了,
    // 直接使用原生API即可。
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public User getUser(String username) {
        Session session = sessionFactory.openSession();
        try {
            Query query = session.createQuery("from User u where u.username = ?");
            query.setString(0, username);
            query.setMaxResults(1);
            return (User)query.uniqueResult();
        } finally {
            session.close();
        }
    }
}

在struts.xml中将action元素中login的class属性改为applicationContext.xml配置文件中的loginAction:

1
2
3
4
<action name="login" class="loginAction">
    <result name="success">/index.jsp</result>
    <result name="input">/index.jsp</result>
</action>

修改LoginAction.java的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.codemany.account.action;

import com.codemany.account.dao.UserDao;
import com.codemany.account.model.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private static final long serialVersionUID = -389833745243649130L;

    private String username;
    private String password;

    private UserDao userDao;

    public String execute() throws Exception {
        if (username == null || username.length() == 0
                || password == null || password.length() == 0) {
            return INPUT;
        }

        User u = userDao.getUser(username);
        if (u == null || !password.equals(u.getPassword())) {
            return INPUT;
        }

        ActionContext.getContext().getSession().put("logined", true);
        return SUCCESS;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}

代码下载:https://github.com/dohkoos/JBookShelf

Struts 2 + Hibernate 4登录实例

使用以下代码创建数据库:

1
2
3
4
5
6
7
8
9
10
11
12
CREATE DATABASE IF NOT EXISTS jbookshelf;

USE jbookshelf;

DROP TABLE IF EXISTS users;

CREATE TABLE users (
    id int NOT NULL AUTO_INCREMENT,
    username varchar(20) NOT NULL,
    password varchar(50) NOT NULL,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;

在pom.xml中添加Hibernate的依赖配置:

1
2
3
4
5
6
7
8
9
10
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.6.Final</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>

创建User.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.codemany.account.model;

public class User {
    private Long id;

    private String username;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在同一目录下创建User.hbm.xml文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.codemany.account.model">
    <class name="User" table="users">
        <id name="id">
            <generator class="increment" />
        </id>

        <property name="username" length="20" />
        <property name="password" length="50" />
    </class>
</hibernate-mapping>

在resources目录下创建hibernate.cfg.xml配置文件,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- MySQL connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/jbookshelf</property>
        <property name="connection.username">yourname</property>
        <property name="connection.password">yourpassword</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <mapping resource="com/codemany/account/model/User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

建立管理Session的HibernateUtil.java类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.codemany.account.dao.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure();
            Properties props = configuration.getProperties();

            ServiceRegistry serviceRegistry =
                    new ServiceRegistryBuilder().applySettings(props).buildServiceRegistry();

            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

在dao包创建数据访问对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.codemany.account.dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.codemany.account.model.User;

public class UserDao {
    public static User getUser(String username) {
        Session session = HibernateUtil.getSession();
        try {
            Query query = session.createQuery("from User u where u.username = ?");
            query.setMaxResults(1);
            query.setString(0, username);
            return (User)query.uniqueResult();
        } finally {
            session.close();
        }
    }
}

现在可以访问数据库了,所以要修改LoginAction.java的execute方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public String execute() throws Exception {
    if (username == null || username.length() == 0
            || password == null || password.length() == 0) {
        return INPUT;
    }

    User u = UserDao.getUser(username);
    if (u == null) {
        return INPUT;
    }
    if (username.equals(u.getUsername()) && password.equals(u.getPassword())) {
        ActionContext.getContext().getSession().put("logined", true);
        return SUCCESS;
    }

    return INPUT;
}

如果显示jta-1.0.1b.jar缺失的错误,可以在pom.xml中添加以下语句:

1
2
3
4
5
6
<repositories>
    <repository>
        <id>java.net</id>
        <url>http://download.java.net/maven/2/</url>
    </repository>
</repositories>

代码下载:https://github.com/dohkoos/JBookShelf

Struts 2登录实例

新的Eclipse已经包含Maven插件了,不过还需要到Eclipse Marketplace中去安装一个m2-wtp(Maven Integeration for Eclipse WTP)插件,不然启动Tomcat时会报错。

安装好后创建新Maven项目,填写groupId和artifactId。

在pom.xml中加入Struts 2的依赖配置:

1
2
3
4
5
6
7
<dependencies>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.3.4</version>
    </dependency>
</dependencies>

在web.xml文件中添加Struts 2的Filter:

1
2
3
4
5
6
7
8
9
10
11
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

配置resources/struts.xml文件:

1
2
3
4
5
6
7
8
9
10
11
12
<struts>
    <package name="default" extends="struts-default">
        <action name="login" class="com.codemany.account.action.LoginAction">
            <result name="success">/index.jsp</result>
            <result name="input">/index.jsp</result>
        </action>

        <action name="logout" class="com.codemany.account.action.LogoutAction">
            <result name="success" type="redirect">/index.jsp</result>
        </action>
    </package>
</struts>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.codemany.account.action;

import com.codemany.account.model.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
    private static final long serialVersionUID = -389833745243649130L;

    private String username;
    private String password;

    public String execute() throws Exception {
        if (username == null || username.length() != 0
                || password == null || password.length() != 0) {
            return INPUT;
        }

        if ("test".equals(username) && "test".equals(password)) {
            ActionContext.getContext().getSession().put("logined", true);
            return SUCCESS;
        }

        return INPUT;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.codemany.account.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LogoutAction extends ActionSupport {
    private static final long serialVersionUID = -518996422060716751L;

    public String execute() throws Exception {
        ActionContext.getContext().getSession().put("logined", false);
        return SUCCESS;
    }
}

index.jsp内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Struts2 Login Sample</title>
</head>

<body>
    <s:if test="#session.logined">
        Welcome, you have logined. <a href="<%= request.getContextPath() %>/logout.action">Logout</a>
    </s:if>
    <s:else>
        <p>User: test/test</p>
        <s:form action="login">
            <s:textfield key="username" label="Username" />
            <s:password key="password" label="Password" />
            <s:submit value="Login" />
        </s:form>
    </s:else>
</body>
</html>

在项目上点击右键 -> Run As -> Maven build运行项目。在Goals栏中填写tomcat:run,Maven会自动下载Tomcat到项目的target目录下后启动服务器。

代码下载:https://github.com/dohkoos/JBookShelf

使用Ruby批量修改繁体文件名为简体

首先是遍历目录所有文件,使用了 http://beike.iteye.com/blog/361108 的代码,稍微做了下修改。主要是在Windows下处理系统目录时会停止遍历,加上了异常处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def traverse(path)
  begin
    if File.directory?(path)
      Dir.foreach(path) do |file|
        if file != "." and file != ".."
          traverse(path + "/" + file) {|x| yield x}
        end
      end
    else
      yield path
    end
  rescue
    puts "Error: #{$!}"
  end
end

如果不输入文件夹路径,就使用当前目录作为根目录:

1
root = ARGV[0] || Dir.pwd

将繁体中文改成简体的代码:

1
2
3
4
5
6
7
mapping = {}
mapping["無"] = "无"
mapping["龍"] = "龙"

mapping.each do |key, value|
  file.gsub!(key.encode('gbk', 'utf-8'), value.encode('gbk', 'utf-8'))
end

文件重命名:

1
File.rename(old_file_name, new_file_name)

代码下载:https://github.com/dohkoos/big2gb

CSS命名规范

收集了网上的一些CSS命名规范,根据自己的理解和需求整理了一遍。

布局(layout)

  • container 就是将页面中的所有元素包在一起的部分
  • header 页面的头部区域,包含站点的logo和一些其他元素
  • navbar 横向导航栏,最典型的网页元素
  • breadcrumbs 即页面所处位置的导航提示
  • content 是站点的主要区域
  • sidebar
  • footer

头部(header)

  • logo
  • slogan

导航栏(navbar)

  • mainnav
  • subnav
  • topnav

侧边栏(sidebar)

  • menu 包含一般的链接。sidebar中可以包含多个menu

常用

  • userbar 登录注册条
  • copyright
  • banner
  • feature

我写的二分查找算法有bug!

看完 http://reprog.wordpress.com/2010/04/19/are-you-one-of-the-10-percent/ 觉得很不服气,写个二分查找算法还不简单吗?分分钟搞定的事情。

按照它的要求,用Java写出以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int binarySearch(int[] array, int value) {
    int low = 0;
    int high = array.length - 1;
    int mid;
    while (low <= high) {
        mid = (low + high) / 2;
        if (array[mid] < value) {
            low = mid + 1;
        } else if (array[mid] > value) {
            high = mid - 1;
        } else {
            return mid;
        }
    }
    return -1;
}

把代码贴到评论区参加测试。

写代码和检查总共花费20分钟,75%的时间是用来在脑袋里模拟运算,防止数组索引溢出。然后编译2次,消除了两个语法错误(好久没写Java代码和使用Ruby的关系,竟然连个数组初始化都不会写了)。也想过数值溢出的问题,但是没想到点子上。结果恰恰倒在了这个地方。具体原因在 http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html 有描述。因为low + high的和会形成数值溢出,解决方法是采用:

1
int mid = low + ((high - low) / 2);

1
int mid = (low + high) >>> 1;

如何破解中兴ZXA10-F460 v3.0获取超级管理员密码

破解前的系统情况:

  • 硬件版本号 V3.0
  • 软件版本号 F460_IMS_V2.30.10P1T6_JS1111
  • BOOT版本号 V1.1.0P1T1
  • 版本日期 2012-02-29 16:29:07

中兴ZXA10-F460光猫(E8-C)在第一次安装的时候,超级管理员帐号是telecomadmin,密码为nE7jA%5m,这个是默认的,由安装人员设置好相关设置后,会自动下载配置,这时候这个超级管理员密码会被修改为telecomadminXXXXXXXX(8个X是8位数字,每个用户是不同的)这种格式。因为很多设置需要在超级管理员下才能设置,所以破解这个超级管理员密码是非常必要的。

其中V1.0和V2.0版本网上有破解方法,大家可以自己搜索。

在命令行下输入telnet 192.168.1.1,帐号和密码都是root。连接成功后,会出现“F460 login:”这样的提示。

注意:目前网上流传的查看/tmp目录下db_backup_cfg.xml文件内容的破解方法已经无效了。另外在/userconfig/cfg目录下有两个加密的配置文件db_backup_cfg.xml和db_user_cfg.xml,同目录下还有个db_default_cfg.xml是不加密的(该文件是出厂设置的配置文件),但是大家不要用这个文件去替换db_user_cfg.xml,否则会出现不可预知的后果。

实际上只要修改一下/home/httpd/login.gch这个文件,就能看到密码了。patch文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
--- /home/httpd/login.gch 2012-07-03 14:05:16.000000000 +0800
+++ login.gch 2012-07-03 14:03:37.000000000 +0800
@@ -152,6 +152,17 @@
set_language("langcn.conf");
langclass = "login_title_centeren";
}
+var CK_HANDLE = create_paralist();
+var login_name = "telecomadmin";
+set_para(CK_HANDLE, "Username", login_name);
+qeury_list_bycond("OBJ_USERINFO_ID", "IGD", CK_HANDLE);
+destroy_paralist(CK_HANDLE);
+CK_HANDLE = create_paralist();
+var CK_IDENTITY = query_identity(0);
+get_inst(CK_HANDLE, "OBJ_USERINFO_ID", CK_IDENTITY);
+var now_pwd = get_para(CK_HANDLE, "Password");
+now_pwd = delMoreSlash(now_pwd);
+destroy_paralist(CK_HANDLE);
%>
<head>
<META HTTP-EQUIV="pragma" CONTENT="no-cache>
@@ -239,4 +250,5 @@
</script>
</head>
<body onload="onFocus();">
+<div><%=now_pwd;%></div>
<div id="container" class="content">

效果是浏览器登录192.168.1.1的时候,超级管理员密码会显示在首页界面的左上角。

到这儿有人想了,怎么把上面的patch更新到/home/httpd/login.gch中呢?总结了三种方法:

第一种方法是telent到F460上后,执行下面的命令即可:

1
2
3
4
5
6
7
8
9
10
11
12
sed -i '155 s/^/var CK_HANDLE = create_paralist();\n/' /home/httpd/login.gch
sed -i '156 s/^/var login_name = "telecomadmin";\n/' /home/httpd/login.gch
sed -i '157 s/^/set_para(CK_HANDLE, "Username", login_name);\n/' /home/httpd/login.gch
sed -i '158 s/^/qeury_list_bycond("OBJ_USERINFO_ID", "IGD", CK_HANDLE);\n/' /home/httpd/login.gch
sed -i '159 s/^/destroy_paralist(CK_HANDLE);\n/' /home/httpd/login.gch
sed -i '160 s/^/CK_HANDLE = create_paralist();\n/' /home/httpd/login.gch
sed -i '161 s/^/var CK_IDENTITY = query_identity(0);\n/' /home/httpd/login.gch
sed -i '162 s/^/get_inst(CK_HANDLE, "OBJ_USERINFO_ID", CK_IDENTITY);\n/' /home/httpd/login.gch
sed -i '163 s/^/var now_pwd = get_para(CK_HANDLE, "Password");\n/' /home/httpd/login.gch
sed -i '164 s/^/now_pwd = delMoreSlash(now_pwd);\n/' /home/httpd/login.gch
sed -i '165 s/^/destroy_paralist(CK_HANDLE);\n/' /home/httpd/login.gch
sed -i '253 s/^/<div><%=now_pwd;%><\/div>\n/' /home/httpd/login.gch

第二种方法是telent到F460上后,执行cp /home/httpd/login.gch /home/httpd/login_gch.xml,通过浏览器把login_gch.xml保存到电脑上,然后再把patch更新进去。可以在电脑上架设ftp服务器,在F460上执行以下命令:

1
2
cd /home/httpd/
wget ftp://<YOUR_COMPUTER_IP>/login.gch  # 把<YOUR_COMPUTER_IP>替换成你自己的

第三种方法是telent到F460上后,执行df命令,查看是否有usb1_1或usb2_1,如果有就可以进行下一步操作。输入cp /home/httpd/login.gch /mnt/usb1_1/login.gch把文件拷贝到优盘上,修改后使用cp /mnt/usb1_1/login.gch /home/httpd/login.gch把文件更新到猫上就可以。

2013/6/16更新

其实还有种更简便的方法,中兴的光猫有个sendcmd命令,下面是该命令的简单用法:

  1. 读取全部表名 sendcmd 1 DB all;
  2. 读取指定表信息 sendcmd 1 DB p 表名。比如sendcmd 1 DB p UserInfo,查看路由器帐号和密码,超级管理员密码也在这里查看;
  3. 查看当前系统运行的服务状态 sendcmd -pc show;
  4. 修改某个表的某个字段的值 sendcmd 1 DB set 表名 行数 字段名 字段值。比如要修改超级管理员密码,可以使用sendcmd 1 DB set UserInfo 0 Password 123456;
  5. 保存对配置文件的修改 sendcmd 1 DB save。

当然还有其它的命令,但是就修改光猫配置来说,这几条命令足够了。