2011年9月23日星期五

How-to-bind-String-to-java.sql.Timestamp

http://forum.springsource.org/showthread.php?48979-How-to-bind-String-to-java.sql.Timestamp

 

java.sql.TimeStamp is derived from java.util.Date. It shouldn't be hard to figure out how to handle that in the persistence layer- in fact I'm willing to bet that some persistence tools can handle that conversion automatically.

In regard to your command object, however, you have a tougher problem using TimeStamp. I'll explain why.

As I noted, TimeStamp is derived from java.util.Date. Spring has an out-of-the-box CustomDateEditor property editor that does conversions from Strings (like on a form filled out by a user) to java.util.Date. It also converts from java.util.Date back to String when a BindingResult is being used to re-populate form fields because the submission failed validation.

Now, for the CustomDateEditor to take the Date it has converted your String to and "jam" it into a TimeStamp field is not possible because it requires an explicit downcast. Spring does no such thing on your behalf. In fact- off the top of my head, I don't think such a downcast is even legal in Java- meaning you'd get an exception.

Do you see why I'm recommending going back to java.util.Date? It's the standard class used for transporting date (and time) information.

If you're really gung-ho about sticking with java.sql.TimeStamp, however, your next best bet is to create your own CustomTimeStampEditor. Basically crack open and copy the code for Spring's CustomeDateEditor and then modify it to suit TimeStamp.

2011年9月20日星期二

jquery定义除输入框之外的背景色

$j("table.infoTable tr td").each(function(){var child = $j(this).children().eq(0);if(!child.is("input") && !child.is("select") && !child.is("textarea")&& !child.is("span")) $j(this).css('backgroundColor', '#e6eff3'); });

2011年9月5日星期一

Spring事务管理与异常处理注意事项

任何RuntimeException 将触发事务回滚,但是任何checked Exception 将不触发事务回滚

在dao 、servcie层都不要try catch,即使try catch 也要在catch中throw ServiceException供controler捕获

 

在controler中处理异常,所有catch都要ServiceException(自定义异常类 继承于RuntimeException)

参考:http://www.iteye.com/topic/34867

     http://www.4ucode.com/Study/Topic/649831

@InitBinder 日期转换

@Controller
public class AbstractController {
    private  String message;
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Integer.class, null,
                                    new CustomNumberEditor(Integer.class, null, true));
        binder.registerCustomEditor(Long.class, null,
                                    new CustomNumberEditor(Long.class, null, true));
        binder.registerCustomEditor(byte[].class,
                                    new ByteArrayMultipartFileEditor());
        binder.registerCustomEditor(Date.class,new PropertyEditorSupport() {
        public void setAsText(String value) {
            try {
                setValue(new SimpleDateFormat(Constants.DATE_FORMAT).parse(value));
            } catch(ParseException e) {
                setValue(null);
            }
        }

        public String getAsText() {
            return new SimpleDateFormat(Constants.DATE_FORMAT).format((Date) getValue());
        }

    });
    }


}

自定义异常处理类

packagecom.capinfo.webapp.handler;

 

importorg.apache.commons.logging.Log;

importorg.apache.commons.logging.LogFactory;

importorg.springframework.web.servlet.HandlerExceptionResolver;

importorg.springframework.web.servlet.ModelAndView;

 

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjava.util.HashMap;

importjava.util.Map;

 

/**

 * Created by IntelliJ IDEA.

 * User: liuzhaochun

 * Date: 11-8-12

 * Time: 下午5:18

 * 自定义异常处理类.

 */

public classMyHandlerExceptionResolver implements HandlerExceptionResolver {

    private Log log =LogFactory.getLog(getClass());

 

    public ModelAndViewresolveException(HttpServletRequest request,

                                        HttpServletResponse httpServletResponse,

                                         Object o, Exception ex) {

        log.warn("Handle exception: "+ ex.getClass().getName());

 

        Map model = newHashMap();

        model.put("ex",ex.getClass().getSimpleName());

        model.put("error",ex.getMessage());

        return newModelAndView("error", model);

    }

}


Jsp:error.jsp

<%@page language="java" pageEncoding="UTF-8"contentType="text/html;charset=UTF-8" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

    <%@ includefile="/include/meta.jsp"%> 

</head>

 

<bodyid="error">

    <div id="page">

        <div id="content"class="clearfix">

            <div id="main">

                <h1>哦!</h1>

                ${ex}</br>

                ${error}

            </div>

        </div>

    </div>

</body>

</html>

url-pattern问题

spring用到forward("/WEB-INF/jsp/*.jsp")
而forward当然是又要经过web.xml的映射的,
然后,在URL匹配时,
 <url-pattern> / </url-pattern>   不会匹配到*.jsp,不会进入spring的DispatcherServlet类
 <url-pattern> /* </url-pattern> 会匹配*.jsp,导致进入spring的DispatcherServlet 类,然后去寻找controller,接着找不到对应的controller所以报错。

总之,关于web.xml的url映射的小知识:
<url-pattern>/</url-pattern>  会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url
<url-pattern>/*</url-pattern> 会匹配所有url:路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)

SpringMVC 配置2

2、    dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
       default-lazy-init="true">

    <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/include/**" location="/include/"/>
    <mvc:default-servlet-handler/>
    <!-- 自定义异常处理类-->
    <bean id="exceptionResolver" class="com.capinfo.webapp.handler.MyHandlerExceptionResolver">  </bean>

    <!-- 自动搜索@Component , @Controller , @Service , @Repository等标注的类 -->        
    <context:component-scan base-package="com.capinfo.webapp.controller"/>

    <!-- Configures the @Controller programming model -->
    <!-- 支持spring mvc新的注解类型 详细spring3.0手册 15.12.1 mvc:annotation-driven-->
    <mvc:annotation-driven/>

    <!-- Convenient way to map URLs to JSPs w/o having a Controller
        当请求/admin/activeUsers时将转发到视图/WEB-INF/pages/admin/activeUsers.jsp中
    -->
    <mvc:view-controller path="/mainMenu" view-name="mainMenu"/>
    <mvc:view-controller path="/error" view-name="error"/>
    <!-- View Resolver for JSPs -->
    <!--  对模型视图名称的解析,即在模型视图名称添加前后缀,在requestmapping输入的地址后自动调用该类进行视图解析-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/jd/*" />
            <mvc:mapping path="/sq/*" />
            <mvc:mapping path="/tcs/*" />
            <mvc:mapping path="/unit/*" />
            <mvc:mapping path="/mainMenu*" />
            <bean class="com.capinfo.webapp.inteceptor.CheckAuthorityInteceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

3、    applicationContext-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
    <!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
    </bean>

    <!-- JNDI DataSource for J2EE environments -->
    <!--<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/appfuse"/>-->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="100"/>
        <property name="maxWait" value="1000"/>
        <property name="poolPreparedStatements" value="true"/>
        <property name="defaultAutoCommit" value="true"/>
    </bean>
</beans>
4、    applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
    <!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->


    
    <!-- Enable @Transactional support -->
    <tx:annotation-driven/>

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>
    
    <!-- 自动搜索@Component , @Controller , @Service , @Repository等标注的类 -->
    <context:component-scan base-package="com.capinfo.service"/>

    <!-- 定义事务规则
    如果 PlatformTransactionManager bean的名字是 'transactionManager' 的话,
    你的事务通知(<tx:advice/>)中的 'transaction-manager' 属性可以忽略。
    否则你则需要明确指定transaction-manager="transactionManager"
    -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <!-- Read-only commented out to make things easier for end-users -->
            <!-- http://issues.appfuse.org/browse/APF-556 -->
            <!--tx:method name="get*" read-only="true"/-->
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    
    <!-- =================================================================== -->
    <!-- AOP: Configuration and Aspects    定义切面 并与 事务规则绑定           -->
    <!-- =================================================================== -->
    <aop:config>
        <!-- 定义一个匹配service包下*Manager类下所有方法的切面 都执行txAdvice事务逻辑规则 -->
        <aop:advisor id="managerTx" advice-ref="txAdvice" pointcut="execution(* *..service.*Manager.*(..))" order="2"/>
    </aop:config>
    

</beans>
5、    applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">
    <!-- 注意上面的default-autowire="byName",如果没有这个声明那么HibernateDaoSupport中的sessionFactory不会被注入 -->

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
       <property name="mappingDirectoryLocations">
         <list><!-- 这里直接映射的pojo类所在的包,简单方便不用没次加一个pojo类都需要到这里来添加 -->
            <value>classpath:com/capinfo/pojo</value>
         </list>
       </property>
       <property name="hibernateProperties">
            <value>
                hibernate.dialect=${hibernate.dialect}
                hibernate.query.substitutions=true 'Y', false 'N'
                hibernate.cache.use_second_level_cache=true
                hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
                hibernate.hbm2ddl.auto=${hibernate.hbm2ddl.auto}
            </value>
       </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>

    <!-- 自动搜索@Component , @Controller , @Service , @Repository等标注的类 -->        
    <context:component-scan base-package="com.capinfo.dao"/>


</beans>

SpringMVC 配置1

SpringMVC 配置

 

1、 web.xml

<?xmlversion="1.0" encoding="UTF-8"?>

<web-appxmlns="http://java.sun.com/xml/ns/javaee"

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

           version="2.5">

 

    <!-- Context Configuration locations forSpring XML files -->

    <context-param>

       <param-name>contextConfigLocation</param-name>

        <param-value>

            classpath:/applicationContext-resources.xml

           classpath:/applicationContext-dao.xml

           classpath:/applicationContext-service.xml

        </param-value>

    </context-param>

    <!--如果不定义webAppRootKey参数,那么webAppRootKey就是缺省的"webapp.root"。但最好设置,

    以免项目之间的名称冲突。

    定义以后,在Web Container启动时将把ROOT的绝对路径写到系统变量里。

    然后log4j的配置文件里就可以用${webName.root }来表示Web目录的绝对路径,把log文件存放于webapp中。

    此参数用于后面的“Log4jConfigListener”-->

    <context-param>

    <param-name>webAppRootKey</param-name>

   <param-value>webapp.root</param-value>

    </context-param>

 

    <!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond-->

    <context-param>

   <param-name>log4jRefreshInterval</param-name>

    <param-value>60000</param-value>

    </context-param>

 

    <!--由Sprng载入的Log4j配置文件位置-->

    <context-param>

       <param-name>log4jConfigLocation</param-name>

       <param-value>/WEB-INF/log4j.properties</param-value>

    </context-param>

 

    <filter>

        <filter-name>encodingFilter</filter-name>

       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <init-param>

           <param-name>encoding</param-name>

           <param-value>UTF-8</param-value>

        </init-param>

        <init-param>

           <param-name>forceEncoding</param-name>

           <param-value>true</param-value>

        </init-param>

    </filter>

 

    <filter-mapping>

       <filter-name>encodingFilter</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

    <!--Spring log4j Config loader

       需要放在ContextLoaderListener之前

       否则会提示log4j:WARN No appenders couldbe found for logger (org.springframework.web.context.ContextLoader)

    -->

    <listener>

        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

    </listener>

    <listener>

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

    </listener>

    <listener>

       <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>

    </listener>

 

    <servlet>

       <servlet-name>dispatcher</servlet-name>

       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

       <servlet-name>dispatcher</servlet-name>

       <url-pattern>/</url-pattern>

    </servlet-mapping>

 

    <session-config>

       <session-timeout>10</session-timeout>

    </session-config>

 

    <welcome-file-list>

       <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

 

    <error-page>

       <error-code>500</error-code>

       <location>/error.jsp</location>

    </error-page>

    <error-page>

        <error-code>400</error-code>

       <location>/index.jsp</location>

    </error-page>

    <error-page>

       <error-code>403</error-code>

       <location>/403.jsp</location>

    </error-page>

    <error-page>

       <error-code>404</error-code>

        <location>/404.jsp</location>

    </error-page>

</web-app>