Below process depicts integration of Spring Framework with the Web Project. When user access the URL the system will display message which is configured in Spring configuration file (applicationContext.xml).
Prerequisites:
1. Download spring framework libraries as shown below (spring.jar and other dependencies)
2. Application Server to deploy the application
Project Structure (Eclipse J2EE Project template):
Testing:
- JBoss is running on 8080 port where application is deployed
http://localhost:8080/DemoHibernateSpring/hello.jsp
Output:
Resource Reference:
(1) MessageService.java (Interface)
package control;
public interface MessageService {
public String getMessage();
}
--------------------------------------------------------------------
(2) MessageServiceImpl.java (Implementation)
(2) MessageServiceImpl.java (Implementation)
package control;
public class MessageServiceImpl implements MessageService {
private String message;
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
}
--------------------------------------------------------------------
--------------------------------------------------------------------
(4) web.xml
--------------------------------------------------------------------
(5) hello.jsp
--------------------------------------------------------------------
(3) applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="msgService"
class="control.MessageServiceImpl">
<property name="message">
<value>Hi from Spring Framework !</value>
</property>
</bean>
</beans>
(4) web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
(5) hello.jsp
<%@ page import="org.springframework.context.*,org.springframework.web.context.*, control.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
ApplicationContext factory =
(ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
MessageService service = (MessageService)factory.getBean("msgService");
%>
Message : <%=service.getMessage() %>
</body>
</html>