Criando uma lista na sessão com DWR – Parte 3

Na parte 3 do nosso artigo vamos ver que tipos de métodos iremos criar no nosso FacadeAjaxSession explicado no artigo anterior.

Agora veremos os trechos dos novos métodos:

Método para adicionar um objeto na sessão:

public void addMapSession(BeanSession beanSession){
Session session = new SessionFacade();//01
Map<String, BeanSession> sessionMap = null;//02

if(session.getAttribute("sessionMap") != null){ //03
sessionMap = (Map) session.getAttribute("sessionMap");//04
}else{
sessionMap = new HashMap<String, BeanSession>();//05
}
String keyMap = beanSession.getId() + "_" +  beanSession.getName();//06

beanSession.setKeyMap(keyMap); //07

sessionMap.put(keyMap, beanSession); //08

session.setAttribute("sessionMap", sessionMap); //09
}

Listagem 03: Método que adiciona em um atributo da sessão o objeto passado como parâmetro.

Na listagem 03 vimos o método addMapSession() que espera como parâmetro um BeanSession(ver listagem 01), veja baixo:

01:Criamos o objeto session a partir de nossa classe SessionFacade;
02:Criamos um Map(sessionMap);
03: Recuperamos da sessão o atributo utilizado, e verificamos se o mesmo já existe;
04:Caso o Atributo exista(linha 03) pegamos o valor desse atributo e adicionamos no Map(sessionMap);
05:Caso o atributo não exista inicializamos o sessionMap;
06:Criamos uma variável que servirá como identificador do objeto, que será utilizado no lado JavaScript para identificar o objeto que o usuário está clicando. OS: Como não estou utilizando dados de um banco, tive que fazer essa “adaptação” para simular o id. O que eu fiz foi nada mais que garantir que o objeto que estou inserindo neste momento não terá o mesmo id do próximo;
07:Adiciono esse keyMap(identifica o mapa, linha 06) no meu BeanSession;
08:Adiciono no sessionMap a chave do meu mapa(keyMap) e o meu objeto(BeanSession).

Método para listar um objeto na sessão:

public Map listMapSession() throws Throwable {
Session session = new SessionFacade();
Map<String, BeanSession> sessionMap = null;

if (session.getAttribute("sessionMap") != null) {
sessionMap = (Map) session.getAttribute("sessionMap");
} else {
sessionMap = new HashMap<String, BeanSession>();
}

return sessionMap;
}

Listagem 04: Método que retorna um Map da sessão.

Este método dispensa explicação mais detalhada, ele apenas retorna um Map que está salvo em um determinado atributo na sessão.

Método para excluir um objeto da sessão:

public void removeValueMap(BeanSession beanSession) throws Throwable {
Session session = new SessionFacade();
Map sessionMap = null;

if (session.getAttribute("sessionMap") != null) {
sessionMap = (Map) session.getAttribute("sessionMap");
} else {
sessionMap = new HashMap<String, BeanSession>();
}

if (sessionMap.containsKey(beanSession.getKeyMap())) {
sessionMap.remove(beanSession.getKeyMap());
}

session.setAttribute("sessionMap", sessionMap);
}

Listagem 05: Método que exclui o objeto passado como parâmetro da sessão.

Um método também bem simples. Recebe o objeto como parâmetro, recupera o valor da sessão, verifica se existe um objeto no Map através da chave (keyMap), caso exista ele remove o objeto do Map e adiciona novamente o Map na sessão.

São métodos simples e claro precisam de mais alguns requintes, mas, esse não é o objetivo do nosso artigo. Quero apenas exemplificar essa funcionalidade.

No próximo artigo(parte 4) iremos ver a implementação no lado JavaScript.

Abraços

4.297 Comments on “Criando uma lista na sessão com DWR – Parte 3

  1. You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never understand.

    It seems too complicated and very broad for me.
    I’m looking forward for your next post, I will
    try to get the hang of it!

  2. I like what you guys are usually up too. This sort of clever work
    and reporting! Keep up the superb works guys I’ve included
    you guys to my blogroll.

  3. It’s truly a great and useful piece of info.

    I am satisfied that you simply shared this helpful information with us.
    Please stay us up to date like this. Thank you for sharing.

  4. I blog often and I really thank you for your information. This
    great article has really peaked my interest. I am going to book mark your
    blog and keep checking for new information about once per week.
    I opted in for your RSS feed as well.

  5. If a ticket has not but been sold, you are capable
    tto edit the listing price tag or cancel the posting via your ‘My Packers
    Account’.

    Feel free too visit my page: web site

  6. I’ll immediately grab your rss feed as I can’t in finding your email subscription hyperlink or newsletter service.
    Do you’ve any? Please let me realize so that I may just subscribe.
    Thanks.

  7. Great blog you have here but I was wanting to know if
    you knew of any message boards that cover the same topics talked about here?
    I’d really like to be a part of group where I can get
    opinions from other experienced individuals that
    share the same interest. If you have any suggestions, please let me know.
    Bless you!

  8. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is valuable and all. But imagine if you added some great photos or video clips to give your posts more, “pop”!

    Your content is excellent but with pics and clips, this website could undeniably be one of
    the most beneficial in its niche. Good blog!

  9. Have you ever thought about publishing an e-book or guest authoring on other blogs?
    I have a blog centered on the same ideas you discuss and would really like to have you share some stories/information. I know my viewers
    would appreciate your work. If you’re even remotely interested, feel free to shoot me an e mail.

  10. Superb blog you have here but I was curious if you knew of any user discussion forums
    that cover the same topics talked about here? I’d really like to
    be a part of online community where I can get advice from other
    experienced people that share the same interest. If you have any recommendations, please
    let me know. Kudos!

  11. I want to be in a position to make a decent living and have some say about tthe wages
    that I’m earning — even aas a nonregular worker.

    Also visit my webpage; site

  12. I absolutely love your blog and find almost all of your post’s to be just what I’m
    looking for. Would you offer guest writers to write content to suit
    your needs? I wouldn’t mind producing a post or elaborating on a number of the
    subjects you write with regards to here.
    Again, awesome website!

  13. Does your site have a contact page? I’m having problems locating it but, I’d like to shoot you an e-mail.
    I’ve got some ideas for your blog you might be interested in hearing.

    Either way, great blog and I look forward to seeing it grow over time.

  14. I’ve been browsing on-line more than three hours as of
    late, yet I by no means found any attention-grabbing article like yours.
    It is pretty price enough for me. In my opinion, if all site owners and bloggers
    made excellent content as you did, the net will be a lot more useful
    than ever before.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.