Spring
Spring File Upload Tutorial
Filed under Spring
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties available; the maximum file size in bytes --> <property name="maxUploadSize" value="100000"/> </bean>
<form method="post" action="upload.form" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>public class FileUploadController extends SimpleFormController { protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws ServletException, IOException { FileUploadBean bean = (FileUploadBean) command; byte[] file = bean.getFile(); if (file == null) { // did not upload anything } ........... } protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws ServletException { binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); } } public class FileUploadBean { private byte[] file; public void setFile(byte[] file) { this.file = file; } public byte[] getFile() { return file; } }
Jars:
lib/commons-fileupload-1.2.1.jar
lib/commons-io-1.4.jar
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
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;