Apache CXF implements Web Service (4)--tomcat container and spring implementation Jax-rs (RESTful) Web Service

Source: Internet
Author: User

Get ready

We still implement Web service using Apache cxf (2)--without the use of heavyweight web containers and spring to implement code in a pure Jax-rs (RESTful) Web service as a basis, and to introduce spring for RESTful Configuration and management of Web service.

Project directory structure such as

First we will add the Spring runtime environment loaded with spring Contextloaderlistener and the spring configuration file of CXF in Web. xml

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" 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>cxf</          Display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/web-inf/cxf-servlet.xml</param-value> </context-param> <!--settings to move the current web app together, load spring and let spring manage beans--<l      Istener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <description>m CXF endpoint</description> <display-name&gt ;cxf</display-name> <servlet-name>cxf</servlet-name> <servlet-class> Org.apache.cxf.transport.servlet.cxfservlet</servlet-class> <load-on-startup>1</load-on-startup > </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/ser vices/*</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</ Session-timeout> </session-config></web-app>

Note that the spring configuration file is named and the path "/web-inf/cxf-servlet.xml", if the project file is renamed to Applicationcontext.xml, and the Web. XML is also modified to "/web-inf/ Applicationcontext.xml ", the Tomcat server will prompt for an error message when it starts: (How to solve this problem later)

org.springframework.beans.factory.BeanDefinitionStoreException:IOException parsing XML document from ServletContext resource [/web-inf/cxf-servlet.xml]; Nested exception is java.io.FileNotFoundException:Could not open ServletContext resource [/web-inf/cxf- Servlet.xml] at Org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions ( Xmlbeandefinitionreader.java:54w) at Org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions ( Xmlbeandefinitionreader.java:60W) at Org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions ( Abstractbeandefinitionreader.java:174) at Org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions ( Abstractbeandefinitionreader.java:209) at Org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions ( Abstractbeandefinitionreader.java:180) at Org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions ( Xmlwebapplicationcontext.java:125) at Org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions ( Xmlwebapplicationcontext.java:94) at Org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory ( Abstractrefreshableapplicationcontext.java:130) at Org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory ( Abstractapplicationcontext.java:537) at Org.springframework.context.support.AbstractApplicationContext.refresh (Abstractapplicationcontext.java: 451) at Org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext ( Contextloader.java:389) at Org.springframework.web.context.ContextLoader.initWebApplicationContext (Contextloader.java:294) at org.springframework.web.context.ContextLoaderListener.contextInitialized (Contextloaderlistener.java: 112) at Org.apache.catalina.core.StandardContext.listenerStart (Standardcontext.java:4793) at Org.apache.catalina.core.StandardContext.startInternal (Standardcontext.java:5236) at Org.apache.catalina.util.LifecycleBase.start (Lifecyclebase.java:150) at Org.apache.catalina.core.containerbase$startchild.call (Containerbase.java:1408) at Org.apache.catalina.core.containerbase$startchild.call (Containerbase.java:1398) at Java.util.concurrent.FutureTask.run (Futuretask.java:266) at Java.util.concurrent.ThreadPoolExecutor.runWorker (Threadpoolexecutor.java:1142) at Java.util.concurrent.threadpoolexecutor$worker.run (Threadpoolexecutor.java:617) at Java.lang.Thread.run (Thread.java:745) caused by:java.io.FileNotFoundException: Could not open ServletContext resource [ /web-inf/cxf- Servlet.xml] at Org.springframework.web.context.support.ServletContextResource.getInputStream ( Servletcontextresource.java:140) at Org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions ( Xmlbeandefinitionreader.java:328)    ... More

In the/web-inf directory, we add the file Cxf-servlet.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs= "Http://cxf.apache.org/jaxrs" 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.xsdHttp://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd "><import resource= "Classpath:meta-inf/cxf/cxf.xml"/> <import resource= "Classpath:meta-inf/cxf/cxf-ser Vlet.xml "/><bean id= "Roomservice" class= "Com.cnblog.richaaaard.cxftest.spring.rs.helloworld.service.RoomService" > < /bean> <jaxrs:server id= "Restcontainer" address= "/" > <jaxrs:serviceBeans> <re F bean= "Roomservice"/> </jaxrs:serviceBeans> <jaxrs:providers> <bean class= "O Rg.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider "/> </jaxrs:providers><!--<jaxrs:extensionmap pings>--><!--<entry key= "json" value= "Application/json"/>--><!--<entry key= "x ML "value=" application/xml "/>--><!--</jaxrs:extensionMappings>-</jaxrs:server></b Eans>

Attention

Spring support in the file, and Http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd (if it is a WS-Type web Service is required to introduce JAXWS specifications)

We can also see that the file is injected into the jaxrs:server by the spring Bean's configuration of the Roomservice instance.

The red highlighted "Import resource" section is also required, otherwise the Tomcat server will start with an error:

Info: Loading XML bean definitions from URL [file:/users/richard/documents/dev/workspace/eclipse/.metadata/.plugins/ org.eclipse.wst.server.core/tmp0/wtpwebapps/cxf-test-rs-spring-helloworld/web-inf/cxf-Servlet.xml] December02, 2015 4:34:02pm Org.springframework.beans.factory.support.DefaultListableBeanFactory preinstantiatesingletons Info: Pre-instantiating singletons in Org.s[email protected]58318a06:defining beans [Roomservice,restcontainer]; Parent:org.s[email protected]22252012566 [localhost-startstop-1] INFO org.apache.cxf.endpoint.serverimpl-setting The server ' s publish address to be/December 02, 2015 4:34:02pm Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroysingletons Info: destroying singletons in Org.s[email protected]58318a06:defining beans [Roomservice,restcontainer]; Parent:org.s[email protected]22252012December02, 2015 4:34:02pm Org.apache.catalina.core.ApplicationContext Log Grave: StandardWrapper.Throwableorg.springframework.beans.factory.BeanCreationException:Error Creating Bean with Name ' Restcontainer ': Invocation of Init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException At Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean ( Abstractautowirecapablebeanfactory.java:1482) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean ( Abstractautowirecapablebeanfactory.java:521) at Org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean ( Abstractautowirecapablebeanfactory.java:458) at org.springframework.beans.factory.support.abstractbeanfactory$1.getObject (abstractbeanfactory.java:295) at Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( Defaultsingletonbeanregistry.java:223) at Org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (Abstractbeanfactory.java:292) at Org.springframework.beans.factory.support.AbstractBeanFactory.getBean (Abstractbeanfactory.java:194) at Org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons ( Defaultlistablebeanfactory.java:628) at Org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization ( Abstractapplicationcontext.java:932) at Org.springframework.context.support.AbstractApplicationContext.refresh (Abstractapplicationcontext.java: 479) at Org.apache.cxf.transport.servlet.CXFServlet.createSpringContext (Cxfservlet.java:151) at Org.apache.cxf.transport.servlet.CXFServlet.loadBus (Cxfservlet.java:74) at Org.apache.cxf.transport.servlet.CXFNonSpringServlet.init (Cxfnonspringservlet.java:77) at Org.apache.catalina.core.StandardWrapper.initServlet (Standardwrapper.java:1231) at Org.apache.catalina.core.StandardWrapper.loadServlet (Standardwrapper.java:1144) at Org.apache.catalina.core.StandardWrapper.load (Standardwrapper.java:1031) at Org.apache.catalina.core.StandardContext.loadOnStartup (Standardcontext.java:4978) at Org.apache.catalina.core.StandardContext.startInternal (Standardcontext.java:5270) at Org.apache.catalina.util.LifecycleBase.start (Lifecyclebase.java:150) at Org.apache.catalina.core.containerbase$startchild.call (Containerbase.java:1408) at Org.apache.catalina.core.containerbase$startchild.call (Containerbase.java:1398) at Java.util.concurrent.FutureTask.run (Futuretask.java:266) at Java.util.concurrent.ThreadPoolExecutor.runWorker (Threadpoolexecutor.java:1142) at Java.util.concurrent.threadpoolexecutor$worker.run (Threadpoolexecutor.java:617) at Java.lang.Thread.run (Thread.java:745) caused by:org.apache.cxf.service.factory.ServiceConstructionException at Org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create (Jaxrsserverfactorybean.java:219) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nativemethodaccessorimpl.java:62) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (Method.java:497)
What does "import resource" do?

Pending research

At last

We run the Web project in Tomcat and access it through the browser

* Extended
    • Why use the Applicationcontext.xml server error, from the error message, it still try to find the Cxf-servlet.xml file?

After looking at the project structure, I found that the file specified in/webcontent/web-inf is also a cxf-servlet.xml, and this web. XML is not synchronized with our files under/src/main/webapp/web-inf. , the file read at Tomcat startup is under WebContent, and the server is normal after the modification.

    

Why is that? So how do you keep the files in the src file in sync with the files in the webcontent? (In fact, this is an online example of the disaster)

We right-view the properties of the entire project Properties->web Deployment Assembly found in the deployment configuration/src/main/webapp and/webcontent are output to the root directory of the server deployment Target "/" and "/ WebContent "/src/main/webapp" after the output, so will overwrite the contents of the previous WebApp, so we have to do is to just keep one output-delete WebApp This line of configuration, Then copy the Applicationcontext.xml file under the original WebApp to WebContent.

After experimentation, the server can start normally.

    • What does "import resource" do? Why its path is "Classpath:meta-inf/cxf/cxf.xml" and "Classpath:meta-inf/cxf/cxf-servlet.xml"

We found that Cxf.xml and cxf-servlet.xml two files are not in the path of our project source code, then is not in the CXF related jar package?

The answer is yes.

Cxf.xml exists in the Cxf-core.jar/meta-inf/cxf/cxf.xml

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xsi:schemalocation="/HTTP/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd/HTTP    Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!--for testing using the Spring Commons processor, uncomment one of:--> <!--<bean class = "Org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> <context:annotation-con    Fig/>--<bean id= "CXF" class= "Org.apache.cxf.bus.spring.SpringBus" destroy-method= "Shutdown"/> <bean id= "Org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor" class= " Org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor "/> <bean id=" Org.apache.cxf.bus.spring.Jsr250BeanPostProcessoR "class=" Org.apache.cxf.bus.spring.Jsr250BeanPostProcessor "/> <bean id=" Org.apache.cxf.bus.spring.BusExtensionPostProcessor "class=" org.apache.cxf.bus.spring.BusExtensionPostProcessor "/></beans>

Cxf-servlet.xml exists and Cxf-rt-transports-http.jar in

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:foo=" Http://cxf.apache.org/configuration/foo "xsi:schemalocation="/HTTP/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "></ Beans>

The strange thing is that there is nothing in the cxf-servlet.xml here, so can we get rid of it? (The answer??? Self-validating)

So the cxf-servlet.xml configured in spring is just the same as in the import resource here, two files are not the same, the path is not the same.

So what's the use of this file inside the Cxf-core.jar cxf.xml configuration?

Later decomposition:)

Reference:

Https://www.mail-archive.com/[email protected]/msg00488.html

Http://www.cnblogs.com/hoojo/archive/2011/03/30/1999563.html

Http://www.kuqin.com/shuoit/20140716/341250.html

Https://cwiki.apache.org/confluence/display/CXF20DOC/JAXRS+Services+Configuration

Apache CXF implements Web Service (4)--tomcat container and spring implementation Jax-rs (RESTful) Web Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.