JSP and Servlet are server-side technology used for creating web applications and to create dynamic web content. We will see JSP vs Servlet later as we proceed further.

What will you learn?

  1. JSP Introduction
  2. JSP (Java Server Page) to display/print Tribhuvan University 10 times.
  3. JSP and Servlet program | Calculate simple interest and do necessary validation.
  4. Write a Servlet program to display Tribhuvan University 10 times.
  5. JSP vs Servlet
  6. Insert data in the database using JSP and Servlet

JSP Introduction

  • JSP is a server-side technology that allows the development of dynamic, platform-independent manners for constructing Web-based applications.
  • JSP provides access to the entire Java API family, including the JDBC API for connecting enterprise databases.
  • Dynamic web pages are created using it.
  • JSP is an extended version of a servlet.

JSP (Java Server Page) to display/print Tribhuvan University 10 times

<%@ page language="java" contentType="text/html"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP program</title>
</head>
<body>

 <%
 String msg="Tribhuvan University";
 for (int i=0;i<10;i++){
	 out.print(msg+"<br>");
 }
 %>

</body>
</html>

Related Questions:

  • Write a simple JSP program to display “Lalitpur, Nepal” 10 times.
  • Write a simple JSP program to display “Kathmandu, Nepal” 10 times.
  • Write a simple JSP file to display 'IOST' 20 times.
  • What is JSP? Discuss with a suitable example

JSP and Servlet program | Calculate simple interest and do necessary validation

Create a dynamic project that will accept the principle, rate, and time from the JSP page and use the Servlet to execute a simple interest calculation. In another response JSP page, pass the relevant result. Do necessary validation where necessary.

Note:

  • JSP (Java Server Page) is a technology that runs on the server.
  • It is used for creating web applications.
  • It is used to generate dynamic web content.
  • JSP is an extended version of the servlet.
  • Servlet is a pure Java code whereas JSP is a html-based code.
  • Servlet is faster than JSP.
  • JSP coding is easy than Servlet.

value.jsp

<%@ page language="java" contentType="text/html">
<!DOCTYPE html>
<html>
<head>
<title>Provide values</title>
<script>
	function validateForm(){
		var p = document.myForm.principle.value;
		var t = document.myForm.time.value;
		var r = document.myForm.rate.value;
		if(p!="" && t!="" && r!="") {
			var numbers = /^[0-9]+$/;
		    if(!(p.match(numbers) && t.match(numbers) && r.match(numbers))){
		    	alert("Please provide only integer values");
		    	return false;
		    }
		}
		else{
			alert("Textfield can't be empty");
			return false;
		}	
	}
</script>
</head>
<body>
	<form name="myForm" action="Servletpage" 
	onsubmit="return validateForm()" method="get">
		<h1>Principle: <input type="text" name="principle"><br>
		Rate: <input type="text" name="rate" ><br>
		Time in year: <input type="text" name="time" ><br><br>
		<input type="submit" value="Submit">
		</h1>
	</form>
</body>
</html>

Servletpage.java:

package ishwar;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/Servletpage")
public class Servletpage extends HttpServlet {
    private static final long serialVersionUID = 1 L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        int principle = Integer.parseInt(request.getParameter("principle"));
        int time = Integer.parseInt(request.getParameter("time"));
        int rate = Integer.parseInt(request.getParameter("rate"));
        float SI = ((principle * time * rate) / (float) 100);
        request.setAttribute("Result", SI);
        request.getRequestDispatcher("Result.jsp").forward(request, response);

        /*
         * If we pass certain value from jsp to another jsp page:
         *  <% int principle = Integer.parseInt(request.getParameter("principle")) %>;
         */
    }
}

Result.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Interest</title>
</head>
<body>
	<h1>Result: </h1><br>
	<h2>Simple Interest =  ${Result} </h2>
</body>
</html>

Write a Servlet program to display Tribhuvan University 10 times

Printing any message with Servlet is the same as printing that message with HTML, with a few small differences.

A servlet is a technology that is used to create a web application. Servlet works on the server side.

The four steps of the Servlet life cycle are as follows:

  • Loading a Servlet
  • Initializing the Servlet
  • Request handling
  • Destroying the Servlet
package myprogram;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/display_msg")
public class display_msg extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//opening
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		//To print Tribhuvan University 10 times using Servlet
		out.println("<html><body>");
		for (int i=0;i<10;i++) {
			out.println("Tribhuvan University </br>");
		}
		
		//Note: to print just Tribhuvan University, no need to write for loop
		//just write:
		out.println("Tribhuvan University")
		
		//closing
		out.println("</body></html>");
				
	}

}

JSP vs Servlet | Insert data in the database using JSP and Servlet

How can we insert data in the database using JSP (Java Server Page) and Servlet?

JSP vs Servlet

What is JSP?

  • JSP --> Java Server Page
  • server-side technology
  • used for creating a web application
  • used to create dynamic web content

What is a servlet?

  • server-side technology
  • used for creating a web application
  • used to create dynamic web content

Are JSP and Servlet the same term then?

No, here is the difference:

S.N. Servlet JSP
a.       A servlet is a Java code. JSP is a html-based code.
b.       Modification in servlet is a time-consuming task because it includes reloading, recompiling, and restarting the server. JSP is easy to code because it is nothing but a html code.
c.        Servlet is faster than JSP. JSP is slower than servlet because the first step in the JSP lifecycle is the translation of JSP to Java code and then compilation.
d.       Servlet can accept all protocol requests. JSP is slower than servlet because the first step in the JSP lifecycle is the translation of JSP to Java code and then compile.
e.       In servlet, we can override the service() method. In JSP, we cannot override its service() method.
f.         Modification in servlet is a time-consuming task because it includes reloading, recompiling and restarting the server. JSP modification is fast, just need to click the refresh button.

Insert data in the database using JSP and Servlet

com/crud/Dao/StudentRecordDao.java:

package com.crud.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.crud.model.StudentModel;
import com.crud.util.DbConnect;

public class StudentRecordDao {
    public void insertRecord(StudentModel student) {
	Connection conn = DbConnect.getConnection();
	String sql = "insert into stu_table(name,address) values(?,?)";
	try {
	    int rowInserted = 0;
	    PreparedStatement stmt = conn.prepareStatement(sql);
	    stmt.setString(1, student.getName());
	    stmt.setString(2, student.getAddress());
	    rowInserted = stmt.executeUpdate();
	    if(rowInserted>0) {
		System.out.println("Data Inserted...");
	    }
	} catch (SQLException e) {
	    System.out.println(e);
	}
    }
}

com/crud/model/StudentModel.java:

package com.crud.model;

public class StudentModel {
	private String name;
	private String address;
	
	public StudentModel( String name, String address) {
		super();
		this.name = name;
		this.address = address;
	}

	public String getName() {
		return name;
	}

	public String getAddress() {
		return address;
	}
}

com/crud/service/StudentService.java:

package com.crud.service;

import com.crud.Dao.StudentRecordDao;
import com.crud.model.StudentModel;

public class StudentService {
    public void insertRecord(StudentModel student) {
	StudentRecordDao dao = new StudentRecordDao();
	dao.insertRecord(student);
    }
}

com/crud/servlet/StudentServlet.java:

package com.crud.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import com.crud.model.StudentModel;
import com.crud.service.StudentService;


@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String name=request.getParameter("myName");
		String address = request.getParameter("myAddress");
		StudentModel student = new StudentModel(name,address);
		StudentService service = new StudentService();
		service.insertRecord(student);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
	
		doGet(request, response);
	}

}

com/crud/util/DbConnect.java:

package com.crud.util;
import java.sql.*;
public class DbConnect {
     static String databaseURL = "jdbc:mysql://localhost:3306/students"
     static String user = "root";
     static String password = "";
     
     public static Connection getConnection() {
    	 Connection conn=null;
	     try {
	         Class.forName("com.mysql.jdbc.Driver");
	         try {
	             conn = DriverManager.getConnection(databaseURL, user, password);
	             System.out.println("Connected to the database");
	         } catch (SQLException e) {
	             System.out.println(e);
	         }
	     } catch (ClassNotFoundException e) {
	         System.out.println("Class not found exception");
	     }
	     return conn;
     }
}

Conclusion

This is how you write JSP and servlet programs. They can be combined to perform certain actions like I have calculated simple interest above. I have also mentioned how you can display Tribhuvan University 10 times with JSP or Servlet.

I hope this post is very helpful to you. If you have any questions, ask me in the comment section. I will reply as soon as possible. Thanks.