使用JSF,JDBC和HttpServlet搜索和检索dataTable中的数据 [英] Search and retrieve data in dataTable using JSF, JDBC and HttpServlet
问题描述
以下是我的代码
我的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扩展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);
}
连接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);
}
语句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 +);
/ **创建一个新的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 ++;
}
返回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;
}
}
}
我的页面jsf
在此输入代码
<%@ page contentType =text / htmlpageEncoding =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/htmlprefix =h%>
<%@ taglib uri =http://java.sun.com/jsf/coreprefix =f%>
< f:view>
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = UTF-8>
< title> JSP页面< / title>
< / head>
< body>
< h:form>
< h:dataTable id =dt1value =#{Beansearch.perInfoAll}var =itembgcolor =#F1F1F1border =10cellpadding = 5cellspacing =3rows =4width =50%dir =LTRframe =hsidesrules =allsummary =这是一个用于创建dataTable的JSF代码。 >
< f:facet name =header>
< h:outputText value =这是'dataTable'demo'/>
< / f:facet>
< h:column>
< f:facet name =header>
< h:outputText value =名字/>
< / f:facet>
< h:outputText style =value =#{item.username}>< / h:outputText>
< / h:column>
< h:column>
< f:facet name =header>
< h:outputText value =姓氏/>
< / f:facet>
< h:outputText value =#{item.jobposition}>< / h:outputText>
< / h:column>
此代码用于在jsf页面中显示数据库中的数据我需要的是如何显示数据通过输入搜索条件并仅显示与请求相对应的元素(select * from mytable where id =+ v +)
问题是我们如何获得 v(输入值)
如何更改我的代码来实现这一点(在文本框中输入搜索条件并仅检索相应的元素)
你可以帮助我,给我一个例子,如果可能的话b $ b谢谢
代码中有太多错误,几乎不可能给出一个合适的答案而不用从头开始重写。
您似乎完全误解了JSF的目的。
@ManagedBean(name =Beansearch)
@SessionScoped
public class Beansearch extends HttpServlet {
为什么它会扩展 您似乎完全误解异常处理。 您只会记录异常,继续代码流而不是中止它,并通知最终用户有关问题。当异常发生时,不应该继续执行代码流。您应该抛出异常,并将其传播到容器的默认或自定义错误页面,或者至少向最终用户显示一个 您似乎也不了解SQL注入风险。 将无符号化的用户控制的输入数据连接在SQL字符串中使门能够打开到 SQL注入攻击。您应该使用 不是技术问题,但您似乎正在使用JSF 2.0 ... ...但是您使用的是较低级的JSP,而不是其后续的Facelets作为视图技术。 我强烈建议您将此项目放在一边,首先通过一本体面的书/教程自己学习基本的Web开发,JSF 2.0,JDBC和SQL概念。不要在没有通过书/教程提供的简单示例的基础上首先了解基本概念,而不要立即处理项目。这只是一个完整的灾难。 尽管如此,以下是JSF表单和bean应如下所示的基本启动示例: 与 其中 祝你好运。而且真的要花点时间先学习基本概念。这将需要几个星期。不要过分关注你目前的项目,否则要花更长的时间。您可以在我们的 JSF wiki页面上入门。 following is my code
my bean my page jsf 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 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. Why does it extend You seem to completely misunderstand the exception handling as well. 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 You seem to not be aware about SQL injection risks as well. Concatenating unsanitized user-controlled input data in a SQL string puts the doors wide open to SQL injection attacks. You should be using Not a technical problem, but you seem to be using JSF 2.0... ... and yet you're using the inferior JSP instead of its successor Facelets as view technology.
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: with where the 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. 这篇关于使用JSF,JDBC和HttpServlet搜索和检索dataTable中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Htt pServlet
?去掉它。在JSF中,所有的请求/响应处理已经由你应该已经在webapp的 web.xml $ c $中声明的
FacesServlet
来处理c>。当您想收集用户输入时,您应该使用JSF输入组件,例如< h:inputText>
,并将它们绑定到通常的JSF方式的bean属性。 p>
连接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);
}
语句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 +);
/ **创建一个新的Beansearch实例* /
} catch(SQLException ex){
Logger.getLogger(Beansearch.class.getName())。log(Level.SEVERE,null ,ex);
}
FacesMessage
。
rs = st.executeQuery(selectusername,jobposition from user_details =+ value +);
PreparedStatement
。除此之外,SQL语法也是无效的。在 SELECT
命令之后需要一个空格,您需要使用 WHERE
子句。
@ManagedBean(name =Beansearch)
@SessionScoped
<%@ page contentType =text / htmlpageEncoding =UTF-8%>
<%@ taglib uri =http://java.sun.com/jsf/htmlprefix =h%>
<%@ taglib uri =http://java.sun.com/jsf/coreprefix =f%>
< h:form>
< h:inputText value =#{bean.query}required =true/>
< h:commandButton value =Searchaction =#{bean.search}/>
< h:messages />
< / h:form>
< h:dataTable value =#{bean.users}var =userrendered =#{not empty bean.users}>
< h:column>#{user.username}< / h:column>
< h:column>#{user.jobposition}< / h:column>
< / h:dataTable>
< h:outputText value =找不到匹配项! rendered =#{not empty bean.query and empty bean.users}/>
@ManagedBean
@RequestScoped
public class Bean {
private String query;
私人列表<用户>用户;
public void search()throws SQLException {
users = new UserDAO()。search(query);
}
// Getters + setters。
}
UserDAO#list()
方法看起来像这样:
public List< User> search(String query)throws SQLException {
列表< 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);
}
}
}
返回用户;
}
查看还有:
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;
}
}
}
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>
@ManagedBean(name="Beansearch")
@SessionScoped
public class Beansearch extends HttpServlet {
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.
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);
}
FacesMessage
to the enduser.
rs = st.executeQuery("selectusername, jobposition from user_details="+value+"");
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.
@ManagedBean(name="Beansearch")
@SessionScoped
<%@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"%>
<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}" />
@ManagedBean
@RequestScoped
public class Bean {
private String query;
private List<User> users;
public void search() throws SQLException {
users = new UserDAO().search(query);
}
// Getters+setters.
}
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;
}
See also: