-3

i have a jsp file which gets some details from the user like name and surname. I want to save the user's answers and use them in a java class to save them in a database. Does anyone knows how can this happen?

Thanks Al

  • Start learning JDBC and Servlets and come back if you have a more concrete question: http://docs.oracle.com/javase/tutorial/jdbc/basics/ and http://stackoverflow.com/tags/servlets/info – BalusC Feb 18 '12 at 16:29
  • i know how to use JDBC, my problem is how to get the variables from jsp to the java file. – user1218282 Feb 18 '12 at 16:30
  • 2
    You seem to not know how to use Servlets. Collecting request parameters is covered in chapter 1 of a bit decent JSP/Servlet book/tutorial. – BalusC Feb 18 '12 at 17:15

2 Answers2

1

Yes - submit them with a form. Then you can read them with request.getParameter(..). Then use JDBC to store them in a database.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • thanks for your answer. i have made the form. do you mean that i can use the request.getParameter in java file and use the variables? – user1218282 Feb 18 '12 at 16:32
0

The basic way of doing this is to import the class you'll be using, instantiate that class, and then pass the form variables to it using that class's methods.

Here's a quick example:

<%@page import="MyClass" %>

<%
MyClass myClassInstance = new MyClass();

//get the value of the submitted form element called "name"
String nameString = request.getParameter("name");

if(nameString != null && nameString.length() > 0)
    myClassInstance.setName(nameString);
%>
//the rest of the JSP would follow

As you say, you already know how to use JDBC, so it should be trivial to get that value into a database once it's in the Java class.

jonmorgan
  • 2,570
  • 2
  • 22
  • 27
  • thank you very much for your answer it seems very useful, i will test it now. – user1218282 Feb 18 '12 at 16:42
  • Be careful. This answer exposes bad practices which may hurt in long term. – BalusC Feb 18 '12 at 17:14
  • Anything in particular? I would appreciate knowing what I've done wrong so that I won't make the same mistakes in the future. – jonmorgan Feb 18 '12 at 17:16
  • i solve the problem with variables with the answer that @spookyjon reccomended. is it possible for data to be stored in the database in the same class which contains the setName() method? I've tried it but it doesnt seem to work. – user1218282 Feb 18 '12 at 17:30
  • @spookyjon Give this a read http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files/3180202#3180202 – Sean Feb 19 '12 at 06:20
  • Well, my mind has just been blown. Thanks for the link. – jonmorgan Feb 19 '12 at 17:29