WebService netbeans glassfish

首先安装NetBeans,jdk1.7 glassfish3.1.1.2 安装完成之后配置数据源

首先配置Jdbc连接池-->新建-->输入名字和资源类型-->可将其余属性删除只添加 url user password

完成之后可以ping一下测试是否成功

配置JDBC资源-->新建-->名字和选择连接池

简单的数据源便配置完成

 

netbeans -->新建项目-->J2EE-->EJB模块(Ejb项目建立成功)

在配置文件(setup)添加数据源配置文件 persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="uappPU" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>jdbc/uapp</jta-data-source> <!-- 此名为glassfish数据源的jdbc名字相同-->
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

实体类

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.entity;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;

import javax.xml.bind.annotation.XmlRootElement;


/**
 *
 * @author song
 */
@Entity
@Table(name = "club")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Club.findById",query = "SELECT a FROM Club a WHERE a.clubId = :id"),
    @NamedQuery(name = "Club.findByName",query = "SELECT a FROM Club a WHERE a.clubName LIKE :clubName"),
    @NamedQuery(name = "Club.delById",query = "DELETE FROM Club a where a.clubId = :id")
})
public class Club implements Serializable {
    private static final long serialVersionUID = 1L;
   
    private Integer clubId;
  
    private String clubDescription;
    
    private String clubName;
   
    private String contactName;
    
    private String contactTel;
   
    private String picUrl;

    private List<UserClub> userClubList;
    public Club() {
    }

    public Club(Integer clubId) {
        this.clubId = clubId;
    }
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "club_id")
    public Integer getClubId() {
        return clubId;
    }

    public void setClubId(Integer clubId) {
        this.clubId = clubId;
    }
    
    @Lob
    @Size(max = 2147483647)
    @Column(name = "club_description")
    public String getClubDescription() {
        return clubDescription;
    }

    public void setClubDescription(String clubDescription) {
        this.clubDescription = clubDescription;
    }
    
    @Size(max = 100)
    @Column(name = "club_name")
    public String getClubName() {
        return clubName;
    }

    public void setClubName(String clubName) {
        this.clubName = clubName;
    }
    @Size(max = 100)
    @Column(name = "contact_name")
    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }
    @Size(max = 20)
    @Column(name = "contact_tel")
    public String getContactTel() {
        return contactTel;
    }

    public void setContactTel(String contactTel) {
        this.contactTel = contactTel;
    }
    @Lob
    @Size(max = 2147483647)
    @Column(name = "pic_url")
    public String getPicUrl() {
        return picUrl;
    }
    
    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }
    @OneToMany(fetch = FetchType.LAZY , mappedBy = "club" )
    public List<UserClub> getUserClubList() {
        return userClubList;
    }

    public void setUserClubList(List<UserClub> userClubList) {
        this.userClubList = userClubList;
    }
    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (clubId != null ? clubId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won‘t work in the case the id fields are not set
        if (!(object instanceof Club)) {
            return false;
        }
        Club other = (Club) object;
        if ((this.clubId == null && other.clubId != null) || (this.clubId != null && !this.clubId.equals(other.clubId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.haiersoft.uapp.entity.Club[ clubId=" + clubId + " ]";
    }
    
}

数据库操作类

package com.dao;

import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author chenlitao
 */
public abstract class AbstractDao<T> {
    private Class<T> entityClass;

    public AbstractDao(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0] + 1);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao;

import com.entity.Club;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
/**
 *
 * @author song
 */
@Stateless
public class ClubDao extends  AbstractDao<Club>{
    @PersistenceContext(unitName = "uappPU")
    private EntityManager em;
    
    public ClubDao(){
        super(Club.class);
    }
    @Override
    public EntityManager getEntityManager(){
        return em;
    }
    public Club findById(int id){
        Query query = getEntityManager().createNamedQuery("Club.findById", Club.class);
        query.setParameter("id", id);
        List<Club> resultList = query.getResultList();
        if(resultList == null || resultList.isEmpty()){
            return new Club(-1);
        }else{
            return resultList.get(0);
        }
    }
    public List<Club> findByName(String clubName){
        Query query = getEntityManager().createNamedQuery("Club.findByName",Club.class);
        query.setParameter("clubName","%"+ clubName +"%");
        List<Club> resultList = query.getResultList();
        if(resultList == null || resultList.isEmpty()){
            return null;
        }else{
            return resultList;
        }
    }
   
}

pojo类

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pojo;

import com.entity.Club;

/**
 *
 * @author song
 */
public class ClubPojo {
     private int clubId;
    private String clubName;
    private String clubDescription;
    private String picUrl;
    private String contactName;
    private String contactTel;
    public ClubPojo(){
        
    }
    public ClubPojo(Club club){
        this.clubId  = club.getClubId();
        this.clubName = club.getClubName();
        this.clubDescription = club.getClubDescription();
        this.picUrl = club.getPicUrl();
        this.contactName = club.getContactName();
        this.contactTel = club.getContactTel();
    }
    public int getClubId() {
        return clubId;
    }

    public void setClubId(int clubId) {
        this.clubId = clubId;
    }

    public String getClubName() {
        return clubName;
    }

    public void setClubName(String clubName) {
        this.clubName = clubName;
    }

    public String getClubDescription() {
        return clubDescription;
    }

    public void setClubDescription(String clubDescription) {
        this.clubDescription = clubDescription;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }

    public String getContactTel() {
        return contactTel;
    }

    public void setContactTel(String contactTel) {
        this.contactTel = contactTel;
    }
    
    
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pojo;

import com.entity.Club;

/**
 *
 * @author song
 */
public class ClubResult {
    private String state;
    private ClubPojo club;
    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public ClubPojo getClub() {
        return club;
    }

    public void setClub(ClubPojo club) {
        this.club = club;
    }
    
}
package com.pojo;

/**
 *
 * @author chenlitao
 */
public class Result {

    private String state;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pojo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author yjd
 */
public class ResultSet<T> implements Serializable {

    /**
     * 状态码
     */
    private String state;
    /**
     * 泛型集合
     */
    private List<T> result = new ArrayList<T>();

    /**
     * 总页数
     */
    private int totalPage = 0;
    /**
     * 总条数
     */
    private int totalCount = 0;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public List<T> getResult() {
        return result;
    }

    public void setResult(List<T> result) {
        this.result = result;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

}

service类

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.service;

import com.dao.ClubDao;
import com.dao.UserClubDao;
import com.entity.Club;
import com.entity.UserClub;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import java.util.ArrayList;
import javax.ejb.EJB;
import java.util.List;
/**
 *
 * @author song
 */
@Stateless
@LocalBean
public class ClubService {
    @EJB 
    private ClubDao clubDao;
    @EJB
    private UserClubDao userClubDao;
  

    public ClubService() {
    }
    
    public Club findById(int clubId){
        return clubDao.findById(clubId);
    }
    
    public List<Club> findByClubName(String clubName){
        List<Club> list = clubDao.findByName(clubName);
        if(list == null || list.isEmpty()){
            return new ArrayList<Club>();
        }else{
            return list;
        }
    }
    public  void addClub(Club club){
        clubDao.create(club);
    }
    
    public void edit(Club club){
        clubDao.edit(club);
    }
    public List<Club> findAll(){
        return clubDao.findAll();
    }
    
     public List<UserClub> findByClubId(int clubId){
        return userClubDao.findByClubId(clubId);
    }
    
    public List<UserClub> findByUserName(String userName){
        return userClubDao.findByUserName(userName);
    }
    
    public boolean delByClubIdAndUserName(int clubId,String userName){
        return userClubDao.delByClubIdAndUserName(clubId, userName);
    }
    public void joinClub(UserClub userClub){
        userClubDao.create(userClub);
    }
    public UserClub findByClubIdAndUserName(int clubId,String userName){
        return userClubDao.findByClubIdAndUserName(clubId, userName);
    }
}

facade类,提供外部调用接口

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.facade;

import com.entity.Club;
import com.entity.UserClub;
import com.pojo.ClubPojo;
import com.pojo.ClubResult;
import com.pojo.Result;
import com.pojo.ResultSet;
import com.pojo.UserClubPojo;
import com.pojo.UserClubResult;
import com.service.ClubService;
import java.util.ArrayList;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import javax.jws.WebParam;
import java.util.List;
/**
 *
 * @author song
 */
@Stateless
@WebService(serviceName = "club",name = "ClubFacade",targetNamespace =  "http://com.haiersoft.uapp.ws.facade.ClubFacade")
@SOAPBinding(style = SOAPBinding.Style.RPC,use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class ClubFacade {
    @EJB
    private ClubService clubService;
    
    /**
     * 根据俱乐部Id查询
     * @param id
     * @return 
     */
    @WebMethod(action = "findByClub0",operationName = "findByClubId")
    @WebResult(name = "result")
    public ClubResult findByClubId(@WebParam(name = "clubId") int clubId){
           ClubResult resultClub = new ClubResult();
           try{
               Club club = clubService.findById(clubId);
               if(club.getClubId() != -1){
                      resultClub.setState("200");
                      resultClub.setClub(new ClubPojo(club));
                }else{
                   resultClub.setState("none");
               }
               return resultClub;
           }catch(Exception e){
               resultClub.setState("900");
               return resultClub;
           }
    }
    
    /**
     * 创建俱乐部信息
     * @param clubPojo
     * @return 
     */
    @WebMethod(action = "createClub",operationName = "createClub")
    @WebResult(name = "result")
    public Result createClub(@WebParam(name="clubPojo") ClubPojo clubPojo){
         Club club = proverClub(clubPojo);
         Result result = new Result();
        
           try{
               clubService.addClub(club);
               result.setState("200");
               return result;
           }catch(Exception e){
               System.out.println(e.toString());
               result.setState("900");
               return result;
           }
    }
    
    /**
     * 根据俱乐部名称查询俱乐部
     * @param clubName
     * @return 
     */
    @WebMethod(action = "findByClubName",operationName = "findByClubName")
    @WebResult(name = "result")
    public ResultSet findByClubName(@WebParam(name="clubName") String clubName){
        ResultSet<ClubPojo> clubResultSet = new ResultSet<ClubPojo>();
        try{
            List<Club> listClub = clubService.findByClubName(clubName);
            if(listClub.size() <= 1){
                  clubResultSet.setState("200");
            }else{
                clubResultSet.setState("201");
            }
            List<ClubPojo> listClubPojos = new ArrayList<ClubPojo>();
            for(Club club:listClub){
                listClubPojos.add(new ClubPojo(club));
            }
          clubResultSet.setResult(listClubPojos);
          clubResultSet.setTotalCount(listClub.size());
        }catch(Exception e){
            clubResultSet.setState("error");
        }
        return clubResultSet;
    }
    /**
     * 编辑俱乐部信息
     * @param clubPojo
     * @return 
     */
    @WebMethod(action = "editClub",operationName = "editClub")
    @WebResult(name = "result")
    public Result editClub(@WebParam(name="clubPojo") ClubPojo clubPojo){
         Club club = proverClub(clubPojo);
         club.setClubId(clubPojo.getClubId());
         Result result = new Result();
        
           try{
               clubService.edit(club);
               result.setState("200");
               return result;
           }catch(Exception e){
               System.out.println(e.toString());
               result.setState("900");
               return result;
           }
    }
    
    /**
     * 查询所有的俱乐部信息
     * @return 
     */
    @WebMethod(action = "findAllClub",operationName = "findAllClub")
    @WebResult(name="result")
    public ResultSet findAllClub(){
        ResultSet<ClubPojo> result = new ResultSet<ClubPojo>();
        List<Club> clubList = clubService.findAll();
        if(clubList.size() <= 1){
            result.setState("200");
        }else{
            result.setState("201");
        }
         List<ClubPojo> listClubPojos = new ArrayList<ClubPojo>();
         for(Club club:clubList){
               listClubPojos.add(new ClubPojo(club));
         }
        result.setResult(listClubPojos);
        return result;
    }
    /**
     * 将俱乐部pojo类转化为实体类
     * @param clubPojo
     * @return 
     */
    private Club proverClub(ClubPojo clubPojo){
        if(clubPojo == null ){
            return null;
        }
        Club club = new Club();
        club.setClubName(clubPojo.getClubName());
        club.setClubDescription(clubPojo.getClubDescription());
        club.setContactName(clubPojo.getContactName());
        club.setContactTel(clubPojo.getContactTel());
        club.setPicUrl(clubPojo.getPicUrl());
        return club;
    }
    
   
    /**
     * 加入俱乐部
     * @param clubId
     * @param userId
     * @param userName
     * @param mobilePhone
     * @return 
     */
    @WebMethod(action = "joinClub",operationName = "joinClub")
    @WebResult(name="result")
    public Result joinClub(@WebParam(name = "clubId") int clubId,@WebParam(name = "userId")String userId,@WebParam(name = "userName")String userName ,@WebParam(name = "mobilePhone")String mobilePhone){
        Result result = new Result();
      
        UserClub userClub = new UserClub();
        
        userClub.setClub(new Club(clubId));
        userClub.setUserId(userId);
        userClub.setUserName(userName);
        userClub.setMobilePhone(mobilePhone);
        Date time = new Date();
        userClub.setJoinTime( time);
        try{
            clubService.joinClub(userClub);
            result.setState("200");
        }catch(Exception e){
            result.setState("error");
            System.out.println(e);
        }
        return result;
    }
    /**
     * 根据俱乐部Id查询俱乐部的报名人数
     * @param clubId
     * @return 
     */
    @WebMethod(action = "findUserByClubId",operationName = "findUserByClubId")
    @WebResult(name = "result")
    public ResultSet findUserByClubId(@WebParam(name  ="clubId") int clubId){
        ResultSet<UserClubPojo> result = new  ResultSet<UserClubPojo>();
        try{
            List<UserClub> userClubList = clubService.findByClubId(clubId);
            if(userClubList.size() <= 1){
                result.setState("200");
            }else{
                result.setState("201");
            }
            List<UserClubPojo> listClubPojos = new ArrayList<UserClubPojo>();
            for(UserClub userClub:userClubList){
               listClubPojos.add(new UserClubPojo(userClub));
            }
            result.setResult(listClubPojos);
            result.setTotalCount(userClubList.size());
        }catch(Exception e){
            result.setState("error");
        }
        return result;
    }
    /**
     * 根据用户名查询报名俱乐部
     * @param userName
     * @return 
     */
    @WebMethod(action = "findByUserName",operationName = "findByUserName")
    @WebResult(name = "result")
    public ResultSet findByUserName(@WebParam(name="userName")String userName){
        ResultSet<UserClubPojo> result = new  ResultSet<UserClubPojo>();
        try{
           List<UserClub> userClubList = clubService.findByUserName(userName);
            if(userClubList.size() <= 1){
                result.setState("200");
            }else{
                result.setState("201");
            }
            List<UserClubPojo> listClubPojos = new ArrayList<UserClubPojo>();
            for(UserClub userClub:userClubList){
               listClubPojos.add(new UserClubPojo(userClub));
            }
          result.setResult(listClubPojos);
          result.setTotalCount(userClubList.size());
        }catch(Exception e){
            result.setState("error");
        }
        return result;
    }
    /**
     * 根据俱乐部Id和用户名查询是否有报名信息
     * @param clubId
     * @param userName
     * @return 
     */
    @WebMethod(action = "findByClubIdAndUserName",operationName = "findByClubIdAndUserName")
    @WebResult(name = "result")
    public UserClubResult findByClubIdAndUserName(@WebParam(name = "clubId")int clubId,@WebParam(name = "userName")String userName){
        UserClubResult result = new  UserClubResult();
        try{
             UserClub userClub = clubService.findByClubIdAndUserName(clubId, userName);
             if(userClub != null){
                result.setState("200");
                result.setUserClub(new UserClubPojo(userClub));
             }else{
                 result.setState("none");
             }
          
        }catch(Exception e){
            result.setState("error");
        }
        return result;
    }
    /**
     * 根据Id和用户名删除报名信息
     * @param clubId
     * @param userName
     * @return 
     */
    @WebMethod(action = "delByClubIdAndUserName",operationName = "delByClubIdAndUserName")
    @WebResult(name = "result")
    public Result delByClubIdAndUserName(@WebParam(name = "clubId")int clubId,@WebParam(name = "userName")String userName){
        Result result = new Result();
        try{
            boolean flag = clubService.delByClubIdAndUserName(clubId, userName);
            if(flag){
                result.setState("200");
            }else{
                result.setState("none");
            }
        }catch(Exception e){
            result.setState("error");
        }
        return result;
    }
}

一个简单的WebService就完成了

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。