使用JSF,JDBC和HttpServlet在dataTable中搜索和检索数据

hib*_*ara -2 datatable jsf servlets jdbc

以下是我的代码我的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;
}



}
}
Run Code Online (Sandbox Code Playgroud)

我的页面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>
Run Code Online (Sandbox Code Playgroud)

这段代码用于显示jsf页面中数据库的数据,我需要的是如何通过输入搜索条件来显示数据,并仅显示带有请求的相应元素(select*from mytable where id ="+ v +")

问题是我们如何得到"v"(输入值)如何改变我的代码来实现这一点(在文本框中输入搜索条件并仅检索相应的元素)你可以帮助我并给我一个例子,如果有可能的话谢谢

Bal*_*usC 8

代码中有太多错误,如果不从头开始重写,几乎不可能给出合适的答案.


你似乎完全误解了JSF的目的.

@ManagedBean(name="Beansearch")
@SessionScoped
public class Beansearch extends HttpServlet {
Run Code Online (Sandbox Code Playgroud)

它为什么延伸HttpServlet?去掉它.在JSF中,所有请求/响应处理已经由FacesServlet您应该已经在webapp中声明的处理web.xml.当你想收集用户输入时,你应该使用JSF输入组件<h:inputText>,并以通常的JSF方式将它们绑定到bean属性.


您似乎也完全误解了异常处理.

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);
}
Run Code Online (Sandbox Code Playgroud)

您只记录异常并继续代码流而不是中止它并通知最终用户该问题.发生异常时,不应该继续代码流.您应抛出异常并将其传播到容器的默认或自定义错误页面,或至少FacesMessage向最终用户显示a .


您似乎也不了解SQL注入风险.

rs = st.executeQuery("selectusername, jobposition from  user_details="+value+"");
Run Code Online (Sandbox Code Playgroud)

在SQL字符串中连接未经过处理的用户控制的输入数据会使SQL注入攻击敞开大门.你应该使用PreparedStatement而不是.除此之外,SQL语法也无效.在SELECT命令之后需要有一个空格,你需要使用一个WHERE子句.


不是技术问题,但你似乎在使用JSF 2.0 ......

@ManagedBean(name="Beansearch")
@SessionScoped
Run Code Online (Sandbox Code Playgroud)

...然而,你使用劣质JSP而不是其后继Facelets作为视图技术.

<%@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"%>
Run Code Online (Sandbox Code Playgroud)

我强烈建议你把这个项目放在一边,首先通过一本体面的书/教程来了解基本的Web开发,JSF 2.0,JDBC和SQL概念.如果没有通过书籍/教程提供的简单示例首先学习基本概念,请不要立即处理您的项目.它只会在一场彻底的灾难中结束.

尽管如此,这是JSF表单和bean应该如何形成的基本启动示例:

<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}" />
Run Code Online (Sandbox Code Playgroud)

@ManagedBean
@RequestScoped
public class Bean {

    private String query;
    private List<User> users;

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

    // Getters+setters.
}
Run Code Online (Sandbox Code Playgroud)

其中,UserDAO#list()方法是这样的:

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;
}
Run Code Online (Sandbox Code Playgroud)

祝好运.实际上,首先要花一些时间学习基本概念.这将需要几周时间.不要过分关注你当前的项目,否则它会花费更长的时间.您可以从我们的JSF wiki页面开始.

也可以看看: