# mySQL Manipulation über JavaServer Faces (Tutorial gesucht)



## stoevinho (7. Apr 2012)

Guten Morgen!

Auch an Ostern schonen euch die Anfänger nicht *g*

Ich bin Anfänger und will jetzt Step-by-Step über JSF ein Projekt angehen. Angefangen damit dass ich mich mit JSF-Büchern rumgequält habe bin ich nun an der Stelle angelangt wo ich entsprechende Tutorials brauche, um mit dem JDBC-Driver eine mySQL Datenbanktabelle zu manipulieren bzw. ausgeben zu lassen.

Nach der Seite: Display Data from Database in JSF Application habe ich es erfolgreich geschafft auf die DB zu connecten und 4 Datensätze ausgeben zu lassen. Das erste Problem dass sich dabei stellt: ich habe in der Tabelle noch eine Spalte mit ID (key, autoincrement) die er als first_name ausgibt und der last_name wird in der Ausgabe zum username und so weiter.. der tauscht da wild durch.

Eine explizite Ausgabe sieht anders aus. Woran hängt das? Wie schaffe ich es, dass in first_name tatsächlich der erste Name steht, bei last_name der Nachname und bei username der entsprechende Nutzername drinsteht? 

FirstName/ LastName / UserName
1 / Holowitz / Howard
2 / Cooper / Sheldon

Es müsste aber natürlich so sein:
FirstName/ LastName / UserName
Sheldon / Cooper / sheldonator 
... usw

Meine verwendete JSP:

```
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html>
<head>

</head>
<body>
<center>
<br><br><br>
<h:dataTable id="dt1" value="#{tableBean.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.firstName}" ></h:outputText>
</h:column>

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

<h:column>
        <f:facet name="header">
        <h:outputText value="Username"/>
        </f:facet> 
             <h:outputText value="#{item.uname}"></h:outputText>
</h:column>

<f:facet name="footer">
        <h:outputText value="The End" />
</f:facet> 

</h:dataTable><br>


</center>
</body></html></f:view>
```

Meine verwendeten SQL-Statements:

```
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL,
  `last_name` varchar(50) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `first_name` varchar(50) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `username` varchar(50) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  KEY `id` (`id`),
  KEY `last_name` (`last_name`)
) 

INSERT INTO `user` (`id`, `last_name`, `first_name`, `username`) VALUES
(1, 'Holowitz', 'Howard', 'howdi'),
(2, 'Hofstetter', 'Lennard', 'lenni'),
(3, 'Kootrhapali', 'Rajesh', 'Ray'),
(4, 'Cooper', 'Sheldon', 'sheldonator');
```

Meine Javaklasse:

```
package roseindia;
import java.sql.*;
import java.util.*;

public class TableBean {

Connection con ;
Statement ps;
ResultSet rs;
private List perInfoAll = new ArrayList(); 

public List getperInfoAll() {

 int i = 0;
  try
  {
	  
	  Class.forName("com.mysql.jdbc.Driver");
	  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdetail",
	"root","");
	
	  ps = con.createStatement();
	  rs = ps.executeQuery("select * from user");
	  while(rs.next()){
		  System.out.println(rs.getString(1));
		  perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2)
		,rs.getString(3)));
		  i++;
	
	  }
  
  }
  catch (Exception e)
  {
  System.out.println("Error Data : " + e.getMessage());
  }
return perInfoAll;
}


public class perInfo {

String uname;
String firstName;
String lastName;


public perInfo(String firstName,String lastName,String uname) {
this.uname = uname;
this.firstName = firstName;
this.lastName = lastName;

}

public String getUname() {
return uname;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

}

}
```

Meine web.xml:

```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>
  <resource-ref>
    <res-ref-name>jdbc/mydb</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>
```
(ich bin mir auch nicht so ganz sicher ob die angegeben config für die web.xml so richtig ist, k.A.)

und meine faces-config:

```
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

<managed-bean>
<managed-bean-name>tableBean</managed-bean-name>
<managed-bean-class>roseindia.TableBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

</faces-config>
```


Die zweite Frage ist die große und wichtige die ich an euch richten will: Ich möchte nun einen Datensatz manipulieren (inputText-field und commandButton "senden") und dann bei erfolgreichem Abschicken auf eine neue Seite weitergeleitet werden. Mir ist wichtig die Logik zu lernen damit ich das entsprechend anwenden kann. Könnt ihr mir lauffähige Tutorials empfehlen? Ich finde dazu nix, mal fehlt die Beschreibung der faces-config (outcome-from success usw) mal fehlt die Beschreibung der Java-Klasse... GRUMMEL... HIiiiiiilfe 

Ich bin für jede Hilfe dankbar!!!!!!!!!


----------



## stoevinho (7. Apr 2012)

AH! Das mit der richtigen Reihenfolge hab ich selber grad herausgefunden:


```
rs = ps.executeQuery("select first_name,last_name,username from user");
```

Bleibt die zweite Frage noch offen.. Ich hoffe ihr könnt mir da helfen


----------



## Marcinek (7. Apr 2012)

Die Felder werden falsch befüllt, weil das Item falsch befüllt wird. SQL Ist hier eine Ausnahme und fängt tatsächlich bei 1 an zu zählen.

Tutorials dazu gibt es im Internet wie Sand am Meer. Siehe google.


Der Nickname von Sheldon ist Sheldor und nicht sheldonator. :noe:


----------



## stoevinho (7. Apr 2012)

Jau, das mit dem SQL wäre abgehackt. Das mit Sheldon ändere ich dann auch noch 

Ich suche jetzt nur noch ein lauffähiges Tutorial für JSF mit JDBC und Datenmanipulation (delete, update, ...whatever).
Sitze seit vorgestern dran und ich finde einfach NICHTS dazu, das is so unfassbar. 

Brauche eure Hilfe!! Vielen Dank vorab


----------



## stoevinho (7. Apr 2012)

Könnt ihr bitte mal ein einfaches und sehr aktuelles Tutorial bei euch ausprobieren?

Sample JSF Web App With Mysql Database  Java World

Wenn das laufen würde, käme ich in der Tat weiter!!!

Console spuckt folgende Fehler aus:

```
07.04.2012 15:19:24 org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: .:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java
07.04.2012 15:19:24 org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jsf-mysql' did not find a matching property.
07.04.2012 15:19:24 org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:sample-web-app-with-mysql-database' did not find a matching property.
07.04.2012 15:19:24 org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNUNG: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:test01' did not find a matching property.
07.04.2012 15:19:25 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
07.04.2012 15:19:25 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
07.04.2012 15:19:25 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2649 ms
07.04.2012 15:19:25 org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
07.04.2012 15:19:25 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
07.04.2012 15:19:27 org.apache.catalina.core.StandardContext addApplicationListener
INFO: The listener "org.apache.myfaces.webapp.StartupServletContextListener" is already configured for this context. The duplicate definition has been ignored.
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_CLEAR_JAVASCRIPT_FOR_BUTTON' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_HIDDEN_FIELDS_FOR_LINK_PARAMS' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.SAVE_FORM_SUBMIT_LINK_IE' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.READONLY_AS_DISABLED_FOR_SELECTS' found, using default value true
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_VIEWSTATE_ID' found, using default value true
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.STRICT_XHTML_LINKS' found, using default value true
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_FORM_SUBMIT_SCRIPT_INLINE' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getLongInitParameter
INFO: No context init parameter 'org.apache.myfaces.CONFIG_REFRESH_PERIOD' found, using default value 2
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.VIEWSTATE_JAVASCRIPT' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getStringInitParameter
INFO: No context init parameter 'org.apache.myfaces.REFRESH_TRANSIENT_BUILD_ON_PSS' found, using default value auto
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.REFRESH_TRANSIENT_BUILD_ON_PSS_PRESERVE_STATE' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.VALIDATE_XML' found, using default value false
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.WRAP_SCRIPT_CONTENT_WITH_XML_COMMENT_TAG' found, using default value true
07.04.2012 15:19:27 org.apache.myfaces.shared_impl.config.MyfacesConfig createAndInitializeMyFacesConfig
INFO: Tomahawk jar not available. Autoscrolling, DetectJavascript, AddResourceClass and CheckExtensionsFilter are disabled now.
07.04.2012 15:19:27 org.apache.myfaces.config.FacesConfigurator feedStandardConfig
INFO: Reading standard config META-INF/standard-faces-config.xml
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator getWebAppConfig
INFO: Reading config /WEB-INF/faces-config.xml
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: Starting up MyFaces-package : myfaces-api in version : 2.0.2 from path : file:/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/WEB-INF/lib/myfaces-api-2.0.2.jar
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: Starting up MyFaces-package : myfaces-impl in version : 2.0.2 from path : file:/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/WEB-INF/lib/myfaces-impl-2.0.2.jar
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk12 not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox12 not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox15 not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : myfaces-orchestra-core not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : myfaces-orchestra-core12 not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : trinidad-api not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : trinidad-impl not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tobago not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : commons-el not found.
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : jsp-api not found.
07.04.2012 15:19:29 org.apache.myfaces.util.ExternalSpecifications isBeanValidationAvailable
INFO: MyFaces Bean Validation support disabled
07.04.2012 15:19:29 org.apache.myfaces.application.ApplicationImpl getProjectStage
INFO: Couldn't discover the current project stage, using Production
07.04.2012 15:19:29 org.apache.myfaces.config.FacesConfigurator handleSerialFactory
INFO: Serialization provider : class org.apache.myfaces.shared_impl.util.serial.DefaultSerialFactory
07.04.2012 15:19:29 org.apache.myfaces.config.annotation.DefaultLifecycleProviderFactory getLifecycleProvider
INFO: Using LifecycleProvider java.lang.String
07.04.2012 15:19:30 org.apache.myfaces.webapp.AbstractFacesInitializer initFaces
INFO: ServletContext '/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/' initialized.
07.04.2012 15:19:30 org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/test01/WEB-INF/lib/servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
07.04.2012 15:19:31 com.sun.faces.config.ConfigureListener contextInitialized
INFO: Mojarra 2.0.3 (FCS b03) für Kontext '/test01' wird initialisiert.
07.04.2012 15:19:33 com.sun.faces.spi.InjectionProviderFactory createInstance
INFO: JSF1048: PostConstruct/PreDestroy-Annotationen vorhanden.  Verwaltete Bean-Methoden, die mit diesen Annotationen markiert sind, lassen die entsprechenden Annotationen verarbeiten.
07.04.2012 15:19:35 com.sun.faces.config.ConfigureListener$WebConfigResourceMonitor$Monitor <init>
INFO: Monitoring jndi:/localhost/test01/WEB-INF/faces-config.xml for modifications
07.04.2012 15:19:35 org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/jsf-mysql/WEB-INF/lib/servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
07.04.2012 15:19:35 org.apache.catalina.core.StandardContext listenerStart
SCHWERWIEGEND: Error configuring application listener of class org.apache.myfaces.webapp.StartupServletContextListener
java.lang.ClassNotFoundException: org.apache.myfaces.webapp.StartupServletContextListener
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546)
	at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525)
	at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507)
	at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:124)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4715)
	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
	at java.util.concurrent.FutureTask.run(FutureTask.java:138)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:680)
07.04.2012 15:19:35 org.apache.catalina.core.StandardContext listenerStart
SCHWERWIEGEND: Skipped installing application listeners due to previous error(s)
07.04.2012 15:19:35 org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Error listenerStart
07.04.2012 15:19:35 org.apache.catalina.core.StandardContext startInternal
SCHWERWIEGEND: Context [/jsf-mysql.pdf] startup failed due to previous errors
07.04.2012 15:19:36 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
07.04.2012 15:19:36 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
07.04.2012 15:19:36 org.apache.catalina.startup.Catalina start
INFO: Server startup in 10658 ms
07.04.2012 15:19:39 org.apache.myfaces.renderkit.html.HtmlLabelRenderer encodeBegin
WARNUNG: Attribute 'for' of label component with id Search:j_id_jsp_1522312929_3 is not defined
07.04.2012 15:19:39 org.apache.myfaces.config.annotation.Tomcat7AnnotationLifecycleProvider newInstance
INFO: Creating instance of bean.Customer
ClassNotFoundException in getConnection, com.mysql.jdbc.Driver
07.04.2012 15:19:40 org.apache.myfaces.renderkit.ErrorPageWriter handleThrowable
SCHWERWIEGEND: An exception occurred
javax.faces.FacesException: org.apache.jasper.el.JspELException: /search.jsp(25,0) '#{customer.allCustomer}' Error reading 'allCustomer' on type bean.Customer
	at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241)
	at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
	at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:680)
Caused by: org.apache.jasper.el.JspELException: /search.jsp(25,0) '#{customer.allCustomer}' Error reading 'allCustomer' on type bean.Customer
	at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:112)
	at javax.faces.component._DeltaStateHelper.eval(_DeltaStateHelper.java:243)
	at javax.faces.component.UIData.getValue(UIData.java:1153)
	at javax.faces.component.UIData.createDataModel(UIData.java:1101)
	at javax.faces.component.UIData.getDataModel(UIData.java:1078)
	at javax.faces.component.UIData.getRowCount(UIData.java:457)
	at org.apache.myfaces.shared_impl.renderkit.html.HtmlTableRendererBase.encodeInnerHtml(HtmlTableRendererBase.java:289)
	at org.apache.myfaces.shared_impl.renderkit.html.HtmlTableRendererBase.encodeChildren(HtmlTableRendererBase.java:173)
	at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:488)
	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:609)
	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
	at org.apache.myfaces.shared_impl.view.JspViewDeclarationLanguageBase.actuallyRenderView(JspViewDeclarationLanguageBase.java:322)
	at org.apache.myfaces.shared_impl.view.JspViewDeclarationLanguageBase.renderView(JspViewDeclarationLanguageBase.java:181)
	at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:263)
	at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85)
	at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
	... 17 more
Caused by: java.lang.NullPointerException
	at bean.Customer.getAllCustomer(Customer.java:79)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
	at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
	at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
	at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
	at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
	at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
	... 33 more
07.04.2012 15:21:16 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/sample-web-app-with-mysql-database] has started
07.04.2012 15:21:16 org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SCHWERWIEGEND: The web application [/sample-web-app-with-mysql-database] created a ThreadLocal with key of type [org.apache.myfaces.el.convert.VariableResolverToELResolver$1] (value [org.apache.myfaces.el.convert.VariableResolverToELResolver$1@4ecd200f]) and a value of type [java.util.HashSet] (value [[]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
07.04.2012 15:21:16 org.apache.catalina.core.StandardContext addApplicationListener
INFO: The listener "org.apache.myfaces.webapp.StartupServletContextListener" is already configured for this context. The duplicate definition has been ignored.
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_CLEAR_JAVASCRIPT_FOR_BUTTON' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_HIDDEN_FIELDS_FOR_LINK_PARAMS' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.SAVE_FORM_SUBMIT_LINK_IE' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.READONLY_AS_DISABLED_FOR_SELECTS' found, using default value true
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_VIEWSTATE_ID' found, using default value true
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.STRICT_XHTML_LINKS' found, using default value true
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.RENDER_FORM_SUBMIT_SCRIPT_INLINE' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getLongInitParameter
INFO: No context init parameter 'org.apache.myfaces.CONFIG_REFRESH_PERIOD' found, using default value 2
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.VIEWSTATE_JAVASCRIPT' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getStringInitParameter
INFO: No context init parameter 'org.apache.myfaces.REFRESH_TRANSIENT_BUILD_ON_PSS' found, using default value auto
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.REFRESH_TRANSIENT_BUILD_ON_PSS_PRESERVE_STATE' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.VALIDATE_XML' found, using default value false
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig getBooleanInitParameter
INFO: No context init parameter 'org.apache.myfaces.WRAP_SCRIPT_CONTENT_WITH_XML_COMMENT_TAG' found, using default value true
07.04.2012 15:21:16 org.apache.myfaces.shared_impl.config.MyfacesConfig createAndInitializeMyFacesConfig
INFO: Tomahawk jar not available. Autoscrolling, DetectJavascript, AddResourceClass and CheckExtensionsFilter are disabled now.
07.04.2012 15:21:16 org.apache.myfaces.config.FacesConfigurator feedStandardConfig
INFO: Reading standard config META-INF/standard-faces-config.xml
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator getWebAppConfig
INFO: Reading config /WEB-INF/faces-config.xml
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: Starting up MyFaces-package : myfaces-api in version : 2.0.2 from path : file:/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/WEB-INF/lib/myfaces-api-2.0.2.jar
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: Starting up MyFaces-package : myfaces-impl in version : 2.0.2 from path : file:/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/WEB-INF/lib/myfaces-impl-2.0.2.jar
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk12 not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox12 not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tomahawk-sandbox15 not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : myfaces-orchestra-core not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : myfaces-orchestra-core12 not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : trinidad-api not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : trinidad-impl not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : tobago not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : commons-el not found.
07.04.2012 15:21:17 org.apache.myfaces.config.FacesConfigurator startLib
INFO: MyFaces-package : jsp-api not found.
07.04.2012 15:21:17 org.apache.myfaces.util.ExternalSpecifications isBeanValidationAvailable
INFO: MyFaces Bean Validation support disabled
07.04.2012 15:21:18 org.apache.myfaces.application.ApplicationImpl getProjectStage
INFO: Couldn't discover the current project stage, using Production
07.04.2012 15:21:18 org.apache.myfaces.config.FacesConfigurator handleSerialFactory
INFO: Serialization provider : class org.apache.myfaces.shared_impl.util.serial.DefaultSerialFactory
07.04.2012 15:21:18 org.apache.myfaces.config.annotation.DefaultLifecycleProviderFactory getLifecycleProvider
INFO: Using LifecycleProvider java.lang.String
07.04.2012 15:21:18 org.apache.myfaces.webapp.AbstractFacesInitializer initFaces
INFO: ServletContext '/Users/stoevn/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/sample-web-app-with-mysql-database/' initialized.
07.04.2012 15:21:18 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/sample-web-app-with-mysql-database] is completed
```

In der Zeile "allCustomer" gibt es nicht als Methode, nach Customer.java nur getAllCustomer oder getAllCustormerDetail. Wenn ich das in "customer.getAllCustomer" ändere kann ich die JSP mit dem Hinweis: "Method must have signature "String method(), but has signature "List method()"


----------



## stoevinho (7. Apr 2012)

Hallo :-(

ich komme immer noch nicht weiter, ich hänge an diesem String<->Liste Problem: Ich übergebe nen String und bekomme ne Liste zurück, wo genau das Problem dabei jetzt ist verstehe ich nicht so ganz. Hoffe ihr könnte mir da weiterhelfen.

Fehler 1: Error@index.jsp Line15 "Method must have signature "String method(), but has signature "List method()"
Fehler 2: Caused by: org.apache.jasper.el.JspPropertyNotFoundException: /index.jsp(14,2) '#{suchen_bean.suchbegriff}' Property 'suchbegriff' not readable on type java.lang.String

Folgendes habe ich: Index.jsp, Result.jsp, suchen_bean.java, faces-config.xml

Index.jsp

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

	<h:form>
		<h:inputText value="#{suchen_bean.suchbegriff}"> Suchbegriff </h:inputText>
		<h:commandButton action="#{suchen_bean.sucheBegriff}" value="Suche!"></h:commandButton>
	</h:form>
</f:view>
</body>
</html>
```

Result.jsp

```
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html>
<head>

</head>
<body>
<center>
<br><br><br>
<h:dataTable id="dt1" value="#{suchen_bean.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="ID" />
        </f:facet> 
             <h:outputText style=""  value="#{item.ID}" ></h:outputText>
</h:column>

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

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

<f:facet name="footer">
        <h:outputText value="The End" />
</f:facet> 

</h:dataTable><br>


</center>
</body></html></f:view>
```

suchen_bean.java

```
package beans;

import java.sql.*;
import java.util.*;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean(name="suchen_bean")
@RequestScoped

public class suchen_bean {

	private String suchbegriff;
	
	Connection con ;
	Statement ps;
	ResultSet rs;
	String SQL_Str;
	
	public String getSuchgegriff() {
		return suchbegriff;
	}
	public void setSuchbegriff(String suchbegriff) {
		this.suchbegriff = suchbegriff;
	}
	
	private List perInfoAll = new ArrayList(); 
	
	public List sucheBegriff()
	{		
		int i = 0;
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
			
			SQL_Str="Select * from tbl_users where UName like ('" + suchbegriff +"')";
			ps = con.createStatement();
			//rs = ps.executeQuery("select * from user where UName like ('"+suchbegriff+"')");
			rs=ps.executeQuery(SQL_Str);
			while(rs.next()){
				//System.out.println(rs.getString(1));
				perInfoAll.add(i,new perInfo(rs.getInt(1),rs.getString(2),rs.getString(3)));
				i++;
		}
	}catch (Exception e)
	{
		System.out.println("Error Data : " + e.getMessage());
	}
	  
	return perInfoAll;
	}
	
	
	public class perInfo {
	
		Integer ID;
		String UName;
		String PWord;
		
		public perInfo(Integer ID, String UName, String PWord) {
			this.ID = ID;
			this.UName = UName;
			this.PWord = PWord;
		}
		
		public String ResultSearch(){
			sucheBegriff();
			return "result";
		}		
		
		public Integer getID() {
			return ID;
		}
		
		public String getUname() {
			return UName;
		}
		
		public String getPWord() {
			return PWord;
		}
	
	}

}
```

faces-config.xml

```
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
	<managed-bean>
		<managed-bean-name>labcon</managed-bean-name>
		<managed-bean-class>beans.Labcon</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>suchen_bean</managed-bean-name>
		<managed-bean-class>beans.suchen_bean</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
	
<navigation-rule>
  <from-view-id>/index.jsp</from-view-id>
  <navigation-case>
   <from-outcome>result</from-outcome>
   <to-view-id>/result.jsp</to-view-id>
  </navigation-case>
</navigation-rule>


</faces-config>
```

Bitte helft mir! :-(
Ich weiß nicht mehr weiter......


----------



## vladimir75 (8. Apr 2012)

Wenn es dich interessiert, findest du hier andere Tutorials und Beispiele.

JSF 2.0 + JDBC integration example

A tutorial on Java visual web JSF applications and MySQL database using Java Persistence API (JPA) with tons of screenshots

A complete tutorial on Java visual web application development that uses JSP, JSF, JPA and other currently available Java technologies with Derby/mySQL database

Simple Database Application with JSF (User Login)  Prashant's Blog

JSF 2.0, JPA, GlassFish and MySQL | Java.net

https://anshuchoudhury.files.wordpress.com/2012/03/jsf-mysql.pdf

Vladimir


----------



## Final_Striker (8. Apr 2012)

```
Fehler 1: [email]Error@index.jsp[/email] Line15 "Method must have signature "String method(), but has signature "List method()"
```

Da steht doch, dass die Methode einen String zurückgeben soll und keine Liste.


----------



## stoevinho (8. Apr 2012)

Hallooo!!

Danke vladimir75 für die nützlichen Tipps!

Endlich - meine Güte!!! Geschafft. Hab jetzt (ungelogen) 20H an einem Fehler "herumgebastelt" der letztendlich ein Schreibfehler war *grml*  -> Anfänger halt.

So. Für alle die es interessiert und nicht interessiert:

Web.xml:
[XML]<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>jsf-database-application</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <description>
	This parameter tells MyFaces if javascript code should be allowed in
	the rendered HTML output.
	If javascript is allowed, command_link anchors will have javascript code
	that submits the corresponding form.
	If javascript is not allowed, the state saving info and nested parameters
	will be added as url parameters.
	Default is 'true'</description>
    <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <description>
	If true, rendered HTML code will be formatted, so that it is 'human-readable'
	i.e. additional line separators and whitespace will be written, that do not
	influence the HTML code.
	Default is 'true'</description>
    <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
    <param-value>true</param-value>
  </context-param>
  <context-param>
    <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
    <param-value>false</param-value>
  </context-param>
  <context-param>
    <description>
	If true, a javascript function will be rendered that is able to restore the
	former vertical scroll on every request. Convenient feature if you have pages
	with long lists and you do not want the browser page to always jump to the top
	if you trigger a link or button action that stays on the same page.
	Default is 'false'
</description>
    <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
    <param-value>true</param-value>
  </context-param>
  <listener>
    <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
  </listener>
</web-app>[/XML]

faces-config:
[XML]<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
	<managed-bean>
		<managed-bean-name>labcon</managed-bean-name>
		<managed-bean-class>beans.Labcon</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>suchen_bean</managed-bean-name>
		<managed-bean-class>beans.suchen_bean</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>

  <navigation-rule>
        <description>Suche</description>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
            <from-action>#{suchen_bean.checkBegriffEmpty}</from-action>
            <from-outcome>valid</from-outcome>
            <to-view-id>/result.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-action>#{suchen_bean.checkBegriffEmpty}</from-action>
            <from-outcome>invalid</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
        </navigation-case>

    </navigation-rule>

</faces-config>
[/XML]

index.jsp (als "Suchmaske" *g*):

```
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
	<h:form>
		
		<h:inputText id="suchbegriff" value="#{suchen_bean.suchbegriff}" required="true" styleClass="input_text"/>
		<h:commandButton action="#{suchen_bean.checkBegriffEmpty}" value="Suche" type="submit"></h:commandButton>
	</h:form>
</f:view>
</body>
</html>
```

result.jsp (als Ergebnisdarstellung *g*):

```
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html>
<head>

</head>
<body>


<h:dataTable id="dt1" value="#{suchen_bean.result}" 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.firstName}" ></h:outputText>
</h:column>

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

<h:column>
        <f:facet name="header">
        <h:outputText value="Username"/>
        </f:facet> 
             <h:outputText value="#{item.uname}"></h:outputText>
</h:column>

<f:facet name="footer">
        <h:outputText value="The End" />
</f:facet> 

</h:dataTable><br>



</body></html></f:view>
```

suchen_bean.java

```
package beans;

import java.sql.*;
import java.util.*;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import beans.suchen_bean.perInfo;

public class suchen_bean {

private String suchbegriff;

Connection con ;
Statement ps;
ResultSet rs;
private List result = new ArrayList(); 

	public void setResult (List result){
		this.result = result;
	}
	public List getResult() {
		return result;
	}

	public String getSuchbegriff() {
	    return suchbegriff;
	}
	public void setsuchbegriff(String suchbegriff) {
	    this.suchbegriff = suchbegriff;
	}

	public String checkBegriffEmpty(){
		
		
		 if(suchbegriff!=null)
		 {
			 sucheBegriff(suchbegriff);
			 return "valid";
		 }else
		 {
	         return "invalid";
		 }    
	}
	
	public List sucheBegriff (String suchbegriff){
	
	 int i = 0;
	  try
	  {
		  Class.forName("com.mysql.jdbc.Driver");
		  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student",
		"root","");
		
		  ps = con.createStatement();
		  rs = ps.executeQuery("select * from users where username like '"+suchbegriff+"' ");
		  while(rs.next()){
			  //System.out.println(rs.getString(1));
			  result.add(i,new perInfo(rs.getString(1),rs.getString(2),rs.getString(3)));
			  i++;
		  }
	  }
	  catch (Exception e)
	  {
		  System.out.println("Error Data : " + e.getMessage());
	  }
	  
	  return result;
	}


	public class perInfo {
	
		String uname;
		String firstName;
		String lastName;
	
	
		public perInfo(String firstName,String lastName,String uname) {
			this.uname = uname;
			this.firstName = firstName;
			this.lastName = lastName;
		
		}
		
		public String getUname() {
			return uname;
		}
		
		public String getFirstName() {
			return firstName;
		}
		
		public String getLastName() {
			return lastName;
		}
	
	}//class perInfo

}//class suchen_bean
```

Nicht schön aber weitestgehend funktionabel.

Eine elementare Frage habe ich dennoch -> Die Sucheanfrage per SQL String lautet: 
	
	
	
	





```
select * from users where username like suchbegriff
```
Das Ergebnis ist, dass er nur exakte Strings ausgibt als "Treffer". Wenn ich "AA" eingebe und "AA" sowie "AAA" in der DB habe, dann filter er nur exakte Sucheingaben. *Wie kann ich erreichen, dass wenn ich A eingebe er mir auch AA und AAA als Ergebnis zurückliefert???*

Vielen Dank im Voraus für jeden Tipp!


----------



## Gast2 (8. Apr 2012)

```
... LIKE '%suchbegriff%'
```


----------



## stoevinho (8. Apr 2012)

Danke!!! DAAAANKE DANKE DANKE!!!!!!!! made-my-day!! :applaus:


----------

