easy-chat之好友列表

博文说明

本篇属于Spring+Hibernate+Struts开发easy-chat项目系列的第二篇,第一篇是ssh开发之登录实现,本篇主要记录好友列表、添加好友、删除好友的实现方法,本篇博文也涉及到了jsp与Action进行数据交互的方法,本节中用到的是Struts的标签库。

先放一张图,因为这个项目还没做好,所以下图仅供参考

添加好友的按钮,默认添加id为2的用户
这里写图片描述

左侧显示的就是添加成功的好友列表,右侧UI未完成
这里写图片描述


准备工作

先来梳理一下要做的工作:

  1. 列出我的所有好友
  2. 添加指定好友
  3. 删除指定好友

对于第一个任务:
用户登录,保存用户登录信息,返回一个redirectAction类型的结果
redirectAction表示将重定向到另一个Action
登录成功后,重定向到获取所有好友的Action,该操作完成后返回index.jsp

对于第二个任务:
向添加好友的Action发起请求,传入待添加好友的用户ID,该操作完成后返回index.jsp

对于第三个任务:
向删除好友的Action发起请求,传入待删除好友的用户ID,该操作完成后返回index.jsp

以上是大致流程,实现方法接下来介绍


基础设施

基本的DAO组件和业务逻辑组件和上节相同,和上节相同的代码这里不再说,如果不明白,请看本节首部博文说明中的连接。不同的是:

增加一些类
1. FriendAction:处理好友相关的用户请求
2. FriendDao:好友DAO接口
3. FriendDaoImpl:好友DAO接口实现类
4. Friend:好友实体持久化类
5. FriendService:好友业务逻辑组件接口
6. FriendServiceImpl:好友业务逻辑接口实现类


修改了一些类
1. 用户业务逻辑接口中加了一个根据ID查找User的方法

//UserSerive.java片段
public User findById(Integer id);

2.User实体中添加了与好友的关联关系,但他不控制关联关系

    @OneToMany(targetEntity=Friend.class,mappedBy="own")
    private Set<Friend> friends=new HashSet<Friend>();

    public void setFriends(Set<Friend> friends) {
        this.friends = friends;
    }

    public Set<Friend> getFriends() {
        return friends;
    }

DAO组件

这两个类没有难度,看一下就可以了。

package com.easychat.dao;

import com.easychat.entity.Friend;
//好友DAO接口
public interface FriendDao extends BaseDao<Friend>{

}
package com.easychat.daoImpl;

import com.easychat.dao.FriendDao;
import com.easychat.entity.Friend;
//好友DAO接口实现类
public class FriendDaoImpl extends BaseDaoImpl<Friend> implements FriendDao{

}

业务逻辑组件

业务逻辑组件的实现依靠于DAO组件,Action调用业务逻辑组件处理用户请求,业务逻辑组件需要调用DAO组件来完成底层数据库相关操作。

先看下业务逻辑接口

/**
 * 好友业务逻辑接口
 * @author Administrator
 *
 */
public interface FriendService {

    /**
     *查找用户user的好友列表
     * @param friend
     * @return
     */
    public List<Friend> find(User user);

    /**
     * 删除好友
     * @param friendId
     * @return
     */
    public boolean delete(Serializable friendId);

    /**
     * 添加好友
     * @param user
     * @param friend
     * @return
     */
    public Serializable add(User owner,User userFriend);

    /**
     * 判断两者是否为好友关系
     * @param owner
     * @param other
     * @return
     */
    public boolean isFriend(User owner,User other);
}

接下来提供一个接口的实现类
查找的实现是使用hql语句查询的,dao基类中本来就有删除实体的方法,所以删除好友可以直接用该方法实现。
添加用户怎么做呢?
首先:传入两个用户:自己、待添加的User
然后:把待添加的User、当前时间、所有者等信息封装为Friend对象
最后:使用friendDao保存该实体
代码如下:

public class FriendServiceImpl implements FriendService {

    private FriendDao friendDao;

    public void setFriendDao(FriendDao friendDao) {
        this.friendDao = friendDao;
    }

    @Override
    public List<Friend> find(User user) {
        return friendDao.find("select f from Friend f where f.own=?", user);
    }

    @Override
    public boolean delete(Serializable friendId) {
        friendDao.delete(Friend.class, friendId);
        return true;
    }

    @Override
    public Serializable add(User owner, User userFriend) {
        //日期格式化
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

        //将用户封装为Friend
        Friend friend=new Friend();
        friend.setFriend(userFriend);
        friend.setOwn(owner);
        friend.setTime(sdf.format(new Date()));

        return friendDao.save(friend);
    }

    @Override
    public boolean isFriend(User owner, User other) {
        List list=friendDao.find("select f from Friend f where f.own=? and f.friend=?",owner,other);
        return list.size()==0?false:true;
    }

}

以下是用户业务逻辑组件新增的一个方法的实现

public class UserServiceImpl implements UserService{

    //省略和上节相同的代码

    @Override
    public User findById(Integer id) {
        List<User> list=userDao.find("select u from User u where u.id=?",id);
        return list.size()==0?null:list.get(0);
    }

}

Action实现

Action的作用就是组合业务逻辑组件完成用户请求,看下列代码,以下Action可以处理用户的三个请求,代码如下:

public class FriendAction extends ActionSupport {

    // 好友业务逻辑组件
    private FriendService friendService;

    // 用户业务逻辑组件
    private UserService userService;

    // 保存结果
    private List<Friend> friends;

    // 参数:ID
    private Integer id;

    //设置结果
    public void setFriends(List<Friend> friends) {
        this.friends = friends;
    }

    public List<Friend> getFriends() {
        return friends;
    }

    //注入业务逻辑组件
    public void setFriendService(FriendService friendService) {
        this.friendService = friendService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //注入参数
    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    /**
     * 得到好友列表
     * 
     * @return
     */
    public String listFriends() {
        // 获取用户信息
        ActionContext ctx = ActionContext.getContext();
        String tel = ctx.getSession().get(Constants.SESSION_USERNAME).toString();
        String password = ctx.getSession().get(Constants.SESSION_PASSWORD).toString();
        // 查找它的好友
        List<Friend> friends = friendService.find(userService.find(tel, password));
        setFriends(friends);
        return SUCCESS;
    }

    /**
     * 添加好友
     * @return
     */
    public String addFriend(){
        //获取用户信息
        ActionContext ctx=ActionContext.getContext();
        String tel=ctx.getSession().get(Constants.SESSION_USERNAME).toString();
        String password=ctx.getSession().get(Constants.SESSION_PASSWORD).toString();

        //获取到用户对象
        User owner=userService.find(tel, password);
        User userFriend=userService.findById(id);

        if(userFriend==null) addActionError("该好友不存在!");

        //添加
        if(!friendService.isFriend(owner,userFriend)) friendService.add(owner, userFriend);
        else addActionError("该用户已是你的好友!");
        return "addFriend_success";
    }

    /**
     * 删除好友
     * @return
     */
    public String deleteFriend(){
        friendService.delete(id);
        return "deleteFriend_success";
    }


    @Override
    public String execute() throws Exception {
        ActionContext ctx = ActionContext.getContext();
        String tel = ctx.getSession().get(Constants.SESSION_USERNAME).toString();
        String password = ctx.getSession().get(Constants.SESSION_PASSWORD).toString();
        if (tel == null || tel.equals("") || password == null || password.equals(""))
            return LOGIN;
        return SUCCESS;
    }
}

Friend实体

@Entity
@Table(name="friends_inf")
public class Friend {

    @Id @Column(name="friends_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    //是谁的好友,即好友的所有者
    @ManyToOne(targetEntity=User.class)
    @JoinColumn(name="friends_own",referencedColumnName="user_id",nullable=false)
    private User own;

    //好友是谁
    @ManyToOne(targetEntity=User.class)
    @JoinColumn(name="friends_friend",referencedColumnName="user_id",nullable=false)
    private User friend;

    @Column(name="friends_time")
    private String time;

    //省略所有变量的setter、getter方法

    public Friend(User own, User friend, String time) {
        super();
        this.own = own;
        this.friend = friend;
        this.time = time;
    }

    public Friend() {
        super();
    }


}

配置

各个组件都实现了,还需要在spring配置文件中配置依赖Bean以及Bean之间的关系,配置方法如上篇博文,这里不再细说。


jsp与Action交互问题

这样的问题也困扰着我,解决方案是这样的:
首先在Action定义变量并添加setter、getter方法,在上例中代码片段如下:

    // 保存结果
    private List<Friend> friends;

    //设置结果
    public void setFriends(List<Friend> friends) {
        this.friends = friends;
    }

    public List<Friend> getFriends() {
        return friends;
    }

在jsp中这样获取:

<ul class="ul">
    <s:iterator value="friends">
        <li>
            <div>
                <div>
                    <img src="resource/img/touxiang.png" />
                </div>
                <span><s:property value="friend.username" /></span>
            </div>
        </li>
    </s:iterator>
</ul>

重要的以下几行,使用了Struts的标签库,迭代标签的value值friends就是FriendAction刚起的那个变量名字,迭代标签内部friend.username表示该值为friends集合的每个元素(每个元素都是Friend对象)的friend属性(该属性是User类型的)的username值,输出的也就是所有好友的用户名

<s:iterator value="friends">
    <s:property value="friend.username" />
</s:iterator>

以下是请求的方式

<a href="friendAction!addFriend?id=2">添加好友</a>
<a href="friendAction!deleteFriend?id=2">删除好友</a>
<a href="friendAction!listFriends">我的好友</a>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值