<!-- 配置struts2 --> <filter> <filter-name>struts2</filter-name> <!-- 默认的struts2的过虑器类 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> --> <!-- 自定义struts2过虑器类 用于解决struts2把cxf的请求当action处理的问题 --> <filter-class>com.ccland.filter.ExtendStruts2Filter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- webservice --> <servlet> <servlet-name>CXFService</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFService</servlet-name> <url-pattern>/CXFService/*</url-pattern> </servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <!-- Import Apache CXF Bean Definition --> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <!-- 将WebService Bean的创建托管给Spring --> <bean id="helloBean" class="com.ccland.service.impl.HelloWorldImpl" /> <bean id="storageBean" class="com.ccland.service.impl.StorageServiceImpl"> <property name="fileStorageDao"> <ref bean="fileStorageDao" /> </property> </bean> <!-- 要发布成webservice的bean --> <jaxrs:server id="restFulContainer" address="/"> <jaxrs:serviceBeans> <ref bean="helloBean" /> <ref bean="storageBean" /> </jaxrs:serviceBeans> </jaxrs:server> </beans>
自定义过虑器ExtendStruts2Filter,为解决Struts把Webservice请求当普通Action被处理掉的问题。
package com.ccland.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // 自定义扩展Struts2过滤器,用于解决struts会拦截cxf webservice请求的问题 public class ExtendStruts2Filter extends StrutsPrepareAndExecuteFilter { private static Logger log = LoggerFactory .getLogger(ExtendStruts2Filter.class); @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest request = (HttpServletRequest) req; // 判断是否是向WebService发出的请求 if (request.getRequestURI().contains("/CXFService")) { // 如果是来自向CXFService发出的请求 chain.doFilter(req, res); } else { // 默认action请求 super.doFilter(req, res, chain); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } } }
package com.ccland.service; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.ccland.model.FileStorage; import com.ccland.model.FileStorages; @Path(value = "/storager") public interface StorageService { @GET @Path(value = "/findById") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public FileStorage findById(@QueryParam("id") String id) throws RuntimeException; @GET @Path(value = "/listAll") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public FileStorages listAll() throws RuntimeException; }
package com.ccland.service.impl; import java.util.List; import com.ccland.dao.FileStorageDao; import com.ccland.model.FileStorage; import com.ccland.model.FileStorages; import com.ccland.service.StorageService; public class StorageServiceImpl implements StorageService { private FileStorageDao fileStorageDao; public void setFileStorageDao(FileStorageDao fileStorageDao) { this.fileStorageDao = fileStorageDao; } @Override public FileStorage findById(String id) throws RuntimeException { try { return this.fileStorageDao.findById(id); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } @Override public FileStorages listAll() throws RuntimeException { FileStorages storager = new FileStorages(); try { List<FileStorage> list = this.fileStorageDao.listFile(); storager.setList(list); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } return storager; } }
package com.ccland.dao; import java.util.List; import com.ccland.model.FileStorage; public interface FileStorageDao { public long save(FileStorage entity) throws Exception; public void delete(String fileUrl) throws Exception; public FileStorage findById(String fileUrl) throws Exception; public List listFile() throws Exception; }
package com.ccland.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import com.ccland.dao.FileStorageDao; import com.ccland.model.FileStorage; public class FileStorageDaoImpl implements FileStorageDao { // Hibernate4不再支持 HibernateTemplate类了 所以this.getHibernateTemplate()不能再用 private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public long save(FileStorage entity) throws Exception { this.sessionFactory.getCurrentSession().save(entity); return entity.getId(); } @Override public void delete(String fileUrl) throws Exception { this.sessionFactory.getCurrentSession().delete(this.findById(fileUrl)); } @Override public FileStorage findById(String fileUrl) throws Exception { FileStorage entity = null; String hql = "from FileStorage where fileUrl=?"; Query query = this.sessionFactory.getCurrentSession().createQuery(hql); query.setString(0, fileUrl); List<FileStorage> list = query.list(); for (FileStorage item : list) { entity = item; } return entity; // return this.getHibernateTemplate().get(FileStorage.class, fileUrl); } @Override public List listFile() throws Exception { // HQL 语句中的字段和表名,必须使用配置文件中定义的名字 StringBuffer hql = new StringBuffer(); hql.append("from FileStorage order by id"); Query query = this.sessionFactory.getCurrentSession().createQuery( hql.toString()); return query.list(); } }
package com.ccland.model; import javax.xml.bind.annotation.XmlRootElement; /** * FileStorage entity. @author MyEclipse Persistence Tools */ @XmlRootElement(name = "FileStorage") public class FileStorage implements java.io.Serializable { // Fields /** * */ private static final long serialVersionUID = 2256369202006332596L; private Long id; private String fileName; private String fileUrl; private Long taskId; // Constructors /** default constructor */ public FileStorage() { } /** minimal constructor */ public FileStorage(String fileName, String fileUrl) { this.fileName = fileName; this.fileUrl = fileUrl; } /** full constructor */ public FileStorage(String fileName, String fileUrl, Long taskId) { this.fileName = fileName; this.fileUrl = fileUrl; this.taskId = taskId; } // Property accessors public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileUrl() { return this.fileUrl; } public void setFileUrl(String fileUrl) { this.fileUrl = fileUrl; } public Long getTaskId() { return this.taskId; } public void setTaskId(Long taskId) { this.taskId = taskId; } }
package com.ccland.model; import java.util.HashMap; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "FileStorages") public class FileStorages { private FileStorage fileStorage; private List<FileStorage> list; private FileStorage[] fileArr; private HashMap<String, FileStorage> maps; public FileStorage getFileStorage() { return fileStorage; } public void setFileStorage(FileStorage fileStorage) { this.fileStorage = fileStorage; } public List<FileStorage> getList() { return list; } public void setList(List<FileStorage> list) { this.list = list; } public HashMap<String, FileStorage> getMaps() { return maps; } public void setMaps(HashMap<String, FileStorage> maps) { this.maps = maps; } public FileStorage[] getFileArr() { return fileArr; } public void setFileArr(FileStorage[] fileArr) { this.fileArr = fileArr; } }
package com.ccland.model; import java.util.Map; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class MapBean { private Map<String, FileStorage> map; public Map<String, FileStorage> getMap() { return map; } public void setMap(Map<String, FileStorage> map) { this.map = map; } }
JS调用测试:
function listAll() { $.ajax({ type : 'get', url : '<%=basePath%>CXFService/storager/listAll', dataType : 'json', data : {}, success : function(res, status, xhr) { alert(res.FileStorages.list[0].fileName); } }); }
返回Json对象: