Struts 2 and business objects

2019-06-13 20:32发布

In a Struts 2 class where http get params are auto fetched by field variables. While there were repeated such class fields like userId,groupId, etc in many classes, I decided to make one business object class RequestParams in each class and put all the field there.

Then all my class will have just the RequestParams rp; with getRp(); and setRp(); the rp class will have the userId with getters / setters and all other fields.

Now I see I have to replace. e.g userId with getRp().getUserId(); at line 34 Now the code is looking ugly.

With this: messageId = ChatDao.saveMessage(userId,groupId , message);

would look like

rp.setMessageId(  ChatDao.saveMessage(rp.getUserId(), rp.getGroupId(), rp.getMessag()   )   );

what is a better way of doing such things?

public class SendMessageOrStartChatAction extends BaseActoinSupport{


    private static final long serialVersionUID = 1L;
    private int userId;
    private int groupType;
    private int groupId;
    private String groupTitle;
    private String groupMemberIds;
    private int randomCode;
    private String message;
    private int messageId; //internal class ues


    @Override
    /** boo */
    protected void doExecute() throws IOException {



        //check if it had random code in db, (msg already saved in db)
        if(ChatDao.randomCodeExists(randomCode)){
            messageId = ChatDao.getMessageIdThatMatchesRandomCode(randomCode);  
            write(messageId);

        }else{
            if(groupId <= 0){
            //create group 
                groupId = ChatDao.createChatGroup(userId, groupTitle, groupType);
                String[] memberIdsArray = groupMemberIds.split("=="); 
                ChatDao.addUsersToGroup(groupId, memberIdsArray);
            }
            //save message
            messageId = ChatDao.saveMessage(userId,groupId , message);
            // queued: may be put this in last viewed messages here. may be.
            write(messageId);       
        }

    }

}

1条回答
祖国的老花朵
2楼-- · 2019-06-13 21:13

Nothing wrong with this approach, if you aggregate a class and want to access its properties then public accessors are appropriate to you and you could also access them via OGNL. The action is on top of the valueStack, so expression will look much simpler "rp.userId" for example. Anyway there's no need to pass all params to the method, you can use a simplified method signature

ChatDao.saveMessage(rp);  

and inside the method access those parameters.

查看更多
登录 后发表回答