简单web应用spring
1、创建Bean
package com.test.spring;
public class MessageBean {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2、Spring配置:applicationContext.xml(放在WEB-INF/目录下)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- id指定bean 的访问名称,class指定bean的实现类 -->
<bean id="messageBean" class="com.test.spring.MessageBean">
<property name="message"><!-- name指定bean实现类的属性 -->
<value>Spring framework web project test config file:applicationContext.xml!</value><!--指定了向bean属性注入的值 -->
</property>
</bean>
</beans>
注明:spring框架默认使用/WEB-INF/applicationContext.xml作为配置文件。
3、部署描述符文件:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringTest</display-name>
<!-- 监听器-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>SpringWebTest</servlet-name>
<servlet-class>com.test.spring.SpringWebTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SpringWebTest</servlet-name>
<url-pattern>/SpringWebTest</url-pattern>
</servlet-mapping>
</web-app>
通过上面的配置,ContextLoaderListener监听器默认查找/WEB-INF/applicationContext.xml文件。
如果要改变spring的配置文件名称或者位置,需要在web.xml中指定,如:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans-config.xml</param-value>
</context-param>
4、创建servlet类:
package com.test.spring;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class SpringWebTest extends HttpServlet{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//super.doGet(req, resp);
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(request, response);
PrintWriter out = response.getWriter();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
MessageBean bean = (MessageBean)ac.getBean("messageBean");
out.print(bean.getMessage());
out.close();//close
}
}
5、启动tomcat,显示结果。