=========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());
}
}