Maven版,Spring mvc, CXF WebService, WebService/Controller Interceptor, Sitemesh

阅读更多

  =========Spring MVC==============================================================

 

 web.xml



	T-WebServiceServer
	
		contextConfigLocation
		classpath:/spring/spring-*.xml
	
	
	
	
	
		com.sunyf.web.common.cache.MyContextLoaderListener
	
	
	
	
	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
		encodingFilter
		/*
	

	
	
		sitemesh
		com.opensymphony.module.sitemesh.filter.PageFilter
	
	
		sitemesh
		/*
		REQUEST
		FORWARD
	
	
	
	
		CXFServlet
		org.apache.cxf.transport.servlet.CXFServlet
	
	
		CXFServlet
		/rmi/*
	

	
	
		dispatcher
		org.springframework.web.servlet.DispatcherServlet
	
	
		dispatcher
		*.do
	

	
		30
	

	
		/index.html
		/index.jsp
		/index.do
	

	
		400
		/index.jsp
	
	
		403
		/403.jsp
	
	
		404
		/404.jsp
	
	
		500
		/error.jsp
	

 web.xml中配置了 .do请求处理Servlet,因些在web.xm同目录下要配置dispatcher-servlet.xml文件。要求文件名结构为:web.xml中的servlet名称-servlet.xml。

dispatcher-servlet.xml




	
	
	
	

	
	

	 
		
        

 spring-core.xml



	
	
	
	
	

 spring-web.xml



	
	
	
	

	
	
		
		
			
			
			
		
	


 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 userMap = (Map) 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 userMap = (Map) 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 userMap = (Map) 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 userMap = (Map) 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 userMap = (Map) 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"%>



	用户列表
	
	
	


Users

NO. UserId UserName Birth Operation
${status.count } 编辑 删除

 

 

=========Apache CXF=============================================================

spring-ws.xml




	
	
	

	
		
			
		
	


 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 {

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

}

 

 
Maven版,Spring mvc, CXF WebService, WebService/Controller Interceptor, Sitemesh_第1张图片
 

  • T-WebServiceServer.rar (303.6 KB)
  • 下载次数: 294
  • Maven版,Spring mvc, CXF WebService, WebService/Controller Interceptor, Sitemesh_第2张图片
  • 大小: 130.9 KB
  • 查看图片附件

你可能感兴趣的:(webservice,spring,mvc,Sitemesh)