HttpServletRequest injection on RequestScoped bean CDI

I am looking for a way to inject a custom class @RequestScopedinto my JAX-RS endpoint @Stateless:

I want every time an application receives a request, my custom class is injected into my JAX-RS endpoint.

Custom class:

@RequestScoped
public class CurrentTransaction {

    private String user;
    private String token;

    @PersistenceContext(name="mysql")
    protected EntityManager em;

    @Inject HttpServletRequest request;

    public CurrentTransaction() {
        this.user = request.getHeader("user");
        this.token = request.getHeader("token");
    }

    //getters and setters ...
}

So, I declare my class CurrentTransactionas @RequestScopedfor initialization every time a request is received. To do this, I need to access HttpServletResquestto get the header options.

JAX-RS Endpoint:

@Stateless
@Path("/areas")
public class AreasEndpoint {

   @PersistenceContext(unitName = "mysql")
   protected EntityManager em;

   @Inject
   protected CurrentTransaction current_user_service;

    @POST
    @Path("postman")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Authentication
    public Response create(AreaRequest request) {

        if (this.current_user_service.getUser() == null) {
            System.out.println("Go!!!");
            return Response.status(Status.FORBIDDEN).build();
        } else {
            System.out.println("---- user: " + this.current_user_service.getUser());
            System.out.println("---- token: " + this.current_user_service.getToken());
        }
    }

    // ...
}

CDI arrives to execute the class constructor CurrentTransaction. However, the request field is HttpServletRequestnot initialized (entered).

What am I doing wrong?

+3
1

- , : CDI :

- , , :

@Inject HttpServletRequest request;

public CurrentTransaction() {
    // field injection has not yet taken place here
}

@PostConstruct
public void init() {
    // the injected request is now available
    this.user = request.getHeader("user");
    this.token = request.getHeader("token");
}
+1

Source: https://habr.com/ru/post/1610576/


All Articles