使用EJB的java ee JAX-RS中的会话/状态?

时间:2015-09-12 18:58:20

标签: session java-ee ejb jax-rs jaas

假设我们希望在客户端浏览器端使用XHR调用完全实现基于休息的购物车,并在服务器端使用java-ee实现休息服务。我们使用JAAS来保证安全。

客户端将登录,购物,关闭浏览器,稍后返回继续购物,记住他的状态,而无需再次登录。

他的状态究竟是如何保留的?

下面是购物车的名义有状态bean,必须将其注入REST资源,该资源将成为客户端和业务逻辑之间的接口:

@Stateful
public class ClientCart{

    @Resource private SessionContext ctx;
    private List<String> items; //contains a list of products

    @PostConstruct
    private void createCart(){
        /*
        init stuff like db connection...
        get name of user with ctx.getCallerPrincipa()
        check if user had items in cart in the db
        if there were items, create a list: items = new LinkedList()<>;
        else: populate items with whatever was in db
        */
    }

    public List getItems(){ /* return the cart... */ }

    public void addItem(String item){ /*do a items.add(item); */}

    @PrePassivate
    private void maintenanceOnSleep(){
        /*
        Called when the server decided to suspend this instance due to long time of inactivity - when user close browser, etc...
        Does clean up tasks like closing a db connection
        */
    }

    @PostActivate
    private void maintenanceOnActivate(){
        /*
        Opposite of @PrePassivete - open the db connection...
        */
    }

    @Remove
    public void logout(){ /* nothing in here... */ }

    @PreDestroy
    public void cleanUP(){
        /* called when error happens or logout() is explicitly called, will send purge instance vars like items to db and close connections.
    }

}

现在我如何制作其余资源?由于rest是请求范围的,我不能注入有状态的bean ...

@Path("/shop")
public class ShoppingCart{

    @GET
    @Path("/login/{user}/{pass}
    public void (@Context HttpServletRequest rq, @PathParam("user") String u, @PathParam("pass") String p {

        /*
        we do programmatic logins with rq.login(u, p); ... and then what happens? :) 
        */

    }

}

0 个答案:

没有答案