How to pass id from JSP to Servlet through url

  • 3 mins read

In this example, I am going to show you how to pass the id or anything from the JSP page to servlet through URL.

Lets take a example, we have a list of courses available and displayed in the coursetable.jsp page. In this course table there have an operation like edit the course name or course total hours. so, we can make a link to perform this edit operation. When user click the link actually we are going to pass the course id to the servlet controller through URL and it is called the get method, In servlet it is called within the doGet method.

coursetable.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="com.dao.*"%>
<%@page import="com.controller.*"%>
<%
JDBCDao jdbcDao = new JDBCDao();
ResultSet resultSet = jdbcDao.getCourse();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.course-table {
	width: 80%;
	margin-top: 50px;
	margin-left: 200px;
}
</style>
</head>
<body>
	<div class="course-table">
		<table border="1px">
			<tr>
				<td><b>Course Name</b></td>
				<td><b>Total Hour</b></td>
				<td><b>Action</b></td>
			</tr>
			<%
			while (resultSet.next()) {
			%>
			<tr>
				<td><%=resultSet.getString("course_name")%></td>
				<td><%=resultSet.getString("total_hours")%></td>
				<td><a
					href="<%=request.getContextPath()%>/course?edit_id=<%=resultSet.getString("course_id")%>">Edit</a>
					
				</td>
			</tr>

			<%
			}
			%>
		</table>
	</div>
</body>
</html>

CourseController.java

package com.controller;

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;

import com.dao.JDBCDao;
import com.model.Course;

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

	public CourseController() {
		jdbc = new JDBCDao();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (request.getParameter("edit_id") != null) {
			int id = Integer.parseInt(request.getParameter("edit_id"));
			Course course = jdbc.getCourseById(id);
			request.setAttribute("course", course);
			request.getRequestDispatcher("edit_course.jsp").forward(request, response);
		}
	}

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



	}

}

Hope it helps

Leave a Reply