-3

following is my code my bean

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

/**
 *
 * @author utilisateur
 */
@ManagedBean(name="Beansearch")
@SessionScoped
public class Beansearch extends HttpServlet {
    ResultSet rs;
    private String cond;

    public String getcond() {
        return this.cond;
    }
    public void setcond(String cond) {
        this.cond= cond;
        }


   private List perInfoAll = new ArrayList();

    private int i;
public  List getperInfoAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
    String value = req.getParameter("cond");
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
        }
         Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:gmao", "pfe", "gmao");
        } catch (SQLException ex) {
            Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
        }
         Statement st = null;
        try {
            st = con.createStatement();
        } catch (SQLException ex) {
            Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
             rs = st.executeQuery("selectusername, jobposition from  user_details="+value+"");
            /** Creates a new instance of Beansearch */
        } catch (SQLException ex) {
            Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
        }

    while(rs.next())
          {

            perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2)));

            i++;

          }
return perInfoAll;
}
public class perInfo {

 private String username;
private String jobposition;


public perInfo(String username,String jobposition) {
this.username = username;
this.jobposition = jobposition;


}

public String getusername() {
return username;
}

public String getjobposition() {
return jobposition;
}



}
}

my page jsf

enter code here

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
      <h:form>


        <h:dataTable id="dt1" value="#{Beansearch.perInfoAll}" var="item" bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3"  rows="4" width="50%" dir="LTR" frame="hsides" rules="all" summary="This is a JSF code to create dataTable." >

<f:facet name="header">
        <h:outputText value="This is 'dataTable' demo" />
</f:facet>


<h:column>
        <f:facet name="header">
        <h:outputText value="First Name" />
        </f:facet>
             <h:outputText style=""  value="#{item.username}" ></h:outputText>
</h:column>

<h:column>
        <f:facet name="header">
        <h:outputText value="Last Name"/>
        </f:facet>
             <h:outputText  value="#{item.jobposition}"></h:outputText>
</h:column>

this code used to display data from a database in a jsf page what I need is how to display data by entering the search criteria and show only the corresponding elements with the request (select * from mytable where id ="+v+")

the question is how we can get "v" (enter value) how change my code to realize this(entering the search criteria in textbox and retrieve only the corresponding elements) can you help me please and give me an example if it is possible thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
hibara
  • 39
  • 2
  • 3
  • 5

1 Answers1

8

There's too much wrong in the code that it's nearly impossible to give a suitable answer without rewriting from scratch.


You seem to completely misunderstand the purpose of JSF.

@ManagedBean(name="Beansearch")
@SessionScoped
public class Beansearch extends HttpServlet {

Why does it extend HttpServlet? Remove it. In JSF all the request/response handling is already handled by the FacesServlet which you should already have declared in the webapp's web.xml. When you want to collect user input, you should be using the JSF input components like <h:inputText> and bind them to a bean property the usual JSF way.


You seem to completely misunderstand the exception handling as well.

Connection con = null;
try {
    con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:gmao", "pfe", "gmao");
} catch (SQLException ex) {
    Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
}
Statement st = null;
try {
    st = con.createStatement();
} catch (SQLException ex) {
    Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
}
try {
     rs = st.executeQuery("selectusername, jobposition from  user_details="+value+"");
    /** Creates a new instance of Beansearch */
} catch (SQLException ex) {
    Logger.getLogger(Beansearch.class.getName()).log(Level.SEVERE, null, ex);
}

You're only logging the exception and continuing the code flow instead of aborting it and informing the enduser about the problem. You should not be continuing the code flow when an exception occurs. You should throw the exception and propagate it to the container's default or customized error page or at least display a FacesMessage to the enduser.


You seem to not be aware about SQL injection risks as well.

rs = st.executeQuery("selectusername, jobposition from  user_details="+value+"");

Concatenating unsanitized user-controlled input data in a SQL string puts the doors wide open to SQL injection attacks. You should be using PreparedStatement instead. Apart from that, the SQL syntax is also invalid. There needs to be a space after the SELECT command and you need to use a WHERE clause.


Not a technical problem, but you seem to be using JSF 2.0...

@ManagedBean(name="Beansearch")
@SessionScoped

... and yet you're using the inferior JSP instead of its successor Facelets as view technology.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

I strongly recommend you to put this project aside and first work yourself through a decent book/tutorial to learn about the basic web development, JSF 2.0, JDBC and SQL concepts first. Do not work on your project immediately without having learnt the basic concepts first by simple examples provided by the books/tutorials. It will only end up in a complete disaster.

Nonetheless, here's a basic kickoff example of how the JSF form and the bean should look like:

<h:form>
    <h:inputText value="#{bean.query}" required="true" />
    <h:commandButton value="Search" action="#{bean.search}" />
    <h:messages />
</h:form>
<h:dataTable value="#{bean.users}" var="user" rendered="#{not empty bean.users}">
    <h:column>#{user.username}</h:column>
    <h:column>#{user.jobposition}</h:column>
</h:dataTable>
<h:outputText value="No matches found!" rendered="#{not empty bean.query and empty bean.users}" />

with

@ManagedBean
@RequestScoped
public class Bean {

    private String query;
    private List<User> users;

    public void search() throws SQLException {
        users = new UserDAO().search(query);
    }

    // Getters+setters.
}

where the UserDAO#list() method look like this:

public List<User> search(String query) throws SQLException {
    List<User> users = new ArrayList<User>();

    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT username, jobposition FROM user_details WHERE username LIKE ?");
    ) {
        statement.setString(1, "%" + query + "%");

        try (ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()) {
                User user = new User();
                user.setUsername(resultSet.getString("username"));
                user.setJobposition(resultSet.getString("jobposition"));
                users.add(user);
            }
        }
    }

    return users;
}

Good luck. And really, invest some time in learning the basic concepts first. It will take some weeks. Do not concentrate too much on your current project, it would after all otherwise take much longer. You can get started at our JSF wiki page.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You must be aiming for that Reversal badge because this is seriously the most effort I have ever seen in an answer to a hopeless question. ^_^ V – maple_shaft Jun 10 '11 at 10:57