Spring
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>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);
Spring + Sitemesh
web.xml <!--Sitemesh--> <filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter </filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
decorators.xml <?xml version="1.0" encoding="UTF-8"?> <decorators defaultdir="/WEB-INF/jsp/layouts"> <decorator name="main" page="main.jsp"> <pattern>/*</pattern> </decorator> </decorators>
main.jsp <%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title><decorator:title default="MySite" /></title> </head> <body> <h1>Template</h1> <decorator:body /> </body> </html>
Spring Locale Change
dispatcher-servlet.xml
<!--Message/Locale-->
<mvc:interceptors>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="es"/>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>messages_en_US.properties button.cancel=Cancel button.create=Create button.edit=Edit button.delete=Delete button.reset=Reset button.save=Save button.search=Search
messages_es.properties button.cancel=Cancelar button.create=Crear button.edit=Corregir button.delete=Borrar button.reset=Restaurar button.save=Guardar button.search=Buscar
To change locale: any url?lang=en
Spring Security Configuration
web.xml
<!–Spring security–>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
applicationContext.xml
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:sec=”http://www.springframework.org/schema/security”
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd”>
<!–Spring Security–>
<sec:global-method-security secured-annotations=”enabled” />
<sec:http auto-config=”true” access-denied-page=”/accessDenied.jsp” >
<sec:intercept-url pattern=”/login.jsp*” filters=”none”/>
<sec:intercept-url pattern=”/admin/editUser.do” access=”ROLE_ADMIN” />
<sec:intercept-url pattern=”/admin/searchUsers.do” access=”ROLE_ADMIN” />
<sec:intercept-url pattern=”/**” access=”ROLE_USER” />
<sec:form-login authentication-failure-url=”/login.jsp?login_error=1″ default-target-url=”/home.do”/>
<sec:logout logout-success-url=”/home.do”/>
</sec:http>
<sec:authentication-manager>
<sec:authentication-provider>
<sec:password-encoder hash=”md5″/>
<sec:user-service>
<sec:user name=”rod” password=”a564de63c2d0da68cf47586ee05984d7″ authorities=”ROLE_SUPERVISOR, ROLE_USER, ROLE_TELLER” />
<sec:user name=”dianne” password=”65d15fe9156f9c4bbffd98085992a44e” authorities=”ROLE_USER,ROLE_TELLER” />
<sec:user name=”scott” password=”2b58af6dddbd072ed27ffc86725d7d3a” authorities=”ROLE_USER” />
<sec:user name=”peter” password=”22b5c9accc6e1ba628cedc63a72d57f8″ authorities=”ROLE_USER” />
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
<!–
Usernames/Passwords are
rod/koala
dianne/emu
scott/wombat
peter/opal
–>
login.jsp
<%@ taglib prefix=’c’ uri=’http://java.sun.com/jstl/core_rt’ %>
<%@ page import=”org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter” %>
<%@ page import=”org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter” %>
<%@ page import=”org.springframework.security.core.AuthenticationException” %>
<html>
<head>
<title>Spring Security Login — </title>
</head>
<body>
<h1>Login</h1>
<c:if test=”${not empty param.login_error}”>
<font color=”red”>
Your login attempt was not successful, try again.<br/><br/>
Reason: <c:out value=”${SPRING_SECURITY_LAST_EXCEPTION.message}”/>.
</font>
</c:if>
<form name=”f” action=”<c:url value=’j_spring_security_check’/>” method=”POST”>
<table>
<tr><td>User:</td><td><input type=’text’ name=’j_username’ value=’<c:if test=”${not empty param.login_error}”><c:out value=”${SPRING_SECURITY_LAST_USERNAME}”/></c:if>’/></td></tr>
<tr><td>Password:</td><td><input type=’password’ name=’j_password’></td></tr>
<tr><td><input type=”checkbox” name=”_spring_security_remember_me”></td><td>Don’t ask for my password for two weeks</td></tr>
<tr><td colspan=’2′><input name=”submit” type=”submit”></td></tr>
</table>
</form>
</body>
<a href=”<c:url value=”/j_spring_security_logout”/>”>Logout</a>
</html>