OneCompiler

exams

143
  1. Write a program in JDBC to implement Insertion operation on a database.
  2. Write a program in JDBC to implement Retrieval operation on a database.
  3. Write a program in JDBC to implement Update operation.
  4. Write a program in JDBC to implement Scrollable and Updatable ResultSet
  5. Write a program in JDBC to retrieve the database Metadata Information.
  6. Write a program to implement doGet() and doPost() methods
  7. Write a program to read request parameters from Http Request(Student Report)
  8. Write a program to implement Session handling using Cookies
  9. Write a program to implement session handling using HttpSession object
    21.Write a program to implement RequestDispatcher class methods
  10. Write a program to retrieve data from database using servlets.
  11. Write a program to demonstrate JSP Implicit objects
  12. Write a program to implement JSP Scripting elements
  13. Write a program to implement JSP use bean Action tags beans
  14. Write a program to implement include and forward jsp actions
  15. write a program to insert record in a table from JSP
  16. Write a program to develop a web application using PHP.
  1. Write a program to implement session handling using session object in PHP
  2. write a program to implement database operations in PHP
    create a table
    Insert data into a table
    retrieve data from a table

import java.sql.*;

public class StudentDBCreation {

public static void main(String[] args) {

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.jdbc.Driver");

       

        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");

       

        // Create SQL query for table creation

        String query = "CREATE TABLE student (" +

                       "rno INT PRIMARY KEY, " +

                       "name VARCHAR(20), " +

                       "branch VARCHAR(10), " +

                       "marks DOUBLE)";

       

        // Execute the query

        Statement st = con.createStatement();

        st.execute(query);

        System.out.println("Student table created successfully");

       

        // Close the connection

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

steps: write on left side page

starting Steps:

  1. Create a folder with the name “jdbc” in Desktop .

  2. Download and Copy mysql.jar file in “jdbc” folder.

  3. Start mysql database using below command

sudo /opt/lampp/lampp start

  1. Login into mysql database using below command

mysql --host=127.0.0.1 --user=root

  1. Change database to test using below command

use test;

  1. Use the below command to check for tables.

  2. Ensure the database “test” should be empty.

Procedure:

Step-1: Save the file as StudentDBCreation.java in the jdbc folder.

Step-2: Open Terminal and Change directory to jdbc folder

Step-3: Compile using below command javac StudentDBCreation.java

Step-4: Run the program using below command

java -cp :./mysql.jar StudentDBCreation

  1. Write a program in JDBC to implement Insertion operation on a database.

import java.sql.*;

import java.util.*;

public class StudentDBInsertion {

public static void main(String[] args) {

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.cj.jdbc.Driver");


        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");


        // Prepare SQL query for insertion

        String query = "INSERT INTO student VALUES (?, ?, ?, ?)";

        PreparedStatement pst = con.prepareStatement(query);


        // Input student details

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter Student details:");

        System.out.print("Enter roll number: ");

        int rno = sc.nextInt();

        System.out.print("Enter name: ");

        String name = sc.next();

        System.out.print("Enter branch: ");

        String branch = sc.next();

        System.out.print("Enter marks: ");

        double marks = sc.nextDouble();


        // Set parameters and execute the query

        pst.setInt(1, rno);

        pst.setString(2, name);

        pst.setString(3, branch);

        pst.setDouble(4, marks);

        int count = pst.executeUpdate();

        System.out.println(count + " record inserted into database");


        // Close the resources

        pst.close();

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

  1. Write a program in JDBC to implement Retrieval operation on a database.

import java.util.*;

import java.sql.*;

public class StudentDBRetrieval {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter student roll number: ");

    int rno = sc.nextInt();

   

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.cj.jdbc.Driver");


        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");


        // Prepare SQL query for retrieval

        String query = "SELECT * FROM student WHERE rno = ?";

        PreparedStatement pst = con.prepareStatement(query);

        pst.setInt(1, rno);


        // Execute the query and retrieve results

        ResultSet rs = pst.executeQuery();

        boolean result = rs.next();


        System.out.println("Student Details:\n===========");

        if (result) {

            System.out.println("Roll No\tName\tBranch\tMarks\n======\t=====\t======\t=====");

            System.out.printf("%d\t%s\t%s\t%.2f%n",

                              rs.getInt(1),

                              rs.getString(2),

                              rs.getString(3),

                              rs.getDouble(4));

        } else {

            System.out.println("Record doesn't exist");

        }


        // Close resources

        rs.close();

        pst.close();

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

  1. Write a program in JDBC to implement Update operation.

import java.sql.*;

import java.util.*;

public class StudentDBUpdate {

public static void main(String[] args) {

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.cj.jdbc.Driver");


        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");


        // Prepare SQL query for insertion

        String query = "update student set name=?,branch=?,marks=? where rno=?";

        PreparedStatement pst = con.prepareStatement(query);


        // Input student details

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter roll number which exist: ");

        int rno = sc.nextInt();

        System.out.print("Enter new name: ");

        String name = sc.next();

        System.out.print("Enter new branch: ");

        String branch = sc.next();

        System.out.print("Enter new marks: ");

        double marks = sc.nextDouble();


        // Set parameters and execute the query

       

        pst.setString(1, name);

        pst.setString(2, branch);

        pst.setDouble(3, marks);

                    pst.setInt(4, rno);

        int count = pst.executeUpdate();

        System.out.println("record updated...");


        // Close the resources

        pst.close();

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

  1. Write a program in JDBC to implement Scrollable and Updatable ResultSet

Scrollable.java

import java.util.*;

import java.sql.*;

public class Scrollable {

public static void main(String[] args) {

   

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.cj.jdbc.Driver");


        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");


        // Prepare SQL query for retrieval

        String query = "SELECT * FROM student6";

        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

       


        // Execute the query and retrieve results

        ResultSet rs = st.executeQuery(query);

       


        System.out.println("Student6 Details:\n===========");

        System.out.println("Roll No\tName\tBranch\tMarks\n======\t=====\t======\t=====");

     

        while(rs.next()) {

  System.out.printf("%d\t%s\t%s\t%.2f%n",

                              rs.getInt(1),

                              rs.getString(2),

                              rs.getString(3),

                              rs.getDouble(4));

        }

       

        System.out.println("Student2 Details from end:\n===========");

        System.out.println("Roll No\tName\tBranch\tMarks\n======\t=====\t======\t=====");

     

     // rs.beforeFirst();

        while(rs.previous()) {

  System.out.printf("%d\t%s\t%s\t%.2f%n",

                              rs.getInt(1),

                              rs.getString(2),

                              rs.getString(3),

                              rs.getDouble(4));

        }


        // Close resources

        rs.close();

        st.close();

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

Updatable.java

import java.util.*;

import java.sql.*;

public class Updatable {

public static void main(String[] args) {

   

    String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";


    try {

        // Load MySQL JDBC driver

        Class.forName("com.mysql.cj.jdbc.Driver");


        // Establish database connection

        Connection con = DriverManager.getConnection(dbUrl, user, password);

        System.out.println("Database connection successful");


        // Prepare SQL query for retrieval

        String query = "SELECT * FROM student6";

        Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

       


        // Execute the query and retrieve results

        ResultSet rs = st.executeQuery(query);

       


       

        while(rs.next()) {

                      double d=rs.getDouble(4);

                      d=d+10;

                      rs.updateDouble("marks",d);

                      rs.updateRow();

        }

       

        System.out.println("Student6 Details \n===========");

        System.out.println("Roll No\tName\tBranch\tMarks\n======\t=====\t======\t=====");

     

     rs.beforeFirst();

        while(rs.next()) {

  System.out.printf("%d\t%s\t%s\t%.2f%n",

                              rs.getInt(1),

                              rs.getString(2),

                              rs.getString(3),

                              rs.getDouble(4));

        }


        // Close resources

        rs.close();

        st.close();

        con.close();

    } catch (Exception e) {

        System.out.println("Database error: " + e.getMessage());

    }

}

}

  1. Write a program in JDBC to retrieve the database Metadata Information.

        ResultsetMetadata.java
    

import java.sql.*;

class ResultSetMetadata

{

public static void main(String[]args)

{

String dbUrl = "jdbc:mysql://localhost:3306/test";

    String user = "root";

    String password = "";

try

{

Class.forName("com.mysql.cj.jdbc.Driver");

Connection c=DriverManager.getConnection(dbUrl, user, password);

Statement st=c.createStatement();

String str="select *from student6";

ResultSet rs=st.executeQuery(str);

ResultSetMetaData md=rs.getMetaData();

    int x=md.getColumnCount();

    System.out.println("no of columns:"+x);

    for(int i=1;i<=x;i++)

    {

            System.out.print(md.getColumnLabel(i)+"   "+md.getColumnTypeName(i)+"\n");

    }

    

    rs.close();

    c.close();

}

catch(Exception e)

    {

    System.out.println(e);

    }

}

}

Steps for Tomcat Servlet Program Execution
Check for Apache Tomcat Installation
Ensure Apache Tomcat is installed on your system. Verify the installation by checking the /bin directory for startup scripts (startup.bat or startup.sh).
Identify the WebContainer
Navigate to the webapps folder within the Tomcat installation directory. This folder serves as the WebContainer for hosting applications.
Create the Web Application Directory
Inside webapps, create a folder for your web application (e.g., MyWebApp). The directory structure so far:

Tomcat/

  └── webapps/

                └── MyWebApp/

Set Up the Required Directory Structure
Inside the MyWebApp folder:
Create a WEB-INF directory.
Inside WEB-INF, create the following:
web.xml (Deployment Descriptor)
A classes folder for .class files.
Final directory structure after this step:

Tomcat/

└── webapps/

   └── MyWebApp/

            ├── WEB-INF/

                           ├── web.xml

                            └── classes/

Develop the Servlet File
In a development workspace, create a servlet file (e.g., HelloServlet.java).
After writing the servlet, compile it using the following command:
javac -cp path/to/servlet-api.jar -d path/to/WEB-INF/classes HelloServlet.java

This will place the compiled .class file in the classes directory.
Update the Deployment Descriptor (web.xml)
Define your servlet and its mapping in the web.xml file within the WEB-INF directory. Ensure the servlet is registered properly for Tomcat to recognize it.
Start Apache Tomcat
Launch Tomcat using the startup script located in the /bin directory.
7. Access Your Web Application
Open a browser and access your application using one of the following URLs:

http://ip-address:8080/MyWebApp

http://127.0.0.1:8080/MyWebApp

http://localhost:8080/MyWebApp

  1. Modify the Servlet (If Necessary)
    To make changes to the servlet:

Stop Tomcat.
Modify the servlet code.
Recompile it using the same command.
Restart Tomcat to view the updated changes.
Open a browser the view, URL =
ip-address:8080/WebApp_Folder_Name

or

127.0.0.1:8080/WebApp_Folder_Name

or

localhost:8080/WebApp_Folder_Name

If Changes to servlet are to be made - Stop Tomcat -> Modify -> Re-Compile -> Start Tomcat

  1. Write a program to implement doGet() and doPost() methods .

      import java.io.*;
    

import javax.servlet.*;

import javax.servlet.http.*;

public class Hello extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{

    PrintWriter out=res.getWriter();

    res.setContentType("text/html");

   out.println("<h2><u>COLLEGE DETAILS</u></h2>");

   out.println("<hr>");

   out.println("Name: <b>MVSR Engineering College</b><br><br>");

   out.println("Address: <b>Nadergul, Hyderabad</b><br><br>");

   out.println("Number of students intake: <b>1300</b><br><br>");

   out.println("<b>Branches offered (UG): </b>");

   out.println("<ul>  <li>CSE </li><li>CSE-AIML </li><li>CSE-IOT </li><li>CSE-DS</li>");

   out.println("<li>ECE</li><li>EEE</li><li>MECH</li><li>CIVIL</li>  </ul>");

}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{

    doGet(req,res);

}

}

web.xml

<web-app> <servlet>

<servlet-name>Ex</servlet-name>

<servlet-class>Hello</servlet-class>

</servlet> <servlet-mapping>

<servlet-name>Ex</servlet-name>

<url-pattern>/Hello</url-pattern>

</servlet-mapping> </web-app>
  1. Write a program to read request parameters from Http Request(Student Report)

home.html

<html> <BODY> <CENTER> <H1>Student Report</H1> <FORM METHOD=get ACTION="Report">
    Enter name:<INPUT TYPE="text" NAME="nm"><br>

    Marks of sub 1:<INPUT TYPE="text" NAME="t1"><br>

    Marks of sub 2:        <INPUT TYPE="text" NAME="t2"><br>

    Marks of sub 3:        <INPUT TYPE="text" NAME="t3"><br>

    Marks of sub 4:        <INPUT TYPE="text" NAME="t4"><br>

    Marks of sub 5:        <INPUT TYPE="text" NAME="t5"><br>
<INPUT TYPE="submit"> </FORM> </CENTER> </BODY> </HTML>

Report.java

mport javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Report extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            PrintWriter pw=res.getWriter();

            res.setContentType("text/html");

            String nm=req.getParameter("nm");

            int m1=Integer.parseInt(req.getParameter("t1"));

        int m2=Integer.parseInt(req.getParameter("t2"));

            int m3=Integer.parseInt(req.getParameter("t3"));

            int m4=Integer.parseInt(req.getParameter("t4"));

            int m5=Integer.parseInt(req.getParameter("t5"));


            int avg=(m1+m2+m3+m4+m5)/5;


            pw.println("<center>");

    pw.println("<h1>Student Report </h1><br>");

            pw.println("Student Name:"+nm+"<br>");

            pw.println("Average : "+avg);

            pw.println("</center>");

    }

}

web.xml

<web-app> <servlet>

<servlet-name>rep</servlet-name>

<servlet-class>Report</servlet-class>

</servlet> <servlet-mapping>

<servlet-name>rep</servlet-name>

<url-pattern>/Report</url-pattern>

</servlet-mapping> </web-app>
  1. Write a program to implement Session handling using Cookies

login.html

<HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <FORM METHOD=get ACTION="Validate">
    <CENTER>

Enter username: <INPUT TYPE="text" NAME="un"><BR>

Enter password:<INPUT TYPE="text" NAME="pwd"><BR>

<INPUT TYPE="submit">
    </CENTER>
</FORM> </BODY> </HTML>

Validate.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Validate extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            PrintWriter pw=res.getWriter();

            res.setContentType("text/html");

            String uname=req.getParameter("un");

            String pwd=req.getParameter("pwd");

            if(uname.equals("abc") && pwd.equals("xyz”))

            {

                    res.addCookie(new Cookie("login","true"));

                    System.out.println("Login Success...<br>");


            pw.println("<a href='Times'> Click here</a>");

            }

            else

                    pw.println("Login Failed..try again..");

    }

}

Times.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Times extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            PrintWriter pw=res.getWriter();

            res.setContentType("text/html");

        Cookie ck[]=req.getCookies();

            boolean b=false;

            if(ck!=null)

            for(int i=0;i<ck.length;i++)

            {

                    String s=ck[i].getName();

                    String n=ck[i].getValue();

            

                    if(s.equals("login") && n.equals("true"))

                    {

                            b=true;

                            break;

                    }

            }

            if(b)

            {

                    pw.println("<b> The time is:"+new java.util.Date()+"</b>");

            }

            else

                    pw.println("Please login to view this page..");


    }

}

web.xml

<web-app> <servlet>
<servlet-name>a</servlet-name>

<servlet-class>Validate</servlet-class>
</servlet> <servlet>
<servlet-name>ss</servlet-name>

<servlet-class>Times</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>a</servlet-name>

<url-pattern>/Validate</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>ss</servlet-name>

<url-pattern>/Times</url-pattern>
</servlet-mapping> </web-app>
  1. Write a program to implement session handling using HttpSession object

login.html

<html> <BODY> <FORM METHOD=get ACTION="First">

Enter name:<INPUT TYPE="text" NAME="nm"><br>

<INPUT TYPE="submit"> </FORM> </BODY> </HTML>

First.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class First extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            PrintWriter out=res.getWriter();

            res.setContentType("text/html");

            HttpSession s=req.getSession(true);

            String nm=req.getParameter("nm");

            s.setAttribute("nm",nm);

            out.println("<form action=Second method=get>");

            out.println("Enter ur rollno:<input type=text name=rno><br>");

            out.println("<input type=submit></form>");

    

    }

}

Second.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Second extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            PrintWriter out=res.getWriter();

            res.setContentType("text/html");

            HttpSession s=req.getSession(true);

            String rno=req.getParameter("rno");

            s.setAttribute("rno",rno);

            out.println("Click <a href=Final> Here </a> to view details");


            

    }

}

Final.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Final extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

              PrintWriter out=res.getWriter();

                    res.setContentType("text/html");

                    HttpSession s=req.getSession(true);

              String nm=(String)s.getAttribute("nm");

              String rno=(String)s.getAttribute("rno");

              out.println("Name:"+nm+"<br>"+

                               "Rol No."+rno);

    }

}

web.xml

<web-app> <servlet>
<servlet-name>Final</servlet-name>

<servlet-class>Final</servlet-class>
</servlet> <servlet>
<servlet-name>First</servlet-name>

<servlet-class>First</servlet-class>
</servlet> <servlet>
<servlet-name>Second</servlet-name>

<servlet-class>Second</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>First</servlet-name>

<url-pattern>/First</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>Second</servlet-name>

<url-pattern>/Second</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>Final</servlet-name>

<url-pattern>/Final</url-pattern>
</servlet-mapping> </web-app>

21.Write a program to implement RequestDispatcher class methods

Home.html

<html> <BODY> <CENTER> <FORM METHOD=get ACTION="Ex">

Usename: <INPUT TYPE="text" NAME="t1"><BR>

Password: <INPUT TYPE="text" NAME="t2"><BR>

<INPUT TYPE="submit"> </FORM> </CENTER> </BODY> </HTML>

Ex.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Ex extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            res.setContentType("text/html");

            PrintWriter out=res.getWriter();

            String s1=req.getParameter("t1");

            String s2=req.getParameter("t2");

            if(s1.equals("abc") && s2.equals("xyz"))

            {

                    RequestDispatcher rd=req.getRequestDispatcher("/Disp");

                    out.println("This from Ex page");

                    rd.forward(req,res);


            }

            else

                    out.println("Login Failed..");

    }

}

Disp.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class Disp extends HttpServlet

{

    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

    {

            res.setContentType("text/html");

            PrintWriter out=res.getWriter();

            out.println("welcome to my web-page..");

    }

}

web.xml

<web-app> <servlet>
<servlet-name>Disp</servlet-name>

<servlet-class>Disp</servlet-class>
</servlet> <servlet>
<servlet-name>Ex</servlet-name>

<servlet-class>Ex</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>Ex</servlet-name>

<url-pattern>/Ex</url-pattern>
</servlet-mapping> <servlet-mapping>
<servlet-name>Disp</servlet-name>

<url-pattern>/Disp</url-pattern>
</servlet-mapping> </web-app>
  1. Write a program to retrieve data from database using servlets.

    │<HTML>
    
<HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <center> <b> </b> <form action="Select" method="get">

Enter the table name: <INPUT TYPE="text" NAME="t1"><br>

<INPUT TYPE="submit"> </form> </center> </BODY> </HTML>

Select.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.sql.*;

public class Select extends GenericServlet

{

    Connection con=null;

    Statement st;

    ResultSet rs;

    public void init()

    {

            try

            {

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");

            }

            catch(Exception e)

            {

                    e.printStackTrace();

            }

    }

    public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException

    {

            res.setContentType("text/html");

            PrintWriter out=res.getWriter();


            String tname=req.getParameter("t1");

            try

            {

                    st=con.createStatement();

                    rs=st.executeQuery("select * from "+tname);

                    out.println("<center><table border=2 cellpadding=10>");

 


                    while(rs.next())

                    {

                            out.println("<tr>");

                            out.println("<td>"+rs.getString(1)+"</td>");

                            out.println("<td>"+rs.getString(2)+"</td>");

                            out.println("<td>"+rs.getString(3)+"</td>");

                            out.println("<td>"+rs.getString(4)+"</td>");

                            out.println("</tr>");

                    }

                    out.println("</table></center>");

            }

            catch(Exception e)

            {

                    out.println(e+"Table does not exist");

                    e.printStackTrace();

            }


    }

};

web.xml

<web-app> <servlet>
<servlet-name>jdbc</servlet-name>

<servlet-class>Select</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>jdbc</servlet-name>

<url-pattern>/Select</url-pattern>
</servlet-mapping> </web-app>
  1. Write a program to demonstrate JSP Implicit objects

  2. Write a program to implement JSP Scripting elements

fact.html

<html> <body> <form method= get action=fact.jsp>

<input type=text name=t1><br>

<input type= submit> </body> </html>

fact.jsp

<%

int a=Integer.parseInt(request.getParameter("t1"));

int s=1;

for(int i=1;i<=a;i++)

s=s*i;

%>

<b>The factorial is:<%=s%></b>

declaration.jsp

<%!

String s;

String greet()

{

    return ("hello:"+s);

}

%>

<%

s="john";

out.println(greet());

%>

  1. Write a program to implement JSP use bean Action tags

beans

home.html

<HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY> <CENTER> <FORM METHOD=get ACTION="Bn.jsp">
    Enter rno:<INPUT TYPE="text" NAME="rno"><BR>

    Enter student name:<INPUT TYPE="text" NAME="name"><BR>

    <INPUT TYPE="submit">
</FORM> </CENTER> </BODY> </HTML>

Bn.jsp

<jsp:useBean id="MyBean" class="ex.Student" scope="application">

<jsp:setProperty name="MyBean" property="*" />

</jsp:useBean>

welcome<jsp:getProperty name="MyBean" property="rno"/>

<jsp:getProperty name="MyBean" property="name"/>

Student.java

package ex;

public class Student

{

    int rno;

    String name;

    public void setName(String x)

    {

            name=x;

    }

public void setRno(int r)

    {

       rno=r;

    }

    public int getRno()

    {

            return rno;

    }

    public String getName()

    {

            return name;

    }

    

}

compile command:

javac -d . Student.java

  1. Write a program to implement include and forward jsp actions

include.jsp

<html> <body>

<%! String un,pwd;%>

<% un=request.getParameter("t1");

pwd=request.getParameter("t2"); %>

UserName:<%=un%><br>

Password:<%=pwd%><br>

<%if(un.equals("abc")&&pwd.equals("mvsr"))

{%><jsp:forward page="forward.jsp" />

<%}

else

{%> <center>

<font color="red">INVALID USERNAME/PASSWD</font>

<jsp:include page="valid.html" />

<%}%>

</center> </body> </html>

forward.jsp

<html> <body>

VALID USER NAME<BR>

<IMG SRC="Blue hills.jpg" WIDTH="800" HEIGHT="600" BORDER="0" ALT=""> </body> </html>
  1. write a program to insert record in a table from JSP

st.html

<HTML>
    <HEAD>

            <TITLE>

            Student Registration Form

            </TITLE>

    </HEAD>

    <form action="st.jsp" method="get">
<BODY>
            <CENTER><H2><U>Input student details and click SUBMIT button</u></h2>

            <table align="center" width"100%">

            <tr>

                    <td align="center">Enter Student Number</td>

                    <td><input type=text name=rno size=10 maxlength=5></td>

            </tr>


            <tr>

                    <td align="center">Enter Student Name</td>

                    <td><input type=text name=name size=20 maxlength=15></td>

            </tr>


            <tr>

                    <td align="center">Enter branch</td>

                    <td><input type=text name=branch size=4 maxlength=6></td>

            </tr>
<tr>
                    <td align="center">Enter marks</td>

                    <td><input type=text name=marks size=4 maxlength=6></td>

            </tr>
</table> <center><input type="submit" value="submit"></center> </BODY> </HTML>

st.jsp

<%@page import="java.sql.*"%>

<%

try

{

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

Statement st=con.createStatement();

%>

<% int rno=Integer.parseInt(request.getParameter("rno"));

String sname=request.getParameter("name");

String b=request.getParameter("branch");

double m=Double.parseDouble(request.getParameter("marks"));

%>

<%int res=st.executeUpdate("INSERT INTO student VALUES("+ rno +", '"+ sname+"','"+ b+"','"+m+"')") ;%>

<html>
            <head>

                    <title>

                               My fifth jsp

                    </title>

            </head>


            <body>                

                            <center><h3>

                       

                       <%

                       if(res==0)

                       {

                               %>

                               Problem in inserting record

                               <%

                            }

                            else

                            {

                                     %>

                                       Sucessfully Inserted

                                      <%

                               }

                                            %>

            </body>

    </html>

                                       <%con.close();

                                            }

            

    catch(Exception e)

    {

            e.printStackTrace();

    }

%>

  1. Write a program to develop a web application using PHP.

index.html

<html> <head>
<title>Product Billing</title>
</head> <body>
<h1>Product Billing Form</h1>

<form action="process.php" method="POST">

    Product Name:

    <input type="text" id="product" name="product" required><br><br>


    Price per Unit:

    <input type="number" id="price" name="price" required><br><br>


    Quantity:

    <input type="number" id="quantity" name="quantity" required><br><br>


    <input type="submit"><br>

</form>
</body> </html>

process.php

<?php // Retrieve input from the form $product = $_POST["product"]; $price = floatval($_POST["price"]); $quantity = intval($_POST["quantity"]); // Validate inputs if (!empty($product) && $price > 0 && $quantity > 0) { // Calculate total bill $total = $price * $quantity; } else { $error = "Please enter valid product details."; } ?> <html> <head>
<title>Billing Details</title>
</head> <body>
<?php if (isset($error)) { ?>  

    <!--   if error exists then isset returns true -->

    <h1>Error</h1>

    <p><?= $error ?></p>

<?php } else  {  ?>

    <h1>Billing Details</h1>

    <p><strong>Product:</strong> <?= $product ?></p>

    <p><strong>Price per Unit:</strong> <?= $price ?></p>

    <p><strong>Quantity:</strong> <?= $quantity ?></p>

    <p><strong>Total Bill:</strong> <?= $total ?></p>

<?php } ?>
</body> </html>
  1. Write a program to implement session handling using session object in PHP

index.html

<body> <h2>Login</h2> <form method=post action=check.php>

Username: <input ype=text name="un"><br><br>

Password: <input ype=text name="pwd"><br><br>

<input type=submit> </body> </html>

check.php

<?php session_start(); ?> <html> <body> <?php $un=$_POST["un"]; $pwd=$_POST["pwd"]; if($un=="admin" &&$pwd=="admin") { echo "Login sucess<br>"; $_SESSION["bgcolor"]="green"; ?>
     <a href="time.php"> Check time </a>


     <?php

}

else

{

echo "invalid login<br>";

echo "<a href='index.html'>back to login</a>";

}

?>

<html>

time.php

<?php session_start(); ?> <html> <?php $clr=$_SESSION["bgcolor"]; $d=date('d-m-Y'); ?> <body style="background-color: <?=($clr) ?>">

The current date is: <?=$d?>

</body>
  1. write a program to implement database operations in PHP

create a table

<?php $host="localhost:3306"; $uname="root"; $pwd=""; $db="test"; $con=mysqli_connect($host,$uname,$pwd,$db); if(isset($con)) echo "Connected to database sucessfully"; else die("Error"); $qry="create table emp(eno int(5), ename varchar(20), sal float(6,2))"; if(mysqli_query($con, $qry)) echo "Table created"; else echo "Error"; ?>

Insert data into a table

<?php $host="localhost:3306"; $uname="root"; $pwd=""; $db="test"; $con=mysqli_connect($host,$uname,$pwd,$db); if(isset($con)) echo "Connected to database sucessfully<br>"; else die("Error"); $qry="insert into emp values(101,'john',4500.0)"; if(mysqli_query($con, $qry)) echo "Row inserted"; else echo "Error"; ?>

retrieve data from a table

<?php $host="localhost:3306"; $uname="root"; $pwd=""; $db="test"; $con=mysqli_connect($host,$uname,$pwd,$db); if(isset($con)) echo "Connected to database sucessfully<br>"; else die("Error"); $qry="select * from student"; $rs=mysqli_query($con, $qry); if(mysqli_num_rows($rs)>0) { while($row=mysqli_fetch_assoc($rs)) echo $row["rno"]." ".$row["name"]." ".$row["branch"]." ".$row["marks"]."<br>"; } ?>