=========Spring MVC==============================================================
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>T-WebServiceServer</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/spring-*.xml</param-value>
</context-param>
<!-- Spring内置与自定义监听器 -->
<!-- Spring Listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> -->
<listener>
<listener-class>com.sunyf.web.common.cache.MyContextLoaderListener</listener-class>
</listener>
<!-- 自定义与Spring内置的编码过滤器 -->
<!-- filter>
<filter-name>CharsetEncoding</filter-name>
<filter-class>com.sunyf.web.common.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>RequestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>ResponseEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter> -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- WebService 拦截器 -->
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rmi/*</url-pattern>
</servlet-mapping>
<!-- Spring .do请求 拦截器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
<welcome-file>/index.jsp</welcome-file>
<welcome-file>/index.do</welcome-file>
</welcome-file-list>
<error-page>
<error-code>400</error-code>
<location>/index.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
web.xml中配置了 .do请求处理Servlet,因些在web.xm同目录下要配置dispatcher-servlet.xml文件。要求文件名结构为:web.xml中的servlet名称-servlet.xml。
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.nec.bss.web" />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/view/" p:suffix=".jsp" />
<!-- 上传拦截,如最大上传值及最小上传值
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="utf-8" >-->
<!--1024*1024*20即20M
<property name="maxUploadSize" value="20971520" />-->
<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常
<property name="resolveLazily" value="true"/>
</bean>-->
</beans>
spring-core.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- inject -->
<!-- 自动扫描所有注解该路径 -->
<context:component-scan base-package="com.sunyf" />
<!-- 导入属性配置文件 -->
<context:property-placeholder location="classpath:/*Resource.properties" />
</beans>
spring-web.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- inject -->
<mvc:annotation-driven />
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.sunyf.web" />
<!-- 拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<!-- 如果不配置或/*,将拦截所有的Controller -->
<mvc:mapping path="/*" />
<bean class="com.sunyf.web.common.ControllerInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
UserController.java
package com.sunyf.web.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.sunyf.web.common.cache.CacheOperater;
import com.sunyf.web.vo.User;
/**
* @Description TODO
* @author Sunyf
* @date 2013-5-23 下午5:18:57
* @version V1.0
*/
@Controller
@RequestMapping("/user.do")
public class UserController {
private Logger log = Logger.getLogger(this.getClass());
@RequestMapping
public String load(ModelMap m) {
log.info("==========[UserController load] Start...");
Map<String, User> userMap = (Map<String, User>) CacheOperater.getInstance().getUserMap();
m.put("userMap", userMap);
m.put("topMenu", "list");
log.info("==========[UserController load] End...");
return "user/list";
}
@RequestMapping(params = "method=toAdd")
public String toAdd( ModelMap m) throws Exception {
log.info("==========[UserController toAdd] Start...");
m.put("topMenu", "add");
log.info("==========[UserController toAdd] End...");
return "user/add";
}
@RequestMapping(params = "method=add")
public String add(@ModelAttribute("user") User u, HttpServletRequest request, ModelMap modelMap) throws Exception {
log.info("==========[UserController add] Start...");
Map<String, User> userMap = (Map<String, User>) CacheOperater.getInstance().getUserMap();
userMap.put(u.getUserId(), u);
log.info("==========[UserController add] End...");
return "user/add";
}
@RequestMapping(params = "method=delete")
public String delete(@RequestParam("userId") String id, HttpServletRequest request, ModelMap m) throws Exception {
log.info("==========[UserController delete] Start...");
Map<String, User> userMap = (Map<String, User>) CacheOperater.getInstance().getUserMap();
userMap.remove(id);
m.put("userMap", userMap);
log.info("==========[UserController delete] End...");
return "user/list";
}
@RequestMapping(params = "method=toUpdate")
public String toUpdate(@RequestParam("userId") String id, ModelMap m) throws Exception {
log.info("==========[UserController toAdd] Start...");
Map<String, User> userMap = (Map<String, User>) CacheOperater.getInstance().getUserMap();
m.put("user", userMap.get(id));
m.put("topMenu", "update");
log.info("==========[UserController toAdd] End...");
return "user/update";
}
@RequestMapping(params = "method=update")
public String update(@ModelAttribute("user") User u, HttpServletRequest request, ModelMap m) throws Exception {
log.info("==========[UserController add] Start...");
Map<String, User> userMap = (Map<String, User>) CacheOperater.getInstance().getUserMap();
userMap.put(u.getUserId(), u);
m.put("userMap", userMap);
m.put("topMenu", "list");
log.info("==========[UserController add] End...");
return "user/list";
}
@InitBinder
public void initBinder(WebDataBinder binder) {
// 忽略字段绑定异常
// binder.setIgnoreInvalidFields(true);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, "birth",
new CustomDateEditor(format, true));
}
}
list.jsp
<%@ page language="java" errorPage="/error.jsp" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%> <%@ include file="/includes/taglibs.jsp"%> <!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> <title>用户列表</title> <meta name="menu" content="list" /> <link rel="stylesheet" type="text/css" href="./css/tablesorter/style.css" /> <script type="text/javascript" src="./js/jquery.tablesorter.js"></script> </head> <body> <h1>Users</h1> <table id="tableList" class="tablesorter" cellspacing="1"> <thead> <tr> <th>NO.</th> <th>UserId</th> <th>UserName</th> <th>Birth</th> <th>Operation</th> </tr> </thead> <tbody> <c:forEach var="prop" items="${userMap}" varStatus="status"> <c:set var="user" value="${prop.value }"></c:set> <tr> <td align="center"> <c:choose> <c:when test="${status.count%2==0}"> <img src="images/user-online.png" /> </c:when> <c:otherwise> <img src="images/user-offline.png" /> </c:otherwise> </c:choose> ${status.count } </td> <td><c:out value="${user.userId}" /></td> <td><c:out value="${user.userName}" /></td> <td align="center"><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" value="${user.birth}" /></td> <td> <a href="user.do?method=toUpdate&userId=${user.userId }">编辑</a> <a href="user.do?method=delete&userId=${user.userId }">删除</a> </td> </tr> </c:forEach> </tbody> </table> <script type="text/javascript"> //<![CDATA[ $(function() { $('#tableList').tablesorter(); //$('#tableList').tablesorter( {sortList: [[0,0], [1,0]]} ); //$('table tr:nth-child(odd)').addClass('odd'); $('table tr:nth-child(even)').addClass('even'); }); //]]> </script> </body> </html>
=========Apache CXF=============================================================
spring-ws.xml
<?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:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<jaxws:endpoint id="RemoteService"
implementor="com.sunyf.web.ws.impl.RemoteServiceImpl" address="/RemoteService">
<jaxws:inInterceptors>
<bean class="com.sunyf.web.common.WebServiceInterceptor" />
</jaxws:inInterceptors>
</jaxws:endpoint>
</beans>
WebServiceInterceptor.java
package com.sunyf.web.common;
import javax.servlet.http.HttpServletRequest;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
/**
* @Description TODO
* @author Sunyf
* @date 2013-5-21 下午4:55:21
* @version V1.0
*/
public class WebServiceInterceptor extends AbstractPhaseInterceptor<Message> {
private Logger log = Logger.getLogger(this.getClass());
public WebServiceInterceptor() {
super(Phase.POST_INVOKE);
}
@Value("${msg.client.ipUnknow}")
private String ipUnknow;
@Value("${msg.client.ipIllegal}")
private String ipIllegal;
@Value("${msg.client.checkSuss}")
private String checkSuss;
// 利用正则映射到需要拦截的路径
@Value("${cfg.client.ips}")
private String clientIPs;
public void handleMessage(Message message) throws Fault {
log.info("==========[WebServiceInterceptor] Start...");
//指定CXF获取客户端的HttpServletRequest : http-request;
HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
if (null == request) {
log.info("==========[null:null]" + ipUnknow);
throw new Fault(new IllegalAccessException(ipUnknow));
}
// 客户端IP验证
String ip = request.getRemoteHost().toString();
int port = request.getRemotePort();
String logStart = "==========[" + ip + ":" + port + "]";
log.info(logStart + request.getRequestURI());
if (clientIPs == null || !ip.matches(clientIPs)) {
log.info(logStart + ipIllegal);
throw new Fault(new IllegalAccessException(ipIllegal));
}
log.info(logStart + checkSuss);
log.info("==========[WebServiceInterceptor] End...");
}
}
RemoteService.java
package com.sunyf.web.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.sunyf.web.vo.Result;
import com.sunyf.web.vo.User;
@WebService
public interface RemoteService {
@WebMethod
User findUserById(String id);
@WebMethod
Result saveUser(User u);
}
RemoteServiceImpl.java
package com.sunyf.web.ws.impl;
import java.util.Date;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Value;
import com.sunyf.web.ws.RemoteService;
import com.sunyf.web.vo.Result;
import com.sunyf.web.vo.User;
@WebService
public class RemoteServiceImpl implements RemoteService {
@Value("${msg.saveuser.success}")
private String saveUserSuccess;
@Value("${msg.saveuser.isnull}")
private String saveUserIsnull;
@Value("${msg.saveuser.exist}")
private String saveUserExist;
// @Resource
// private MsgValidator msgVali;
public User findUserById(String id) {
if("sunyf".equals(id)) {
User u = new User();
u.setUserId(id);
u.setUserName("孙云芳");
u.setBirth(new Date());
return u;
} else {
return null;
}
}
public Result saveUser(User u) {
Result r = new Result();
if(null == u) {
r.setSuccess(Result.FAILURE);
r.setDescribe(saveUserIsnull);
return r;
}
if("sunyf".equals(u.getUserId())) {
r.setSuccess(Result.FAILURE);
r.setDescribe(saveUserExist);
return r;
} else {
r.setSuccess(Result.SUCCESS);
r.setDescribe(saveUserSuccess);
return r;
}
}
}
ClientTest.java
package com.sunyf.web.client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.sunyf.web.ws.RemoteService;
import com.sunyf.web.vo.Result;
import com.sunyf.web.vo.User;
/**
* @Description TODO
* @author Sunyf
* @date 2013-5-21 下午3:58:02
* @version V1.0
*/
public class ClientTest {
public static void main(String[] args) {
JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
// factoryBean.getInInterceptors().add(new LoggingInInterceptor());
// factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
factoryBean.setServiceClass(RemoteService.class);
factoryBean.setAddress("http://127.0.0.1:8080/T-WebServiceServer/rmi/RemoteService");
RemoteService impl = (RemoteService) factoryBean.create();
// 查询用户
User user = impl.findUserById("sunyf");
System.out.println(user.getUserId() + "==>" + user.getUserName() + "==>" + user.getBirth());
User u = null;
Result r = null;
// 保存用户U1
r = impl.saveUser(u);
System.out.println(u + "==>" + r.isSuccess() + "==>" + r.getDescribe());
// 保存用户U2
u = new User();
u.setUserId("sunyf");
r = impl.saveUser(u);
System.out.println(u.getUserId() + "==>" + r.isSuccess() + "==>" + r.getDescribe());
// 保存用户U3
u = new User();
u.setUserId("sun");
r = impl.saveUser(u);
System.out.println(u.getUserId() + "==>" + r.isSuccess() + "==>" + r.getDescribe());
}
}
相关推荐
Web项目中基于Maven与Spring整合的WebService之cxf的实现⬇️ 详情请参考如下链接: https://locqi.github.io/locqi.com/2018/09/05/Eclipse+Maven+Spring+CXF-create-WebService/
【标题】"maven+spring+cxf webservice demo"是一个基于Maven、Spring和CXF框架的Web服务示例项目,旨在展示如何整合这三个技术来创建和消费Web服务。Maven是项目管理和构建工具,Spring提供了强大的依赖注入和面向...
这个示例中的具体应用是通过一个名为"HelloWorld"的服务来展示的,其Web Service地址为`http://localhost:8080/springCxf/HelloWorld?wsdl`。让我们逐步了解这个过程。 **1. Spring框架介绍** Spring是一个广泛使用...
Spring框架是Java企业级应用开发的首选,而CXF是一个强大的开源服务框架,支持创建和消费Web服务。本教程将深入探讨如何利用Spring和CXF来实现基于HTTP和HTTPS的Web服务,并且将涉及到HTTPS的证书配置。 1. **...
本教程将深入探讨如何利用Apache CXF 2与Spring 2.5来构建和使用WebService。 首先,让我们理解这两个组件的基本概念。Apache CXF是一个全面的服务框架,它支持多种Web服务规范,如SOAP、RESTful、WS-*等。它提供了...
【标题】"mybatis+spring+cxf Webservice框架"是一个集成性的开发框架,它结合了三个主流的技术组件:MyBatis、Spring和Apache CXF,用于构建高效、灵活且易于维护的Web服务。MyBatis是一个优秀的持久层框架,Spring...
idea+maven+spring+cxf
【标题】"maven项目 cxf webservice"指的是使用Maven构建的一个项目,该项目集成了Apache CXF框架来开发Web服务。Apache CXF是一个开源的Java框架,它允许开发者创建和消费各种Web服务,包括SOAP和RESTful服务。...
【标题】"webservice=maven+spring+cxf" 指的是使用 Maven 作为构建工具,Spring 作为框架,CXF 作为 Web 服务实现的综合应用。这三者结合,可以高效地创建和消费 Web 服务。 【描述】"we服务端+java客户端代码" ...
maven+spring+cxf+mybatis 搭建的webservice项目
【Spring-CXF WebService】是基于Spring框架和Apache CXF实现的一个Web服务示例,它展示了如何在Spring环境中集成CXF来创建、部署和消费Web服务。Spring-CXF结合了Spring的强大功能和CXF的优秀Web服务支持,使得开发...
在IT行业中,Maven、Spring和CXF是三个非常重要的技术组件,它们分别在构建、管理和提供Web服务方面发挥着核心作用。以下是对这个"Maven+Spring+CXF"项目的详细解释: **Maven**: Maven是一个项目管理工具,主要...
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/> <cxf:bus> <cxf:features> <cxf:logging/> </cxf:features> </cxf:bus> ...
Spring + cxf = webservice 完整实例源码免费下载 完全免费。此资源仅为文档提供。 版权为百度文档 "Spring + cxf = webservice 完整实例源码免费下载" 所有。
【标题】"Spring+CXF 开发Web Service" 在Java世界中,开发Web服务的一个常见选择是使用Spring框架结合Apache CXF。Spring作为一个强大的轻量级框架,提供了丰富的功能,包括依赖注入、AOP(面向切面编程)以及企业...
【标题】"maven整合Spring MVC Mybatis"涉及的核心知识点主要集中在Java Web开发中的三大框架——Spring、Spring MVC和Mybatis的集成应用上。对于初学者来说,理解这些框架的协同工作方式至关重要。 首先,Maven是...
本文将深入探讨如何使用Spring和CXF来发布WebService服务。 首先,Spring是一个开源的Java平台,它提供了全面的编程和配置模型,用于简化企业级应用的开发。Spring框架的核心特性包括依赖注入、面向切面编程(AOP)...
蛮简陋的一个项目,适合新手使用。 这是一个包含简单登录和查询的Web项目,内附有一个表sql文件和两个java项目。...WS_Client是客户端,是一个project项目,内部有一个WebService的测试类,用来测试从服务端取得数据