Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Newcomers » Newcomers » Dependency injection with @inject(Dependency injection with @inject having problems)
Dependency injection with @inject [message #1842866] Sun, 04 July 2021 03:20 Go to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
I currently have a pagination class, I will share it here:
package net;

public class PageClass {

    String pagination;

    public void setpagination(int maxPage, int cpage, String vfile, String queryvars, String pageName) {

        String pag = "<div class='pagination'>";
        int fpage = 1;
        int page = cpage;
        int limit = 3;

        int pageno = cpage;
        int spage = cpage;
        int lower = spage - 1;
        int upper = spage + 1;
        String self = vfile + "?";
        int khigh = 0;
        int klow = 0;

        if (maxPage > limit) {
            if (pageno > 1) {

                pag = pag + "<li><a href=" + self + pageName + "=" + fpage + queryvars + ">1..</a></li>";
                pag = pag + "<li><a href=" + self + pageName + "=" + (pageno - 1) + queryvars + ">&laquo; </a></li>";
            }

            if (spage == 1) {
                klow = spage;
                khigh = limit;
            }
            if (spage > 1) {
                if (lower < 1) {
                    klow = 1;
                    khigh = limit;
                } else {
                    klow = lower;
                    khigh = upper;
                }

                if (upper > maxPage) {
                    khigh = maxPage;
                    klow = maxPage - (2 * 1);
                }
            }

            for (int i = klow; i <= khigh; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>";
                } else {
                    pag = pag + "<li><a href=" + self + pageName + "=" + i + queryvars + ">" + i + "</a></li>";
                    //pag = pag + "<li><a href=" + self + this->pag->pageName + "=" + i + queryvars + ">" + i + "</a></li>" + "\n";
                }
            }

            if (pageno < maxPage) {
                //pag = pag + "<span>...</span>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'>" + " &raquo;</a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (maxPage) + queryvars + "'>" + " .." + maxPage + "</a></li>";
            }
        } else {
            /*     * * if this is page 1 there is no previous link ** */
            if (pageno != 1) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno - 1) + queryvars + "'>&laquo; </a></li>";
            }
            /*     * * loop over the pages ** */
            for (int i = 1; i <= maxPage; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>" + "";
                } else {
                    pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>";
                }   //pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>" + "\n";
            }
            /*     * * if we are on the last page, we do not need the NEXT link ** */
            if (pageno < maxPage) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'> &raquo; </a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + maxPage + queryvars + "'> last </a></li>";
            }
        }

        pag = pag + "</div>";
        //String tmppag;
        if (maxPage < 2) {
            pag = "";
        }
        this.pagination = pag;

    }

    public String getpagination() {
        return (this.pagination);
    }

}


It works great, but I have to load class like this:
net.PageClass paging = new net.PageClass();


I am trying to use @inject, I have placed all required things in servlet:
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;

and

@MultipartConfig
@WebServlet(
        name = "FindOwnerServlet",
        urlPatterns = {"/FindOwnerServlet"}
)

@RequestScoped
public class FindOwnerServlet extends HttpServlet {
    @Inject net.PageClass paging;



Usage is as follows:
            String vfile = "FindOwnerServlet";
            String queryvars = "&t1=" + t1;
            String pagename = "page";
            paging.setpagination(cPage, pageno, vfile, queryvars, pagename);
            String pagination = paging.getpagination();


Again, all works, but I cannot use @inject, it only works using the "new" keyword.
How can I get the @inject to work?

It's a jakarta 9 web project.
Re: Dependency injection with @inject [message #1842867 is a reply to message #1842866] Sun, 04 July 2021 08:07 Go to previous messageGo to next message
Stephane Talbot is currently offline Stephane TalbotFriend
Messages: 9
Registered: March 2019
Junior Member
The bean must be either be declared in the CDI standard descriptor beans.xml or be annotated with a CDI annotation (@Named, @RequestScoped, etc.).
In the latter case, the standard descriptor,beans.xml, can be an empty file but it must be present to enable bean discovery.

So you should annotate PageClass with some CDI annotation:
@RequestScoped
public class PageClass {
and verify that there is an empty beans.xml file in the WEB-INF or the WEB-INF/classes/META-INF directory (since it's a web application, I would put it in the WEB-INF directory).

A prori the @RequestScoped on the Servlet class is not required.
Re: Dependency injection with @inject [message #1842871 is a reply to message #1842867] Sun, 04 July 2021 17:33 Go to previous messageGo to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
Stephane Thanks for reply. I did all you said, but still not working. No error, but blank pagination. It's as though @inject expects parameters, however I don't pass parameters til later in the servlet like:

paging.setpagination(cPage, pageno, vfile, queryvars, pagename);  // then
String pagination = paging.getpagination();


So I need an instance of the class, but actual usage comes later in the servlet. As said I am loading class like:
net.PageClass paging = new net.PageClass();


However I would like to use the more modern @inject. I even tried moving at inject just before usage. Does @inject not work for a class that has to pass parameters later? Thanks

Edit:

I did a singleton, it works also:

package net;

public class PGClass {

    private static final PGClass instance
            = new PGClass();
    String pagination;

    private PGClass() {

    }

    public static PGClass getInstance() {
        return instance;
    }

    public String getpagination(int maxPage, int cpage, String vfile, String queryvars, String pageName) {
        String pag = "<div class='pagination'>";
       
        etc, same code from first pagination class
        return (this.pagination);
    }
    
}


And usage:

String pagination = net.PGClass.getInstance().getpagination(cPage, pageno, vfile, queryvars, pagename);


Do you think such a class is okay in this use case? I would still like @inject to work however. But I tried for hours with no luck.

[Updated on: Sun, 04 July 2021 18:56]

Report message to a moderator

Re: Dependency injection with @inject [message #1842872 is a reply to message #1842871] Sun, 04 July 2021 19:13 Go to previous messageGo to next message
Nitin Dahyabhai is currently offline Nitin DahyabhaiFriend
Messages: 4086
Registered: July 2009
Senior Member

Can you show us the updated net.PageClass?

Nitin Dahyabhai
Eclipse Web Tools Platform
Re: Dependency injection with @inject [message #1842873 is a reply to message #1842872] Sun, 04 July 2021 20:22 Go to previous messageGo to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
Nitin the the update just has the new name PGClass:

package net;

public class PGClass {

    private static final PGClass instance
            = new PGClass();
    String pagination;

    private PGClass() {

    }

    public static PGClass getInstance() {
        return instance;
    }

    public String getpagination(int maxPage, int cpage, String vfile, String queryvars, String pageName) {
        String pag = "<div class='pagination'>";
        int fpage = 1;
        int page = cpage;
        int limit = 3;

        int pageno = cpage;
        int spage = cpage;
        int lower = spage - 1;
        int upper = spage + 1;
        String self = vfile + "?";
        int khigh = 0;
        int klow = 0;

        if (maxPage > limit) {
            if (pageno > 1) {

                pag = pag + "<li><a href=" + self + pageName + "=" + fpage + queryvars + ">1..</a></li>";
                pag = pag + "<li><a href=" + self + pageName + "=" + (pageno - 1) + queryvars + ">&laquo; </a></li>";
            }

            if (spage == 1) {
                klow = spage;
                khigh = limit;
            }
            if (spage > 1) {
                if (lower < 1) {
                    klow = 1;
                    khigh = limit;
                } else {
                    klow = lower;
                    khigh = upper;
                }

                if (upper > maxPage) {
                    khigh = maxPage;
                    klow = maxPage - (2 * 1);
                }
            }

            for (int i = klow; i <= khigh; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>";
                } else {
                    pag = pag + "<li><a href=" + self + pageName + "=" + i + queryvars + ">" + i + "</a></li>";
                    //pag = pag + "<li><a href=" + self + this->pag->pageName + "=" + i + queryvars + ">" + i + "</a></li>" + "\n";
                }
            }

            if (pageno < maxPage) {
                //pag = pag + "<span>...</span>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'>" + " &raquo;</a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (maxPage) + queryvars + "'>" + " .." + maxPage + "</a></li>";
            }
        } else {
            /*     * * if this is page 1 there is no previous link ** */
            if (pageno != 1) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno - 1) + queryvars + "'>&laquo; </a></li>";
            }
            /*     * * loop over the pages ** */
            for (int i = 1; i <= maxPage; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>" + "";
                } else {
                    pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>";
                }   //pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>" + "\n";
            }
            /*     * * if we are on the last page, we do not need the NEXT link ** */
            if (pageno < maxPage) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'> &raquo; </a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + maxPage + queryvars + "'> last </a></li>";
            }
        }

        pag = pag + "</div>";
        //String tmppag;
        if (maxPage < 2) {
            pag = "";
        }
        this.pagination = pag;

        return (this.pagination);
    }
    
}




Usage in the servlet:

String pagination = net.PGClass.getInstance().getpagination(cPage, pageno, vfile, queryvars, pagename);


And passed to jsp view:
request.setAttribute("mypager", pagination);
// other request
RequestDispatcher dispatcher = request.getRequestDispatcher(displaypage);


And in jsp page:
${mypager}


Also I am still tweaking as needed but it works. I just cannot figure out how to use @inject with the pagination.

[Updated on: Sun, 04 July 2021 20:31]

Report message to a moderator

Re: Dependency injection with @inject [message #1842874 is a reply to message #1842873] Sun, 04 July 2021 20:39 Go to previous messageGo to next message
Stephane Talbot is currently offline Stephane TalbotFriend
Messages: 9
Registered: March 2019
Junior Member
Which Jakarta EE 9 server are you using?

Could you show the code of the Servlet?

[Updated on: Sun, 04 July 2021 20:44]

Report message to a moderator

Re: Dependency injection with @inject [message #1842878 is a reply to message #1842874] Sun, 04 July 2021 23:59 Go to previous messageGo to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
apache-tomcat-10.0.7

The servlet is just standard doGet stuff. But right now it is a mess from experimenting, needs to be cleaned up. I will post tomorrow if I get a chance.
Re: Dependency injection with @inject [message #1842879 is a reply to message #1842878] Mon, 05 July 2021 00:13 Go to previous messageGo to next message
Nitin Dahyabhai is currently offline Nitin DahyabhaiFriend
Messages: 4086
Registered: July 2009
Senior Member

You have not annotated the PGClass class with a scope as directed.

Nitin Dahyabhai
Eclipse Web Tools Platform

[Updated on: Mon, 05 July 2021 00:13]

Report message to a moderator

Re: Dependency injection with @inject [message #1842880 is a reply to message #1842879] Mon, 05 July 2021 02:33 Go to previous messageGo to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
Nitin I did try that: I changed name to PagingClass. And I added a blank bean.xml.

package net;

import jakarta.enterprise.context.RequestScoped;


@RequestScoped
public class PagingClass {

    private static final PagingClass instance
            = new PagingClass();
    String pagination;

    private PagingClass() {

    }

    public static PagingClass getInstance() {
        return instance;
    }
    public String getpagination(int maxPage, int cpage, String vfile, String queryvars, String pageName) {
        String pag = "<div class='pagination'>";
        int fpage = 1;
        int page = cpage;
        int limit = 3;

        int pageno = cpage;
        int spage = cpage;
        int lower = spage - 1;
        int upper = spage + 1;
        String self = vfile + "?";
        int khigh = 0;
        int klow = 0;

        if (maxPage > limit) {
            if (pageno > 1) {

                pag = pag + "<li><a href=" + self + pageName + "=" + fpage + queryvars + ">1..</a></li>";
                pag = pag + "<li><a href=" + self + pageName + "=" + (pageno - 1) + queryvars + ">&laquo; </a></li>";
            }

            if (spage == 1) {
                klow = spage;
                khigh = limit;
            }
            if (spage > 1) {
                if (lower < 1) {
                    klow = 1;
                    khigh = limit;
                } else {
                    klow = lower;
                    khigh = upper;
                }

                if (upper > maxPage) {
                    khigh = maxPage;
                    klow = maxPage - (2 * 1);
                }
            }

            for (int i = klow; i <= khigh; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>";
                } else {
                    pag = pag + "<li><a href=" + self + pageName + "=" + i + queryvars + ">" + i + "</a></li>";
                    //pag = pag + "<li><a href=" + self + this->pag->pageName + "=" + i + queryvars + ">" + i + "</a></li>" + "\n";
                }
            }

            if (pageno < maxPage) {
                //pag = pag + "<span>...</span>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'>" + " &raquo;</a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + (maxPage) + queryvars + "'>" + " .." + maxPage + "</a></li>";
            }
        } else {
            /*     * * if this is page 1 there is no previous link ** */
            if (pageno != 1) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno - 1) + queryvars + "'>&laquo; </a></li>";
            }
            /*     * * loop over the pages ** */
            for (int i = 1; i <= maxPage; i++) {
                if (i == pageno) {
                    pag = pag + "<li><span class='active'>" + i + "</span></li>" + "";
                } else {
                    pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>";
                }   //pag = pag + "<li><a href='" + self + pageName + "=" + i + queryvars + "'>" + i + "  " + "</a></li>" + "\n";
            }
            /*     * * if we are on the last page, we do not need the NEXT link ** */
            if (pageno < maxPage) {
                pag = pag + "<li><a href='" + self + pageName + "=" + (pageno + 1) + queryvars + "'> &raquo; </a></li>";
                pag = pag + "<li><a href='" + self + pageName + "=" + maxPage + queryvars + "'> last </a></li>";
            }
        }

        pag = pag + "</div>";
        //String tmppag;
        if (maxPage < 2) {
            pag = "";
        }
        this.pagination = pag;

        return (this.pagination);
    }
    
}



And top of servlet:

package net;

import jakarta.servlet.*;
import java.sql.*;
import java.util.ArrayList;
import SQLBean.ConnBean;
import jakarta.enterprise.context.RequestScoped;
import jakarta.inject.Inject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 *
 * @author jimwin7a
 */
@MultipartConfig
@WebServlet(
        name = "FindOwnerServlet",
        urlPatterns = {"/FindOwnerServlet"}
)


public class FindOwnerServlet extends HttpServlet {
    @Inject net.PagingClass mypager;



And tried to use like:
String pagination = mypager.getpagination(cPage, pageno, vfile, queryvars, pagename);


However without @inject, this does work:
    net.PagingClass mypager = net.PagingClass.getInstance();
    String pagination = mypager.getpagination(cPage, pageno, vfile, queryvars, pagename);


I tried everything with original getter setter class and the new singleton class, but for now am using the singleton. I just can't seem to get @inject to work.

I even tried @EJB I saw in an S.O. post. I even took out the returning of the instance. So far only thing working is:

            net.PagingClass mypager = net.PagingClass.getInstance();
            String pagination = mypager.getpagination(cPage, pageno, vfile, queryvars, pagename);


[Updated on: Mon, 05 July 2021 03:05]

Report message to a moderator

Re: Dependency injection with @inject [message #1842882 is a reply to message #1842878] Mon, 05 July 2021 05:10 Go to previous messageGo to next message
Stephane Talbot is currently offline Stephane TalbotFriend
Messages: 9
Registered: March 2019
Junior Member
Jim Whitaker wrote on Sun, 04 July 2021 23:59
apache-tomcat-10.0.7

The servlet is just standard doGet stuff. But right now it is a mess from experimenting, needs to be cleaned up. I will post tomorrow if I get a chance.


Tomcat is just a Servlet/JSP container, it doesn't provides all the Jakarta EE Web API.
I think it doesn't have CDI by default, you have to add it.
Re: Dependency injection with @inject [message #1842897 is a reply to message #1842866] Mon, 05 July 2021 15:45 Go to previous messageGo to next message
Stephane Talbot is currently offline Stephane TalbotFriend
Messages: 9
Registered: March 2019
Junior Member
I've tested with a equivalent simplified equivalent project:

CDI bean:
package test.jee9.cdi;

import jakarta.enterprise.context.RequestScoped;

@RequestScoped
public class TestCdibean {
	private String param;

	public TestCdibean() {
		super();
	}
	
	public void setParam(String p) {
		this.param = (p == null) ? "empty" : p ;
	}
	public String getParam() {
		return param.toUpperCase();
	}
}


Servlet :
package test.jee9.cdi;

import java.io.IOException;

import jakarta.inject.Inject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Inject
	private TestCdibean bean;
       
    public TestServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String param = request.getParameter("p");
		bean.setParam(param);
		param = bean.getParam();
		request.setAttribute("p", param);
		request.getRequestDispatcher("/page.jsp").forward(request, response);
	}
}


JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<p>${p}</p>
</body>
</html>


beans.xml : empty file in Web-INF

I've tested it on Apache TomEE 9.0.0-M7-webprofile and it is working as expected.
TomEE is Tomcat extended to fulfill JavaEE/Jakarta EE Web Profile specification, so it comes with CDI preinstalled.
Re: Dependency injection with @inject [message #1842906 is a reply to message #1842897] Tue, 06 July 2021 04:25 Go to previous messageGo to next message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
Thank you so much, all who helped. That Apache TomEE 9.0.0-M7-webprofile did the trick, also is the super part needed, I added it. But all works now.

I had TomEE up and running in minutes, new project, copied web pages and beans and servlets over, assigned TomEE, added the super, clean and build, worked.

For TomEE in netbeans to work I had to uncheck "Use IDE Proxy Settings" under the Platform tab. However with Tomcat 10 I didn't have to, any ideas why?

But happy all is good, I now know why inject wasn't working.

Stephane I basically just changed my original code as needed to match your example, and added the super.

[Updated on: Tue, 06 July 2021 04:37]

Report message to a moderator

Re: Dependency injection with @inject [message #1842912 is a reply to message #1842906] Tue, 06 July 2021 07:10 Go to previous messageGo to next message
Stephane Talbot is currently offline Stephane TalbotFriend
Messages: 9
Registered: March 2019
Junior Member
For a CDI bean a constructor or a producer is mandatory.

For TomEE in Netbeans, I don't know what the problem is.
However, since TomEE is basically Tomcat++, I would expect the Tomcat 10 plugin to work.

In Eclipse IDE, for example you have to declare TomEE 9 servers as Tomcat 10 instances.
Re: Dependency injection with @inject [message #1842931 is a reply to message #1842912] Tue, 06 July 2021 23:27 Go to previous message
Jim Whitaker is currently offline Jim WhitakerFriend
Messages: 26
Registered: October 2020
Junior Member
All is working in Netbeans. I tried to also install TomEE in Eclipse, but no CDI is working. TomEE works, but @inject is not. I even followed this:
https://tomee.apache.org/latest/docs/tomee-and-eclipse.html

Any idea why Dependency Injection is working in netbeans but not eclipse. Identical projects.

Moving to new discussion.

[Updated on: Tue, 06 July 2021 23:55]

Report message to a moderator

Previous Topic:Cant run Karel the robot or other kinds of programs in Eclipse
Next Topic:[Solved] TomEE in Eclipse IDE 2021-06
Goto Forum:
  


Current Time: Sun Jul 25 02:03:26 GMT 2021

Powered by FUDForum. Page generated in 0.03963 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top