Home > front end >  CDI in JSP ( not JSF ) on Tomcat 10 ( jakarta.servlet.* )
CDI in JSP ( not JSF ) on Tomcat 10 ( jakarta.servlet.* )

Time:01-27

Spec : TOMCAT10 , weld -libraries from jboss

Process : Trying (CDI) insert from input-text to pojo from a pure simple JSP Page

<form method="get">
  <table  width="25%" border=1>
   <tr>
   <td>Name :</td>
   <td><input type="text" maxlength="10" id="login" name="login" value="${bean.input}"/></td>
   </tr>    
   <tr>
   <td colspan=2>
   <button type="button" id="TEST" value="${bean.submit()}"   name="TEST" />TEST-CDI</button>   
   </td>
   </tr>  
   </table> 
   </form>

Pojo is as follows

@Named()
@RequestScoped
public class Bean implements java.io.Serializable {

    private String input;
    private String output;

    //Get/setters
    public String getInput() {return input;}
    public void setInput(String input) {this.input = input;}
    public String getOutput() {return output;}
    public void setOutput(String output) {this.output = output;}
    public void submit() {
        output = "Hello World! You have typed: "   input;
        System.out.println("SUBMITTED : "   output);
    }
}

O/p : SUBMITTED : Hello World! You have typed: null

Question : Why Injection of InputText not passed to pojo ?

Leads : No post avaliable on WWW (google/yahoo....)

with regards karthik

CodePudding user response:

Why Injection of InputText not passed to pojo ?

Because this is not done by CDI.

You basically forgot to create a servlet like below:

@WebServlet("/yourServlet")
public class YourServlet extends HttpServlet {

    @Inject
    private Bean bean;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        bean.setInput(request.getParameter("login"));

        if ("submit".equals(request.getParameter("action")) {
            bean.submit();
        }

        request.getRequestDispatcher("your.jsp").forward(request, response);
    }
}

You only need to adjust form and submit button as follows:

<form action="${pageContext.request.contextPath}/yourServlet" method="post">
    ...
    <button type="submit" name="action" value="submit">TEST-CDI</button>
    ...
</form>

CDI basically only autocreates bean instance when referenced for the first time in a particular scope, such as ${bean} in EL or @Inject in some container managed component such as a servlet or another bean. CDI doesn't at all collect and set submitted HTTP request parameters. That's the responsibility of a servlet.

Do note that when using JSF, the entire YourServlet is unnecessary and you only need a view (like that JSP page) and a model (like that CDI bean). That's the whole point of JSF. It comes with its own FacesServlet which does this all automagically. And it does even more, such as (implicit) conversion, validation and, importantingly, XSS attack prevention.

See also:

  •  Tags:  
  • Related