This example will show you how to write the data provided by the user into a text file.
Step 1 : Create HTML or JSP page to accept user input.
Enter the following code in the body tag of your code
<form action="servlet1">
Name : <input type="text" name="username"/>
<br/>
Email ID : <input type="text" name="email"/>
<br/>
<input type="submit" value="OK"/>
</form>
Step 2 : Retriving User input values and writing it into a text file.
Enter the following code in the doGet() of the servlet (in my case named "servlet1").
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//retriving & storing user input in the String Variables
String name = request.getParameter("username");
String eid = request.getParameter("email") ;
//writing data into a text file
PrintWriter pw = null;
try {
pw= new PrintWriter(new FileWriter("D:\\file.txt", true)); //the second parameter of the file writer object accepts a boolean value to specify whether to append to existing file (true) or to overwrite the existing file (false).
pw.print(name + "\t");
pw.println(eid);
pw.close();
}
catch (IOException ex) { //exception handling code }
finally {
pw.close();
}
Finally, check the file from the path where it has been created.
JSP & Servlet Help
Wednesday, September 22, 2010
Monday, September 20, 2010
Passing Objects between Servlets
In this example we will see how to create class files, create objects with user input values and pass object from one servlet to another.
Step 1 : Create Java Class File.
Objects are an instance of a Class. So, we need a class file as a structure to create objects from user input values.
Create a java class file named "User.java".
public class User {
private String name;
private String email;
public User(String n, String e) {
this.name = n;
this.email = e;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
Step 2 : Create HTML or JSP page to accept user input.
Enter the following code in the body tag of your code
<form action="servlet1">
Name : <input type="text" name="username"/>
<br/>
Email ID : <input type="text" name="emailid"/>
<br/>
<input type="submit" value="OK"/>
</form>
Step 3 : Create First Servlet to create object and store the user input values.(in my case named "servlet1").
Enter the following code in the doGet() of the servlet.
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//creating an object named "newUser" of the class User & passing user input values as parameter to the constructor.
User newUser = new User(request.getParameter("username"),request.getParameter("emailid"));
//set a string value (eg."userData") for the object "newUser" to be able to access it from another servlet.
request.setAttribute("userData", newUser);
//passing the control to the second servlet named "servlet2" using RequestDispatcher.
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
Step 4 : Create Second Servlet to retrive object data and display it to the user.
Enter the following code in the doGet() of the servlet.
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//get the "userData" attribute from servlet1 and store it in variable "u" of the type "User" created earlier.
//also do not forget to typecast the attribute to the desired type.
User u = (User) request.getAttribute("userData");
//finally print the values using the getter methods of the User Class.
response.getWriter().println("Name : " + u.getName());
response.getWriter().println("Email : " + u.getEmail());
Finally, run the HTML or JSP page.
Step 1 : Create Java Class File.
Objects are an instance of a Class. So, we need a class file as a structure to create objects from user input values.
Create a java class file named "User.java".
public class User {
private String name;
private String email;
public User(String n, String e) {
this.name = n;
this.email = e;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
Step 2 : Create HTML or JSP page to accept user input.
Enter the following code in the body tag of your code
<form action="servlet1">
Name : <input type="text" name="username"/>
<br/>
Email ID : <input type="text" name="emailid"/>
<br/>
<input type="submit" value="OK"/>
</form>
Step 3 : Create First Servlet to create object and store the user input values.(in my case named "servlet1").
Enter the following code in the doGet() of the servlet.
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//creating an object named "newUser" of the class User & passing user input values as parameter to the constructor.
User newUser = new User(request.getParameter("username"),request.getParameter("emailid"));
//set a string value (eg."userData") for the object "newUser" to be able to access it from another servlet.
request.setAttribute("userData", newUser);
//passing the control to the second servlet named "servlet2" using RequestDispatcher.
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
Step 4 : Create Second Servlet to retrive object data and display it to the user.
Enter the following code in the doGet() of the servlet.
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//get the "userData" attribute from servlet1 and store it in variable "u" of the type "User" created earlier.
//also do not forget to typecast the attribute to the desired type.
User u = (User) request.getAttribute("userData");
//finally print the values using the getter methods of the User Class.
response.getWriter().println("Name : " + u.getName());
response.getWriter().println("Email : " + u.getEmail());
Finally, run the HTML or JSP page.
Saturday, September 18, 2010
Navigating from one Page or Servlet to another.
The following example shows 2 methods to navigate from one servlet to another servlet or html or jsp page.
In this example the user selects a color and accordingly goes to the respective page.
Step 1 : Create a startup HTML or JSP page.
Enter the following code in the body tag of the page.
//create a drop down list to allow user to select their choice.
<form action="servlet1">
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<input type="submit" value="Go!"/>
</form>
When User clicks the "Go!" the control of the application will pass to the servlet
Step 2 : Create a servlet (in my case named "servlet1")
Enter the following code in the doGet() method of the servlet
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//accept user input and store it into a String variable.
String option = request.getParameter("color");
//following code shows 2 methods to go to another page or servlet.
//check the value selected by the user and pass the control to the respective page.
if(option.equals("red")){
//Method 1
RequestDispatcher rd = request.getRequestDispatcher("red.html");
rd.forward(request, response);
} else if (option.equals("blue")){
//Method 2
response.sendRedirect("blue.html");
}
Step 3 : Create Result files
Enter the following code in the body tag of the "red.html" file
<h1>Red</h1>
Enter the following code in the body tag of the "blue.html" file
<h1>Blue</h1>
In this example the user selects a color and accordingly goes to the respective page.
Step 1 : Create a startup HTML or JSP page.
Enter the following code in the body tag of the page.
//create a drop down list to allow user to select their choice.
<form action="servlet1">
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<input type="submit" value="Go!"/>
</form>
When User clicks the "Go!" the control of the application will pass to the servlet
Step 2 : Create a servlet (in my case named "servlet1")
Enter the following code in the doGet() method of the servlet
//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.
//accept user input and store it into a String variable.
String option = request.getParameter("color");
//following code shows 2 methods to go to another page or servlet.
//check the value selected by the user and pass the control to the respective page.
if(option.equals("red")){
//Method 1
RequestDispatcher rd = request.getRequestDispatcher("red.html");
rd.forward(request, response);
} else if (option.equals("blue")){
//Method 2
response.sendRedirect("blue.html");
}
Step 3 : Create Result files
Enter the following code in the body tag of the "red.html" file
<h1>Red</h1>
Enter the following code in the body tag of the "blue.html" file
<h1>Blue</h1>
Friday, September 17, 2010
Multiple user selection using Checkbox
You need to allow user to select multiple values by using check boxes and storing them into an array. To do so, follow the steps given below :
//Enter the following code in the body tag of your HTML or JSP page.
<form action="servlet1">
Your Hobbies :
//assign same value to the name property of the checkboxes.
<input type="checkbox" name="hobby" value="Reading"/>Reading
<input type="checkbox" name="hobby" value="Music"/>Music
<input type="checkbox" name="hobby" value="Travelling"/>Travelling
<input type="submit" value="OK"/>
</form>
//Enter the following code in the doGet() of the your servlet (in my case "servlet1").
//assuming request as the object of the HttpServletRequest Class.
//to retrive multiple value from the same named input control (in my case checkbox) use "getParameterValues()"
//as multiple values are retrived, an array of String datatype can be used to store the values.
String[] myHobby = request.getParameterValues("hobby");
//assuming response as the object of the HttpServletResponse Class.
//to display values in the myHobby array, use for loop
for (int i = 0 ; i < myHobby.length ; i++) {
response.getWriter().println(myHobby[i]);
response.getWriter().println(" ");
}
Note : The same technique can be used to store values from multiple textboxes in to an array of String i.e. by assigning same name to the textboxes.
//Enter the following code in the body tag of your HTML or JSP page.
<form action="servlet1">
Your Hobbies :
//assign same value to the name property of the checkboxes.
<input type="checkbox" name="hobby" value="Reading"/>Reading
<input type="checkbox" name="hobby" value="Music"/>Music
<input type="checkbox" name="hobby" value="Travelling"/>Travelling
<input type="submit" value="OK"/>
</form>
//Enter the following code in the doGet() of the your servlet (in my case "servlet1").
//assuming request as the object of the HttpServletRequest Class.
//to retrive multiple value from the same named input control (in my case checkbox) use "getParameterValues()"
//as multiple values are retrived, an array of String datatype can be used to store the values.
String[] myHobby = request.getParameterValues("hobby");
//assuming response as the object of the HttpServletResponse Class.
//to display values in the myHobby array, use for loop
for (int i = 0 ; i < myHobby.length ; i++) {
response.getWriter().println(myHobby[i]);
response.getWriter().println(" ");
}
Note : The same technique can be used to store values from multiple textboxes in to an array of String i.e. by assigning same name to the textboxes.
Thursday, September 16, 2010
Calculator Servlet using Radio Buttons
Design HTML or JSP Page to accept user input :
Enter the following code snippet in the body tag:
<form action="calculation">
<input type="text" name="fnum"/>
<br/>
<input type="text" name="snum"/>
<br/>
Select Operation
<br/>
<input type="radio" name="calc" value="Add"/>Add
<input type="radio" name="calc" value="Sub"/>Subtract
<input type="radio" name="calc" value="Div"/>Divide
<input type="radio" name="calc" value="Multi"/>Multiply
<br/>
<input type="submit" value="Calculate" name="submit"/>
</form>
Retrive user input & display the output of the calcultion:
Enter the following code in the doGet() of the servlet:
//assuming request as the object of the HttpServletRequest Class.
//retriving & storing the values from the textboxes into the String Variables.
String n1 = request.getParameter("fnum");
int num1 = Integer.parseInt(n1); //Converting String into Integer Variable
String n2 = request.getParameter("snum");
int num2 = Integer.parseInt(n2); int ans=0;
//performing calculation according to the selection made from the Radio Buttons named "calc".
if(request.getParameter("calc").equals("Add"))
ans = num1+num2;
if(request.getParameter("calc").equals("Sub"))
ans = num1-num2;
if(request.getParameter("calc").equals("Div"))
ans = num1/num2;
if(request.getParameter("calc").equals("Multi"))
ans = num1*num2;
//assuming response as the object of the HttpServletResponse Class.
//displaying output to the user
response.getWriter().println(ans);
Enter the following code snippet in the body tag:
<form action="calculation">
<input type="text" name="fnum"/>
<br/>
<input type="text" name="snum"/>
<br/>
Select Operation
<br/>
<input type="radio" name="calc" value="Add"/>Add
<input type="radio" name="calc" value="Sub"/>Subtract
<input type="radio" name="calc" value="Div"/>Divide
<input type="radio" name="calc" value="Multi"/>Multiply
<br/>
<input type="submit" value="Calculate" name="submit"/>
</form>
Retrive user input & display the output of the calcultion:
Enter the following code in the doGet() of the servlet:
//assuming request as the object of the HttpServletRequest Class.
//retriving & storing the values from the textboxes into the String Variables.
String n1 = request.getParameter("fnum");
int num1 = Integer.parseInt(n1); //Converting String into Integer Variable
String n2 = request.getParameter("snum");
int num2 = Integer.parseInt(n2); int ans=0;
//performing calculation according to the selection made from the Radio Buttons named "calc".
if(request.getParameter("calc").equals("Add"))
ans = num1+num2;
if(request.getParameter("calc").equals("Sub"))
ans = num1-num2;
if(request.getParameter("calc").equals("Div"))
ans = num1/num2;
if(request.getParameter("calc").equals("Multi"))
ans = num1*num2;
//assuming response as the object of the HttpServletResponse Class.
//displaying output to the user
response.getWriter().println(ans);
Basic User Input & Output
Steps:
Enter the following code snippet in the body tag of the HTML or JSP Page.
<form action="resultservlet">//action is used to go to the servlet when user clicks OK.
Name : <input type="text" name="username"/>
Email ID : <input type="text" name="email"/>
<input type="submit" value="OK"/>
</form>
Step 2 : Retrive Information from the HTML or JSP page & Displaying it on to the Servlet..
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
//retriving & storing user input in the String Variables
String name = request.getParameter("username");
String eid = request.getParameter("email") ;
//displaying output to the user as simple text
response.getWriter().println("Hello" + name + ", Your Email ID is " + eid);
}
- Prepare HTML or JSP Page to accept user input.
- Retrive Information from the HTML or JSP page & Displaying it on to the Servlet.
Enter the following code snippet in the body tag of the HTML or JSP Page.
<form action="resultservlet">//action is used to go to the servlet when user clicks OK.
Name : <input type="text" name="username"/>
Email ID : <input type="text" name="email"/>
<input type="submit" value="OK"/>
</form>
Step 2 : Retrive Information from the HTML or JSP page & Displaying it on to the Servlet..
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
//retriving & storing user input in the String Variables
String name = request.getParameter("username");
String eid = request.getParameter("email") ;
//displaying output to the user as simple text
response.getWriter().println("Hello" + name + ", Your Email ID is " + eid);
}
Subscribe to:
Comments (Atom)