1 导入jar包
- 本文最后会给出项目的地址,各位无须看急。
2 配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- Spring的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Struts2的核心过滤器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
- 其中,Struts2的核心过滤器不必多说。
- Spring的监听器是ServletContext的监听器,当项目启动的时候,ContextLoaderListener会将applicationContext.xml放入到ServletContext对象的域属性中。
- 因为ServletContext对象,所以需要在web.xml中配置<context-param>节点。
3 Action.java
- 示例:ClassesAction.java
package com.xuweiwei.action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.xuweiwei.domain.Classes; import com.xuweiwei.service.ClassesService; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.annotation.Resource; import java.util.List; @Controller("classAction") @Scope("prototype") //此注解表明是单例还是多例 public class ClassesAction extends ActionSupport { @Resource(name=ClassesService.SERVICE_NAME) private ClassesService classesService; /** * 获取所有的班级信息 * @return */ public String classesInfos(){ List<Classes> classesList = classesService.classesInfos(); ServletActionContext.getRequest().setAttribute("classesList",classesList); return Action.SUCCESS; } }
4 项目地址