Unicode/UTF-8 in Spring 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&amp;characterEncoding=UTF-8&amp;connectionCollation=utf8_general_ci&amp;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&amp;characterEncoding=UTF-8&amp;connectionCollation=utf8_general_ci&amp;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.

Tutorial

Comments (0)

Tomcat filter to log response HTML

web.xml
  <filter>
        <filter-name>testFilter</filter-name>
        <filter-class>filters.ResponseLoggingFilter
        </filter-class>
    </filter>
 
    <filter-mapping>
        <filter-name>testFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
ResponseLoggingFilter.java
 
public class ResponseLoggingFilter implements Filter {
 
    FilterConfig config;
 
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }
 
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain filterChain) throws IOException, ServletException {
 
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
 
        ContentCaptureServletResponse capContent = new ContentCaptureServletResponse(response);
        filterChain.doFilter(request, capContent);
        System.out.println("Response: " + capContent.getContent());
 
 
    }
 
    public void destroy() {
    }
}
ContentCaptureServletResponse.java
 
public class ContentCaptureServletResponse extends HttpServletResponseWrapper {
 
        private ByteArrayOutputStream contentBuffer;
        private PrintWriter writer;
 
        public ContentCaptureServletResponse(HttpServletResponse originalResponse) {
                super(originalResponse); 
        }
 
        @Override
        public PrintWriter getWriter() throws IOException {
                if(writer == null){
                        contentBuffer = new ByteArrayOutputStream();
                        writer = new PrintWriter(contentBuffer);
                }
                return writer;
        }
 
        public String getContent(){
                writer.flush();
                return contentBuffer.toByteArray(); 
        }
}
Comments (0)

Spring + Hibernate Validation Example

 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;
Comments (0)

Spring 3 Annotation Controller Tutorial

web.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:sec="http://www.springframework.org/schema/security"
       xmlns:jms="http://www.springframework.org/schema/jms"
       xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
       http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
       http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.5.0.xsd">
 
    <context:component-scan base-package="gov.bd.nea" />
 
    <mvc:annotation-driven />
    <context:annotation-config />
 
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
 
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
/**
*
* @author Asif
*/
@Controller
@RequestMapping("/test")
public class TestController {
 
@Autowired
private TestService testService;
 
@ModelAttribute("test")
public Test getCommand() {
Test test = new Test();
//test.setName("asif");
return test;
}
 
 
@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addTest(@ModelAttribute("test") Test test, BindingResult result) {
return new ModelAndView("testAdd");
}
 
 
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveTest(@ModelAttribute("test") Test test, BindingResult result) {
//handle error
 
if (result.hasErrors()) {
return "testAdd";
}
 
testService.saveTest(test);
 
return "redirect:/test";
}
 
@ModelAttribute("hobbyList")
public List<String> getHobbyList() {
List<String> hobby = new ArrayList<String>();
hobby.add("Programming");
hobby.add("Photography");
hobby.add("Traveling");
return hobby;
}
 
@ModelAttribute("countryList")
public Map<String, String> populateCountryList() {
 
//Data referencing for java skills list box
Map<String, String> country = new LinkedHashMap<String, String>();
country.put("US", "United Stated");
country.put("CHINA", "China");
country.put("SG", "Singapore");
country.put("MY", "Malaysia");
 
return country;
 
}
 
 
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}
}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
 
 
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Add Test</title>
 
    </head>
 
    <body>
        <h1>Add Test</h1>
        <h1><fmt:message key="button.search"/></h1>
        <h1><spring:message code="button.search"/></h1>
        <c:url var="viewTestUrl" value="/test" />
        <a href="${viewTestUrl}">View Tests</a>
 
        <br /><br />
 
        <form:form modelAttribute="test" method="POST" action="/test/save" enctype="multipart/form-data">
 
            <form:errors path="*" cssClass="errorblock" element="div"/>
 
 
            <form:label path="name">Title:</form:label>
            <form:input path="name"/>
            <form:errors path="name" /><br />
 
            <form:label path="country">Country:</form:label>
            <form:select path="country" items="${countryList}" /><br />
 
            <form:label path="sex">Gender:</form:label>
            <form:radiobuttons path="sex" items="${genderList}" /><br />
 
            <form:label for="file" path="file">File</form:label><br/>
            <form:input path="file" type="file"/><br/>
 
            <input type="submit" value="Save" />
        </form:form>
 
    </body>
</html>
Comments (0)

Spring + Hibernate Tutorial

dispatcher-servlet.xml
 
    <tx:annotation-driven transaction-manager="transactionManager"/>
 
    <context:property-placeholder location="/WEB-INF/jdbc.properties" />
 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>
 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>gov.bd.nea.db.Test</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>                
            </props>
        </property>
    </bean>
 
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
jdbc.properties
 
database.driver=org.apache.derby.jdbc.ClientDriver
database.url=jdbc:derby://localhost:1527/sample
database.user=app
database.password=app
hibernate.dialect=org.hibernate.dialect.DerbyDialect
hibernate.show_sql=true
hibernate.connection.pool_size=5
Test.java
 
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
 
 
import javax.validation.constraints.NotNull;
 
import org.hibernate.annotations.Proxy;
import org.hibernate.validator.constraints.NotEmpty;
 
/**
 *
 * @author Asif
 */
@Entity
@Table(name = "test")
@Proxy(lazy = false)
public class Test implements Serializable {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String sex;
    private String country;
    private String hobby;
 
    @Lob
    @Column(length = 100000)
    private byte[] file;
 
//getter and setter methods
}
TestDaoImpl.java
 
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
/**
 *
 * @author Asif
 */
@Repository("testDao")
public class TestDaoImpl implements TestDao {
 
    @Autowired
    private SessionFactory sessionFactory;
 
    @Override
    public List<Test> getTestList() {
        return (List<Test>) sessionFactory.getCurrentSession().createCriteria(Test.class).list();
 
    }
 
    @Override
    public void save(Test test) {
        sessionFactory.getCurrentSession().saveOrUpdate(test);
    }
 
    @Override
    public Test getTestById(Integer id) {
        return (Test) sessionFactory.getCurrentSession().load(Test.class, id);
    }
}
TestService.java
 
 
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
/**
 *
 * @author Asif
 */
@Service("testService")
@Transactional
public class TestServiceImpl implements TestService {
 
    @Autowired
    private TestDao testDao;
 
    @Override
    public List<Test> getTestList() {
        return testDao.getTestList();
    }
 
    @Override
    public void saveTest(Test test) {
        testDao.save(test);
    }
 
    @Override
    public Test getTestById(Integer id){
        return testDao.getTestById(id);
    }
 
}
TestController.java
 
@Controller
@RequestMapping("/test")
public class TestController {
 
    private static final Logger logger = Logger.getLogger(TestController.class);
 
    @Autowired
    private TestService testService;
 
....
 
.... = testService.getTestById(id);
Comments (0)
Go to Top