WebService 综合案例
1. 需求:
- 集成公网手机号归属地查询服务;
- 对外发布自己的手机号归属地查询服务;
- 提供查询界面
//1. 使用 wsimport 生成公网客户端代码
// 2. 创建 SEI 接口
@WebService
public interface MobileInterface{
public String queryMobile(String phoneNum);
}
// 3. 创建 SEI 实现类
public class MobileImpl implements MobileInterface{
// 公网服务客户端, 使用 Spring 注入
private MobileCodeWSSoap mobileClient;
public MobileCodeSWWoap getMobileClient(){
return mobileClient;
}
public void setMobileClient(MobileCodeWSSoap mobileClient){
this.mobileClient = mobileClient;
}
public String queryMobile(String phoneNum){
// 调用公网服务客户端查询方法
return mobileClient.getMobileCodeInfo(phoneNum,"");
}
}
// 4. 创建 queryMobile.jsp
<form action="${pageContext.request.contextPath}/queryMobile.action" method="post">
手机号码归属地查询:<input type="text" name="phoneNum"/><input type="submie" value="查询"/>
<br/>
查询结果:${result}
</form>
// 5. 创建 MobileServlet.java
public class MobileServlet extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String phoneNum = req.getParameter("phoneNum");
if(null != phoneNum && !"".equals(phoneNum)){
// 获取 Spring 框架中的内容
ApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
// 获取 mobileServer 对象
mobileServer = (MobileInterface)context.getBean("mobileServer");
String result = mobileServer.queryMobile(phoneNum);
request.setAttribute("result",result);
}
request.getRequest.Dispatcher("/jsp/queryMobile.jsp").forward(req,resp);
}
}
// 6. 配置 applicationContext.xml
<!-- jaxws:server 发布服务 -->
// 配置服务地址和服务接口
<jaxws:server address="/mobile" serviceClass="cn.itcast.mobile.server.MobileInterface">
<jaxws:serviceBean>
<ref bean="mobileServer"/>
</jaxws:serviceBean>
</jaxws:server>
<!-- 配置服务实现类 -->
<bean name="mobileServer" class="cn.itcast.mobile.server.MobileImpl">
<!-- 注入公网客户端 --
<property name="mobileClient" ref="mobileClient"/>
</bean>
<!-- 配置公网客户端 -->
<jaxws:client id="mobileClient"
address="http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"
serviceClass="cn.itcast.mobile.MobileCodeWSSoap"/>
// 7. 配置 web.xml
// 参照 CXF+Spring 整合发布SOAP协议服务
// 配置 MobileServlet
<servlet>
<servlet-name>mobileServlet</servlet-name>
<servlet-class>cn.itcast.mobile.server.servlet.MobileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mobileServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
参考资料