cxf+spring+tomcat 发布RESTful类型的服务

具体关于SOAP和RESTful类型的服务的区别,可自行百度。

创建web工程,我的工程名是:RESTStyleMailServer

工程结构

1. JavaBean的编写。

package edu.ncut.mail;

import java.io.Serializable;
import java.util.Observable;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Mail")
public class Mail extends Observable implements Serializable{
	
	/**  设置SMTP端口号  */    
	private static final String MAIL_PORT = "25";
	/**  邮件发送服务器地址  */    
	private static final String MAIL_SERVAL_HOST = "smtp.126.com";
	/**  邮件发送服务器是否需要验证,默认为TRUE  */    
	private boolean validate ;
	/**  邮件主题  */    
	private String subject;
	/**  邮件内容  */    
	private String content;
	private String fromAddress;
	private String toAddress;
	/**  验证时的用户名和密码  */    
	private String username = null;
	private String password = null;
	private transient Authenticator authenticator = null;
	//验证
	
	public String sendMail(){
		
		if(isValidate()){
			authenticator = new Authenticator() {

				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					// TODO Auto-generated method stub
					return new PasswordAuthentication(getUsername(), getPassword());
				}
				
			};
		}
		if(isValidate() && authenticator == null){
			return "failure";
		}
		
		this.setChanged();
		this.notifyObservers(this);
		return "success";
	}
	public Mail(){
		validate = true;
	}
	
	public Mail(String from, String to, String subject, String content,
			String password) {
		this.fromAddress = from;
		this.toAddress = to;
		this.subject = subject;
		this.content = content;
		this.password = password;
		this.username = from;
		validate = true;
	}

	/**
	 * 方法名称:getProp()
	 * 方法描述:验证时所需要的额属性
	 * @param  
	 * @return String    
	 * @Exception 
	 */
	public Properties getProp() {
		Properties p = new Properties();
		p.put("mail.smtp.host", MAIL_SERVAL_HOST);
		p.put("mail.smtp.port", MAIL_PORT);
		p.put("mail.smtp.auth", validate ? "true" : "false");
		return p;
	}
	public String getSubject() {
		return subject;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isValidate() {
		return validate;
	}
	public void setValidate(boolean validate) {
		this.validate = validate;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}


	public String getFromAddress() {
		return fromAddress;
	}


	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
		setUsername(fromAddress);
	}


	public String getToAddress() {
		return toAddress;
	}


	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}


	public Authenticator getAuthenticator() {
		return authenticator;
	}


	public void setAuthenticator(Authenticator authenticator) {
		this.authenticator = authenticator;
	}
	@Override
	public String toString() {
		return "Mail [validate=" + validate + ", subject=" + subject
				+ ", content=" + content + ", fromAddress=" + fromAddress
				+ ", toAddress=" + toAddress + ", username=" + username
				+ ", password=" + password + "]";
	}
	
}
import java.io.Serializable;
import java.util.Observable;
import java.util.Observer;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Sender")
public class Sender implements Observer,Serializable {

	
	/**     
	 * @param o
	 * @param obj    
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)    
	 */
	@Override
	public void update(Observable o, Object obj) {
		// TODO Auto-generated method stub

		System.out.println("execute");
		final Mail mail = (Mail)obj;
		System.out.println(mail);
		
		//创建session
		try {
			Session session = Session.getInstance(mail.getProp(), mail.getAuthenticator());
			Message message = new MimeMessage(session);
			message.setSubject(mail.getSubject());
			message.setFrom(new InternetAddress(mail.getFromAddress()));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getToAddress()));
			message.setText(mail.getContent());
			//发送
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

}
2. 对外服务接口的编写。
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import edu.ncut.mail.Mail;
import edu.ncut.mail.Sender;

@Produces({MediaType.TEXT_XML})  
@Path("/impl")
public class MailServiceImpl {

/*

   注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。 
   @Path:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/RESTful/rest/hello。 
   @GET:这意味着以下方法可以响应 HTTP GET 方法。 
   @Produces:以纯文本方式定义响应内容 MIME 类型。
   @Context: 使用该注释注入上下文对象,比如 Request、Response、UriInfo、ServletContext 等。 
   @Path("{contact}"):这是 @Path 注释,与根路径 “/contacts” 结合形成子资源的 URI。 
   @PathParam("contact"):该注释将参数注入方法参数的路径,在本例中就是联系人 id。其他可用的注释有 @FormParam、@QueryParam 等。 
   @Produces:响应支持多个 MIME 类型。在本例和上一个示例中,APPLICATION/XML 将是默认的 MIME 类型。

*/
	@GET
	@Path("/send/{from}/{to}/{subject}/{content}/{password}")
	@Produces({MediaType.TEXT_XML})
	public void sendMail(@PathParam("from")String from,@PathParam("to")String to, 
			@PathParam("subject")String subject, @PathParam("content")String content, @PathParam("password")String password ) {
		// TODO Auto-generated method stub
		System.out.println("execute");
		
		Mail mail = new Mail(from, to, subject, content, password);
		Sender sender = new Sender();
		mail.addObserver(sender);
		mail.sendMail();
	}
	
	@GET
	@Path("/test{id}")
	@Produces({MediaType.TEXT_XML})
	public void test(@PathParam("id")int id){
		System.out.println("test****" + id);
	}
	
	
	@POST
        @Path("/sendByPost")
        @Produces({MediaType.TEXT_XML})
        public String sendMailByPost(@QueryParam("from")String from,@QueryParam("to")String to, 
            @QueryParam("subject")String subject, @QueryParam("content")String content ) {
        // TODO Auto-generated method stub
        System.out.println("execute");
        
        Mail mail = new Mail(to, subject, content);
        Sender sender = new Sender();
        mail.setSender(sender);
        return mail.sendMail();
    }

}
3. spring配置文件:beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xmlns:jaxrs="http://cxf.apache.org/jaxrs"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
	http://cxf.apache.org/jaxrs
	http://cxf.apache.org/schemas/jaxrs.xsd">

	<!-- 此处为对外发布的服务的类-->
	<bean id="mail" class="edu.ncut.view.impl.MailServiceImpl"/>
        <!--address 为服务的地址-->
     <jaxrs:server id="restServiceContainer" address="/mailService">
		<jaxrs:serviceBeans>
			<ref bean="mail" />
		</jaxrs:serviceBeans>
		<jaxrs:extensionMappings>
			<entry key="json" value="application/json" />
			<entry key="xml" value="application/xml" />
		</jaxrs:extensionMappings>
		<jaxrs:languageMappings>
			<entry key="en" value="en-gb" />
		</jaxrs:languageMappings>
	</jaxrs:server>

</beans>
注意:可能有的文章说明在beans.xml中加了这些内容:
<import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-http.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />



但是在本例中发现,以上三句内容不需要。


4. 配置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"
	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>RestStyleMailServer</display-name>

<!-- Spring 配置 -->
  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>

    </listener>
    
    
    <!-- cxf配置 -->
	<servlet>
		<servlet-name>restStyleMailServer</servlet-name>
		<!-- <servlet-class>edu.ncut.listener.NonSpringServlet</servlet-class> -->
		 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>restStyleMailServer</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

<!-- 	<session-config>
		<session-timeout>60</session-timeout>
	</session-config> -->
</web-app>
配置完成后启动tomcat发布。

http://localhost:8080/RESTStyleMailServer/这样可查看是否成功

如果出现上图的内容,表示成功。


测试test方法,http://localhost:8080/RESTStyleMailServer/mailService/impl/test1.会在控制台打印内容


你可能感兴趣的:(cxf+spring+tomcat 发布RESTful类型的服务)