Posts tagged Spring
OpenSessionInViewInterceptor for Spring + Hibernate3
- keeps the hibernate session open long enough for the view to render what is needed before it is closed
- allows access to lazy loaded associations without “LazyInitializationException” exception
applicationContext.xml <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> <property> name="flushModeName"> <value>FLUSH_AUTO</value> </property> </bean>
<property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor" /> </list> </property>
OpenSessionInViewFilter
web.xml <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping>
Log4j configuration in Spring
Filed under Spring
web.xml <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
log4j.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <log4j:configuration> <appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" /> <!-- ConversionPattern format specification %d inserts the date; you can specify the format (%d{yyyy-MM-dd HH:mm:ss,SSS}) %-5p inserts the priority log level, 5 characters, left justified %c{1} inserts the name of the class %L inserts the line number %m inserts the user message %n inserts the separator (for example, a new line) --> <param name="MaxFileSize" value="512KB" /> <param name="MaxBackupIndex" value="10" /> </layout> </appender> <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender"> <param name="Threshold" value="INFO" /> <param name="File" value="${webapp.root}/WEB-INF/logs/helloworld.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" /> </layout> </appender> <logger name="org.springframework"> <level value="error"/> </logger> <logger name="org.hibernate"> <level value="error"/> </logger> <logger name= "net.pack"> <level value="debug"/> </logger> <root> <priority value="info"></priority> <appender-ref ref="stdout"/> <appender-ref ref="fileAppender"/> </root> </log4j:configuration>
public class TestController { private static final Logger logger = Logger.getLogger(TestController.class); public ModelAndView addTest(@ModelAttribute("test") Test test, BindingResult result) { logger.debug("test logging --debug"); } }
ActiveMQ configuration in Spring web application
Filed under Spring
Point to Point (using Queue)
applicationContext.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:jms="http://www.springframework.org/schema/jms" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd"> <context:component-scan base-package="jms" /> <context:annotation-config /> <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL"> <value>tcp://localhost:61616</value> </property> </bean> <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="testQueue"/> </bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="defaultDestination" ref="destination"/> </bean> <jms:listener-container connection-factory="connectionFactory"> <jms:listener destination="testQueue" ref="messageReceiver" method="receive"/> </jms:listener-container> </beans>
MessageReceiver.java @Component public class MessageReceiver { public void receive(Map message) throws Exception { String msg = (String) message.get("message"); } }
MessageSender.java @Controller @RequestMapping("/sendMsg") public class MessageSender { @Autowired private JmsTemplate jmsTemplate; @RequestMapping(method=RequestMethod.GET) public String send() { System.out.println("Sending..."); sendMessage("how u doin!!"); return ""; } public void sendMessage(final String msg) { jmsTemplate.send( new MessageCreator() { public Message createMessage(Session session) throws JMSException { MapMessage mapMessage = session.createMapMessage(); mapMessage.setString("message", msg); return mapMessage; } } ); System.out.println("Message sent> " + msg); } }
Publisher – Subscriber (using Topic)
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
<bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="testTopic"/>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="defaultDestination" ref="destination"/>
</bean>
<bean id="smsNotifListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="smsSubscriber"/>
</bean>
<bean id="emailNotifListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="destination"/>
<property name="messageListener" ref="emailSubscriber"/>
</bean>Required Jars:
1. activemq-all-5.5.0 jar
2. log4j-1.2.16
3. slf4j-api-1.5.8
4. slf4j-log4j12-1.5.8
5. jcl-over-slf4j-1.5.8
Unicode/UTF-8 in Spring web application
Filed under Web Application
web.xml
<filter>
<filter-name>encoding-filter</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>
</filter>
<filter-mapping>
<filter-name>encoding-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>dispatcher-servlet.xml
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- PostgreSQL -->
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/test?useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&characterSetResults=UTF-8"/>
<property name="username" value="postgres"/>
<property name="password" value="pass"/>
<!-- MySQL -->
<!--
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&connectionCollation=utf8_general_ci&characterSetResults=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
-->
</bean>*.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %>
Tomcat's server.xml <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" compression="on" compressionMinSize="128" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript" URIEncoding="UTF-8" />
*.jsp <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> ...
- Create the tables with UTF-8 encoding.
Spring + Hibernate Validation Example
Filed under Spring
dispatcher-servlet.xml <mvc:annotation-driven /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
Controller.java @RequestMapping(value = "/save", method = RequestMethod.POST) public String saveTest(@ModelAttribute("test") @Valid Test test, BindingResult result) { //handle error if (result.hasErrors() || result.hasFieldErrors()) { return "testAdd"; }
Test.java @Entity @Table(name = "test") @Proxy(lazy = false) public class Test implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @NotEmpty private String name; private String sex;