Hello everyone,
I am new to this forum and help will really be appreciated.hope that you'll will help me.

I am working on a project using jsp,servlet,ms-access as database.
I have to prepare a login page which should be validated with the database and i have done the coding for that using html and jsp.But i have involved the database connection and validation in jsp as well. I want the db connection and validation to be done in servlet ,so i have attached the servlet file,but how should i connect to the servlet using jsp and what should i write in jsp page so that my main page is displayed.
kindly help.

Recommended Answers

All 26 Replies

You misunderstand the idea of JSP-servlet relation. Bellow is something you should do (I did not compile it so it may not be 100% correct)

Simple html login screen

<html>
<head>
<title>Ask for Names Example</titls>
</head>
<body bgcolor="LightSkyBlue">
<h3 align="center">Login event with use of the POST method</h3>
<form action="LoginEvent" method="post">
<p align="center">Username: <input type="text" site="20" name="username">
&nbsp;&nbsp;&nbsp;
Password: <input type="text" size="20" name="password"></p>
<p align="center"><input type="submit" value="Submit"></p>
</form>
</body>
</html>

Note: The form parameter action uses LoginEvent servlet that has been mapped through web.xml.

servlet to get data and connect to db

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FrontController extends HttpServlet
{
	Connection conn;
	Statement stmt;
	
	public void init() throws ServletException
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		catch (Exception ex)
		{
			System.out.println("Exception is : " + ex.toString() );
		}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		boolean bValid = true;
		HttpSession session = request.getSession();
		
		if( (name.lenght() == 0) || (password.length() == ))
		{
			bValid = false;
		}
		
		if(bValid) // submited data are OK
		{
			try
			{
				conn = DriverManager.getConnection("jdbc:mysql://localhost/" 
														+ "database_name?user=your_username&password=your_password");
				stmt = conn.createStatement();
			}
			catch(SQLException ex)
			{
				System.out.println("SQLException : " + ex.getMessage() );
			}
			
			/**
			 * DO THE REST OF DATABASE REQUESTS
			 *
			 * DO NOT FORGET TO CLOSE CONNECTION
			 *
			 **/			
		}
		
		if(bValid)
		{
			// YOU MAY WANT TO CREATE SOME SESSIONS HERE
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/accept.jsp");
			dispatcher.forward(request, response);
		}
		else
		{
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/reject.jsp");
			dispatcher.forward(request, response);
		}
	}
}

thank you for your help,
I still have a query
If i use the servlet and i compile it ,then i would get the db connectivity as well as the data validation done but i have a jsp page also in which i want to get the parameters from servlet such as the userid and password so that i move on to the next jsp page with reference to that same userdetails.Apart from that i should be creating a bean or a jsp page to forward the servlet class to another page in case the connectivity is required there also to fetch data.
thanks in advance.please suggest a remedy.

Yes, if the results from database confirm is is registered user and he/she is authorized then you should create bean. You can store username and password there, however storing unique user ID in bean would be better solution

Thanks a lot for the suggestion given and it is highly appreciated.
As you said that the unique ID has to be made, but please suggest me that when i make a bean after validation done in servlet i should be using the getPropety or the setProperty in the bean so that the user get to see the new page related to its own details and move forward with various other activities.I am pasting the code over here for the bean.please have a look at it and let me know what is to be done for the particular scenario.If possible send me the code for the bean.Thanks in advance

<%@ page language="java"%>

<[B]jsp:useBean [/B][B]id[/B]="BA" [B]scope[/B]="application" [B]class[/B]="Helloserv"/>
<[B]jsp:setProperty [/B][B]name[/B]="mybean"[B] property[/B]="username" [B]param[/B]="username"/>
<[B]jsp:setProperty [/B][B]name[/B]="mybean" [B]property[/B]="password" [B]param[/B]="password"/>

         or
<[B]jsp:getProperty [/B][B]name[/B]="mybean" [B]property[/B]="username"/>
<[B]jsp:getProperty [/B][B]name[/B]="mybean" [B]property[/B]="password"/>

Yes to get properties in JSP as follows

<%@ page language="java"%>

<jsp:useBean id="mybean" scope="application" class="Helloserv"/>
<jsp:getProperty name="mybean" property="username"/>
<jsp:getProperty name="mybean" property="password"/>

In my other post I marked place where you create session, that is basically where you store data in the bean and past it on the JSPs following after that

session.setAttribute( "mybean", mybean );

Thanks for the suggestion.
I am trying doing this in servlet and hope it works well.But i just want to make the concept clear before i proceed further, that in servlet we have set the attribute as mybean ok.so that will be like i am storing the details such as username and password for further activities right.And the code of the bean that i have stated before is the same using getProperty but what is the proper coding to be done in a bean for the getting the attribute ("mybean") or else i just carry on with the same code stated for bean and in that itself i should write the html code for the main page which is to be displayed after user login.
Thanks in advance.help will really be appreciated.

JavaBeans components, or beans, are reusable software components that follow simple naming and design conventions so they present a standard interface to other beans, programs, and tools.

Simply put bean is just storage class something like this one, which does use setter and getter methods for attributes to be stored or retrieved

package bean;

public class MyBean
{
	private String username;
	private String password;
	
	public MyBean() {}
	
	public void setUsername(String str)
	{
		username = str;
	}
	
	public String getUsername() { return username;}
	
	public void setPassword(String str)
	{
		password = str;
	}
	
	public String getPassword() { return password;}
}

and the above approaches will help you retrieve or set data for your bean

Thanks for the suggestion.
The getter and setter methods is very much clear to me now.But i am facing a problem in placing the files such as jsp,class files in particular folders as well as connecting each of them .I am using j2sdkee1.2.1 and my db is ms-access
now my first page is test.jsp which is the login page fine.Second is the Helloserv.java file which is doing the db connectivity and validation of my login page.The third is the login.jsp which is a bean.
so i should do it in this manner that i should call the bean from the first page(test.jsp)i.e the login page and then from bean i should call the servlet class from where,using RequestDispatcher it should direct me to the main page.
or else in a different way. i am placing all the jsp files in my C:\j2sdkee1.2.1\public_html
and all the class files in C:\j2sdkee1.2.1\lib\classes. one more thing i have never used ms-access as db,i have worked only on ms-sql server, so just have a look whether i am giving a proper db connection.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     	 conn =  DriverManager.getConnection("jdbc:odbc:employee_dat");
	System.out.println("Connection established");
	 stmt = conn.createStatement();

I am very much thankful to u for the help that you have provided to me.
Thanks in advice.Help would be highly appreciated.

What version of Tomcat server you have?
Why don't you use MySQL database which is free to use, better then MS Access in my opinion?
Why do you use j2sdkee1.2.1 when there are newer version of Java?

hi,
I have to install it .let me upgrade with the latest version as suggested then we can go ahead with the queries.I have never installed mysql because i had seen that there is mysql server,mysql enterprise,etc .so what exactly i have to download and where can i find it free.same thing goes for java also.For now thanks .
see you.

hi,
I am installing mysql server and over there it has several options for windows i.e
2.4.8.1. Choosing An Installation Package
2.4.8.2. Installing MySQL with the Automated Installer
2.4.8.3. Using the MySQL Installation Wizard
2.4.8.4. MySQL Server Configuration Wizard
2.4.8.5. Installing MySQL from a Noinstall Zip Archive
2.4.8.6. Extracting the Install Archive
2.4.8.7. Creating an Option File
2.4.8.8. Selecting a MySQL Server Type
2.4.8.9. Starting the Server for the First Time
2.4.8.10. Starting MySQL from the Windows Command Line
2.4.8.11. Starting MySQL as a Windows Service
2.4.8.12. Testing The MySQL Installation
2.4.8.13. Troubleshooting a MySQL Installation Under Windows
2.4.8.14. Upgrading MySQL on Windows
2.4.8.15. MySQL on Windows Compared to MySQL on Unix
now which one to choose and go ahead .after the complete installation of java and db,do i have to set any environment variables or else any other setting to be done.for that please assist me.thank you.

Ehmm, what exactly did you downloaded?

hi,
That was just a mistake from my side . Till now i have downloaded tomcat 6.0 and continuing to download mysql community server and JDK5.0 as well.so till now working fine.see u back after the download is over because assistance is still required.
thank you.
take care

You misunderstand the idea of JSP-servlet relation. Bellow is something you should do (I did not compile it so it may not be 100% correct)

Simple html login screen

<html>
<head>
<title>Ask for Names Example</titls>
</head>
<body bgcolor="LightSkyBlue">
<h3 align="center">Login event with use of the POST method</h3>
<form action="LoginEvent" method="post">
<p align="center">Username: <input type="text" site="20" name="username">
&nbsp;&nbsp;&nbsp;
Password: <input type="text" size="20" name="password"></p>
<p align="center"><input type="submit" value="Submit"></p>
</form>
</body>
</html>

Note: The form parameter action uses LoginEvent servlet that has been mapped through web.xml.

servlet to get data and connect to db

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FrontController extends HttpServlet
{
	Connection conn;
	Statement stmt;
	
	public void init() throws ServletException
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		catch (Exception ex)
		{
			System.out.println("Exception is : " + ex.toString() );
		}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		boolean bValid = true;
		HttpSession session = request.getSession();
		
		if( (name.lenght() == 0) || (password.length() == ))
		{
			bValid = false;
		}
		
		if(bValid) // submited data are OK
		{
			try
			{
				conn = DriverManager.getConnection("jdbc:mysql://localhost/" 
														+ "database_name?user=your_username&password=your_password");
				stmt = conn.createStatement();
			}
			catch(SQLException ex)
			{
				System.out.println("SQLException : " + ex.getMessage() );
			}
			
			/**
			 * DO THE REST OF DATABASE REQUESTS
			 *
			 * DO NOT FORGET TO CLOSE CONNECTION
			 *
			 **/			
		}
		
		if(bValid)
		{
			// YOU MAY WANT TO CREATE SOME SESSIONS HERE
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/accept.jsp");
			dispatcher.forward(request, response);
		}
		else
		{
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/reject.jsp");
			dispatcher.forward(request, response);
		}
	}
}

does this get written directly to the Dreamweaver page or should it be different,
does the system.out.println() print on the browser and what about a mailto link can you help me with that?
i am sorry if these questions seem absurd but i am new with JSP and really need help for a major project
thankyou

@does this get written directly to the Dreamweaver page or should it be different
You do not want to use Dreamweaver for Java web development. NetBeans is more reasonable

@does the system.out.println() print on the browser
No that is system message that will displayed if anything happens while Tomcat server running command prompt

@what about a mailto link can you help me with that
mailto is a basic of HTML that you should already know, if not visit w3schools.com website

@i am sorry if these questions seem absurd but i am new with JSP and really need help for a major project
Do you have any Java programming experiences?

PS: Hijacking other people thread is not a nice thing to do...

@does this get written directly to the Dreamweaver page or should it be different
You do not want to use Dreamweaver for Java web development. NetBeans is more reasonable

@does the system.out.println() print on the browser
No that is system message that will displayed if anything happens while Tomcat server running command prompt

@what about a mailto link can you help me with that
mailto is a basic of HTML that you should already know, if not visit w3schools.com website

@i am sorry if these questions seem absurd but i am new with JSP and really need help for a major project
Do you have any Java programming experiences?

PS: Hijacking other people thread is not a nice thing to do...

how can i say this...
this is an assignment by my web development lecturer which has to be done in dreamweaver as a jsp page which re-validates what has been entered in the previous page and if it is correct it has to print a mailto link on the page otherwise it displays an error message, the lectures are missing those points so i am going for any help i can get

Do you have Tomcat on your pc or access to Tomcat based web hosting?

Do you have Tomcat on your pc or access to Tomcat based web hosting?

no...
do you know where to get it from??
thanks a lot man

Okay I've found a couple of helpful tutorials.. Just one question: how can I (from within the JSP code) set the window location to run a "mailto:..." command?

thank you and one last thing is there a way of creating error messages instead of error pages?

Yes with sessions something like this

<% String e = (String) session.getAttribute( "error" );
if ( e != null ) 
  out.print( e ); 
%>

where the "error" string either been initialized or left intentionally empty depending for example on the outcome of the form validation

does this work with JSP???
i also found error.system.error

can someone check this code for me and tell me if anything is wrong with it
the first is an HTML page which takes you to the second JSP page i want to make sure the JSP works properly

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Submission form</title>
<style type="text/css">
body{
	font-family: Verdana;
	font-size: 13px;
}
.error{
	font-size: 9px;
	font-family: Arial;
	color: #FF0000;
	font-weight: bold;
}
#ermail,
#ername,
#erpass1,
#erpass2
{
		display: none;
}
</style>

<script type="text/javascript">
function onSub()
{
var at=document.getElementById("email").value.indexOf("@");
var name=document.getElementById("fname").value;

var pass1=document.getElementById("pass1").value;
var pass2=document.getElementById("pass2").value;

///////////////////////////////////////////////////////
allowSubmit="true";
if (parseInt(pass1,10)!=pass1)
{
 alert("The student number must only contain numerical digits.");
 allowSubmit="false";
}
if (name.length<3)
 {
 document.getElementById("ername").style.display="block";
 allowSubmit="false";
 }
else
 {
  document.getElementById("ername").style.display="none";
 }
if (at==-1) 
 {
 document.getElementById("ermail").style.display="block";
 allowSubmit="false";
 }
else
 {
  document.getElementById("ermail").style.display="none";
 }
if (pass1.length!=8)
{
 alert("The student number must be exactly 8 digits.");
 allowSubmit="false";
}
if (pass1 == "")
{
 document.getElementById("erpass1").style.display="block";
 allowSubmit="false";
}
else
 {
  document.getElementById("erpass1").style.display="none";
 }

if (pass1 != pass2)
{
 document.getElementById("erpass2").style.display="block";
 allowSubmit="false";
}
else
 {
  document.getElementById("erpass2").style.display="none";
 }

if (allowSubmit=="false")
 {
 return false;
 }
}
</script>
</head>

<body>
<form method="post" action="Submit.jsp" onsubmit="return onSub()">
<table cellspacing="2" cellpadding="0" border="0">
	<tr>
		<td style="width: 180px;">Name</td>
		<td style="width: 180px;"><input type="text" id="fname" size="30" name="name"/></td>
		<td class="error" id="ername">The name must be longer than 2 characters.</td>	
	</tr>
	<tr>
		<td>E-mail</td>
		<td><input type="text" id="email" size="30" name="emailadd"/></td>
		<td class="error" id="ermail">You must enter a valid e-mail address.</td>	
	</tr>
	<tr>
		<td>Student Number</td>
		<td><input type="password" id="pass1" size="30" name="studentno1"/></td>
		<td class="error" id="erpass1">A Student Number must be entered; this is a required feild.</td>	
	</tr>
	</tr>
	<tr>
		<td>Re-enter Student Number</td>
		<td><input type="password" id="pass2" size="30" name="studentno2"/></td>
		<td class="error" id="erpass2">Entered Student Numbetrs do not match.</td>	
	</tr>
	<tr>
	 <td colspan="2" style="text-align: center;"><input name="Submit" type="submit" id="Submit" value="Submit" /></td>
	 <td></td>
	</tr>
</table>
</form>
</body>
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<% import java.io.*;
import java.util.*;


public class Validation

{
	public Validation()
    {
    try
        {
    String name = request.getParameter("name");
    String emailadd = request.getParameter("emailadd");
    int studentno1 = request.getParameter("studentno1");
    int studentno2 = request.getParameter("studentno2");
    	        	if (name.length >= 3 && studentno1.length = 8 && studentno1 = studentno2)
	            {
    	        	<ct:mail to= emailadd>
					Student Name: <%=request.getParameter("name")%>
                    Student Number: <%=request.getParameter(""+"studentno1")%>
                    </ct:mail>
                    <ct:mail to="info@scocietybrton.co.uk">

                    E-mail Address: <%=request.getParameter("email"%>
					Student Name: <%=request.getParameter("name")%>
                    Student Number: <%=request.getParameter(""+"studentno1")%>

                    </ct:mail>
        	    }
                else
                {
                	error.system.error= data inputed is incorrect.
                }
        }
        catch 
        {
        	error.system.error= data inputed is incorrect.
        }
    }
        
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Subittion Page</title>


</head>
<body>
Your rquest has been processed.
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.