How to retrieve data from a form and to send it to a MySQL database via JDBC?
Here's my procedure:
main class:
public class Dati extends MVCPortlet {
public static Connection con() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.out.println("Errore");
}
// APRI CONNESSIONE
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/db_alex","root","25071984");
System.out.println("Connessione effettuata");
return conn;
} catch (SQLException ex) {
System.out.println("SQlException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return null;
}
}
public void Invio (ActionRequest actionRequest, ActionResponse actionResponse)
throws PortletException, IOException {
String username = actionRequest.getParameter("username");
String password = actionRequest.getParameter("password");
Connection conn = null;
try {
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO contacts (username,password) values ('"+username+"','"+password+"')");
System.out.println("Inserimento avvenuto con successo");
} catch (Exception e) {
System.out.println("Inserimento non avvenuto");
}
}
}
view.jsp
<%
/**
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL name="Invio" var="Invio"/>
<form method="post" action="actionURL/>">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Invia!">
</form>
I don't know where my fault is. I was reading Portlet is temporarily unavailable and applying that rule, but Liferay says I'm wrong.
Which is the correct procedure to store?
you define actionURL Invio as a java object in view.jsp but you reference it wrong. you should reference it in <%= %> tag. actually your form tag should look like this:
<form method="post" action='<%=Invio%>'>
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Invia!">