Home Jsp JSP forward
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JSP forward

Advertisement
This section illustrates you how you can use JSP forward action to forward to servlet.

JSP forward

     

This section illustrates you how you can use JSP forward action to forward to servlet.

Create jsp Page: To create a jsp page,  following steps are to be  performed.

1) Creating a web  application  folder(servlets-examples) which  should have  some logical or meaningful name. This folder should be created  under the webapps folder.  The  path will be C:\apache tomcat\webapps\ servlets-examples.

2) Create a new folder (jsp) under the web application folder.

3) Following are the tag libraries that you will have to  use in the jsp page.

a) Directive - Here  you  can import packages, define error handling pages  or declare the session information. Syntax:   <%@ directive attribute="value".

b) Declarative  - Here you can embed java  code.  Variables and functions are defined here.. Syntax :<%! java code %>

c) Scriplets - Here you can embed java code. Syntax : <%  java code %>. 

d) Expressions - Here whatever you will write, displayed as a String. Syntax :  <%="Welcome"%>

4) Copy  the  jsp page under the web application folder.

5) Run  the Tomcat Server 

6) Open the web browser and type the url.

  http://localhost:8080/servlets-examples/jsp/page.jsp

Now following example illustrates you how to use servlet with jsp. There are four files 

1) jspToServlet.jsp
2) MyServlet.java
3) page.jsp
4) output.jsp 

At first, run the jspToServlet.jsp  page.  This jsp page calls the servlet  MyServlet.java by the expression <jsp:forward page="/servlet_name">. This servlet then calls the jsp page page.jsp and you will see a form is displayed on  the browser.  It contains username and password. As you will enter the username and password and submit it, a welcome message will appear on the browser which comes from the output.jsp.

Here is the code of  jspToServlet.jsp  

<%@page contentType="text/html" import="java.util.*" %> 

<html>

<body>
<jsp:forward page="/MyServlet"/>
</body>

</html>

This will call  the servlet MyServlet.java.

Here is the code of MyServlet:

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet { 

public void doGet (HttpServletRequest request,HttpServletResponse response) {

try {
request.setAttribute ("servletName", "MyServlet");
getServletConfig().getServletContext().getRequestDispatcher("/jsp/page.jsp").forward(request, response);

catch (Exception ex) {
ex.printStackTrace ();
}
}
}

This servlet then calls jsp page page.jsp that contains username and  password.

Here is the code of page.jsp

<%@page contentType="text/html" import="java.util.*" %> 
<html>
<body><head><title>Use Servlet with Jsp</title></head> 
<form action="output.jsp" method="post">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>User Name: </td>
<td><input type="text" size="20" name="txtUserName" />
</tr>
<tr>
<td>Password: </td>
<td><input type="password" size="20" name="txtPassword" />
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Submit" name="page" /></td>
</tr>
</table>
</form>

</body>
</html>

Output will be displayed as

Now here is the code of output.jsp

<%@page language="java" %>
<%
String userName = request.getParameter("txtUserName");
String password = request.getParameter("txtPassword");
if(userName == null)
userName = "";
if(password == null)
password = "";
if(!userName.equals("") && !password.equals("")){
session.setAttribute("SessionUser", userName);
session.setAttribute("SessionPassword", password);
out.println("Welcome " + userName + "!");
out.println("<br/><a href=passValue.jsp> Go Back.</a>");

}
else if(userName.equals("")){
out.println("<font color=red><b>User name is required.</b></font>");
out.println("<br/><a href=passValue.jsp>Go back!</a>");
}
else if(password.equals("")){
out.println("<font color=red><b>Password is required.</b></font>");
out.println("<br/><a href=passValue.jsp>Go back!</a>");
}
%>

After entering username and password, following output will be displayed.

 Download Source Code

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 8, 2008

Ask Questions?    Discuss: JSP forward  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
ashwini
October 3, 2011
Servlet jsp information

In first frame it displays the rows of a table,it as radio button for each row,the fields in column it includes id,name,location.when i click radio button in one frame the contents should be displayed in another frame when fetched from database,it should display each field of row in the form of text box in second frame. please help me out
ramprabhu
February 8, 2012
answer

package project.controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import project.bean.*; import project.model.*; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("hi"); ProjectBean bean=new ProjectBean(); if(request.getParameter("action").equals("create")) { bean.setStudentname(request.getParameter("studentname")); System.out.println(request.getParameter("studentname")); bean.setDate(request.getParameter("date")); bean.setMark(Integer.parseInt(request.getParameter("mark"))); //System.out.println(+bean.getMark()); ProjectModel model=new ProjectModel(); try { bean=model.daoCallingMethod(bean); System.out.println("rohini"); request.setAttribute("message","Account created successfully"); RequestDispatcher redirect = getServletContext().getRequestDispatcher("/jsp/UI_page.jsp"); redirect.forward(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(request.getParameter("action").equals("read")) { System.out.println("hello"); String studentname=request.getParameter("studentname"); System.out.println(studentname); ReadModel read=new ReadModel(); try { //request.setAttribute(studentname, bean); bean=read.readDaoCalling(studentname); request.setAttribute("studentname", bean); RequestDispatcher redirect = getServletContext().getRequestDispatcher("/jsp/display.jsp"); redirect.forward(request, response); System.out.println(studentname); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(request.getParameter("action").equals("delete")) { bean.setStudentname(request.getParameter("studentname")); DeleteModel delete=new DeleteModel(); try { delete.deleteDaoCalling(bean); request.setAttribute("message","Deleted successfully"); RequestDispatcher redirect = getServletContext().getRequestDispatcher("/jsp/deletedisplay.jsp"); redirect.forward(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if(request.getParameter("action").equals("update")) { String studentname=request.getParameter("studentname"); System.out.println(studentname); request.setAttribute("studentname", bean); RequestDispatcher redirect = getServletContext().getRequestDispatcher("/jsp/updatepage.jsp"); redirect.forward(request, response); } else if(request.getParameter("action").equals("up")) { bean.setStudentname(request.getParameter("studentname")); System.out.println(request.getParameter("studentname")); bean.setDate(request.getParameter("date")); bean.setMark(Integer.parseInt(request.getParameter("mark"))); UpdateModel updatemodel=new UpdateModel(); try { updatemodel.updateDaoCalling(bean); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package project.dao; import project.bean.*; import java.sql.*; public class DaoClass extends Connections { public ProjectBean daoMethod(ProjectBean bean) throws ClassNotFoundException, SQLException { Connection connection=getConnection(); Statement statement=connection.createStatement(); System.out.println("insert into studentproject values('"+bean.getStudentname()+"','"+bean.getDate()+"',"+bean.getMark()+")"); System.out.println("daoclass"); ResultSet rs=statement.executeQuery("insert into studentproject values('"+bean.getStudentname()+"','"+bean.getDate()+"',"+bean.getMark()+")"); return bean; } public ProjectBean readDaoMethod(String studentname) throws ClassNotFoundException, SQLException { Connection connection=getConnection(); Statement statement=connection.createStatement(); ProjectBean bean=new ProjectBean(); System.out.println("select * from studentproject where studentname='"+studentname+"'"); ResultSet rs1=statement.executeQuery("select * from studentproject where studentname='"+studentname+"'"); while(rs1.next()) { bean.setStudentname(rs1.getString("studentname")); bean.setDate(rs1.getString("Applydate")); bean.setMark(rs1.getInt("mark")); } return bean; } public int deleteDaoMethod(ProjectBean bean) throws ClassNotFoundException, SQLException { Connection connection=getConnection(); Statement statement=connection.createStatement(); ResultSet rs2=statement.executeQuery("delete from studentproject where studentname='"+bean.getStudentname()+"'"); return 1; } public void updateDaoMethod(ProjectBean bean) throws ClassNotFoundException, SQLException { Connection connection=getConnection(); Statement statement=connection.createStatement(); int result =statement.executeUpdate("update studentproject set studentname='"+bean.getStudentname()+"',applydate='"+bean.getDate()+"',mark="+bean.getMark()+""); if(result==1) { System.out.println("data updated"); } else { System.out.println("data not updated"); } } } package project.dao; import java.sql.*; /*class for connections*/ public class Connections { Connection con=null; /*method for open connection*/ public Connection getConnection() throws ClassNotFoundException, SQLException { /* * creating connection */ Class.forName("oracle.jdbc.OracleDriver"); String url= "jdbc:oracle:thin:@172.24.137.30:1521:ora10g"; con=DriverManager.getConnection(url,"e543820","REaqbsude"); return con; } /*method for close connection*/ public void closeConnection(Connection con) throws SQLException { /* * closing connection */ con.close(); } } CREATE MODEL: package project.model; import java.sql.SQLException; import project.bean.*; import project.dao.*; public class ProjectModel { public ProjectBean daoCallingMethod(ProjectBean bean) throws ClassNotFoundException, SQLException { DaoClass dao=new DaoClass(); bean=dao.daoMethod(bean); return bean; } } READ MODEL: package project.model; import java.sql.SQLException; import project.bean.*; import project.dao.DaoClass; public class ReadModel { public ProjectBean readDaoCalling(String studentname) throws ClassNotFoundException, SQLException { DaoClass dao=new DaoClass(); ProjectBean bean=new ProjectBean(); bean=dao.readDaoMethod(studentname); return bean; } } DELETE MODEL: package project.model; import java.sql.SQLException; import project.bean.ProjectBean; import project.dao.DaoClass; public class DeleteModel { public int deleteDaoCalling(ProjectBean bean) throws ClassNotFoundException, SQLException { DaoClass dao=new DaoClass(); int result=dao.deleteDaoMethod(bean); return result; } } package project.model; import java.sql.SQLException; import project.bean.*; import project.dao.DaoClass; public class UpdateModel { public void updateDaoCalling(ProjectBean bean) throws ClassNotFoundException, SQLException { DaoClass dao=new DaoClass(); dao.updateDaoMethod(bean); } }
DMCA.com