CRUD in JSP and Servlets: Full Implementation
CRUD in JSP and Servlets: Full Implementation
CRUD in JSP and Servlets - Guide
यह guide आपको step-by-step दिखाएगा कि कैसे एक पूरी तरह functioning CRUD in JSP and Servlets application बनाते हैं।
हम practical code, database design और best practices देंगे ताकि exam में भी आप confidence से लिख सको।
Why CRUD in JSP and Servlets
CRUD in JSP and Servlets एक fundamental topic है web-app development का, खासकर college exams में।
यह दिखाता है कि कैसे server-side Java, Servlets और JSP मिलकर dynamic pages और DB operations करते हैं।
Prerequisites
आपको basic Java, JDBC, HTML और SQL की समझ होनी चाहिए — इससे concepts जल्दी समझ आ जाएंगे।
IDE (Eclipse/IntelliJ), Tomcat और MySQL/MariaDB ready रखें ताकि hands-on practice हो सके।
Project Structure
सिंपल और clear structure रखें — इससे code maintainable और exam में explanation आसान होगा।
Suggested structure नीचे दिया है जो typical CRUD in JSP and Servlets app के लिए مناسب है।
| Folder/File | Description |
|---|---|
| src/ | Java packages: model, dao, servlet |
| WebContent/ | JSP pages, CSS, JS |
| WEB-INF/web.xml | Servlet mapping (optional with annotations) |
| lib/ | JDBC driver और अन्य dependencies |
Database Design
CRUD in JSP and Servlets के लिए सही DB design जरूरी है — पहले table बनाते हैं जो students record संभाले।
simple और exam-friendly table नीचे है जिसे आप modify कर सकते हैं।
| Column | Type | Notes |
|---|---|---|
| id | INT AUTO_INCREMENT PRIMARY KEY | unique identifier |
| name | VARCHAR(100) | student name |
| VARCHAR(100) UNIQUE | contact email | |
| course | VARCHAR(50) | course enrolled |
| created_at | TIMESTAMP DEFAULT CURRENT_TIMESTAMP | record time |
SQL: Create Table
DB create करने के लिए यह SQL use करें — exam में यह statement पूछे जा सकते हैं।
नीचे का code JDBC से work करेगा जब DB connection सही होगा।
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
course VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Dependencies & Config
JDBC driver jar (mysql-connector) और servlet-api server में होना चाहिए; project में add करें।
web.xml optional है — आप annotations से Servlets map कर सकते हैं।
DB Connection Utility
DB से connect करने के लिए एक utility class बनाएं ताकि बार-बार credentials न लिखने पड़े।
यह practice CRUD in JSP and Servlets apps में common है और exam में अच्छा दिखता है।
public class DbUtil {
private static final String URL = "jdbc:mysql://localhost:3306/yourdb";
private static final String USER = "root";
private static final String PASS = "password";
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USER, PASS);
}
}
Model Layer (POJO)
Model class simple POJO होगी — getters और setters के साथ ताकि JDBC row को map कर सकें।
POJO exam में frequently पूछा जाता है इसलिए clean और concise रखें।
public class Student {
private int id;
private String name;
private String email;
private String course;
// constructors, getters, setters
}
DAO Layer (Data Access Object)
DAO में CRUD operations होंगे — यह application की core logic है जो DB से interact करती है।
PreparedStatement use करें ताकि SQL injection न हो और performance बढ़े।
DAO Methods
- createStudent(Student s)
- getStudentById(int id)
- getAllStudents()
- updateStudent(Student s)
- deleteStudent(int id)
DAO Example (Create & Read)
नीचे का code exam में अच्छे marks दिला सकता है क्योंकि यह clear है और best practice follow करता है।
public class StudentDao {
public int save(Student s) throws Exception {
String sql = "INSERT INTO students(name,email,course) VALUES(?,?,?)";
try(Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
ps.setString(1, s.getName());
ps.setString(2, s.getEmail());
ps.setString(3, s.getCourse());
int rows = ps.executeUpdate();
return rows;
}
}
public Student findById(int id) throws Exception {
String sql = "SELECT * FROM students WHERE id=?";
try(Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
Student s = new Student();
s.setId(rs.getInt("id"));
s.setName(rs.getString("name"));
s.setEmail(rs.getString("email"));
s.setCourse(rs.getString("course"));
return s;
}
return null;
}
}
}
Servlet Controller
Servlets request को handle करेंगे और DAO से data fetch कर JSP को forward करेंगे।
एक central servlet या multiple small servlets दोनों approach valid हैं; exam में दोनों explain करें।
Servlet Mapping (Example)
Annotations use करके servlet map करना modern approach है और code कम cluttered होता है।
नीचे एक example है जो list, add, edit, delete handle करता है।
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if(action == null) action = "list";
try {
switch(action) {
case "new": showNewForm(req, resp); break;
case "insert": insertStudent(req, resp); break;
case "delete": deleteStudent(req, resp); break;
case "edit": showEditForm(req, resp); break;
case "update": updateStudent(req, resp); break;
default: listStudent(req, resp); break;
}
} catch(Exception e) { throw new ServletException(e); }
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
// helper methods: listStudent, showNewForm, insertStudent, etc.
}
JSP Views
JSP pages UI के लिए होंगे — list.jsp, form.jsp जैसे pages बनाएँ ताकि user interact कर सके।
JSP में JSTL और EL का इस्तेमाल करें ताकि scriptlets avoid हों और code readable रहे।
list.jsp (Sample)
List page में सभी students दिखाए जाएँ और edit/delete actions के लिए links रहें।
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Student List
Add New Student
ID Name Email Course Actions
${s.id}
${s.name}
${s.email}
${s.course}
Edit
Delete
Form Handling & Validation
Server-side validation जरूरी है; client-side validation optional है पर helpful होता है UI के लिए।
JSP form से data servlet में आएगा — servlet validate करे और errors वापस form.jsp में भेजे।
Simple Validation Rules
- name required और length check
- email required और regex pattern check
- duplicate email handle करने के लिए unique constraint DB में रखें
// validation pseudo
String name = req.getParameter("name");
String email = req.getParameter("email");
if(name==null || name.trim().isEmpty()) { errors.add("Name required"); }
if(!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) { errors.add("Invalid email"); }
Update & Delete Implementation
Update में existing record fetch करके form में pre-fill करें और फिर submit पर update query चलाएं।
Delete simple रहती है — id मिलते ही DAO से delete कर दें और list पर redirect करें।
DAO: Update & Delete
public int update(Student s) throws Exception {
String sql = "UPDATE students SET name=?, email=?, course=? WHERE id=?";
try(Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, s.getName());
ps.setString(2, s.getEmail());
ps.setString(3, s.getCourse());
ps.setInt(4, s.getId());
return ps.executeUpdate();
}
}
public int delete(int id) throws Exception {
String sql = "DELETE FROM students WHERE id=?";
try(Connection conn = DbUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, id);
return ps.executeUpdate();
}
}
Best Practices for CRUD in JSP and Servlets
PreparedStatement use करें, resource close करने के लिए try-with-resources करें, और input sanitize करें।
JSP में scriptlets avoid करें; JSTL/EL use करें ताकि code readable रहे और exam में अच्छा लगे।
Security Tips
- SQL injection से बचने के लिए PreparedStatement जरूरी है।
- Sensitive data DB में encrypt या hashed रखें अगर needed हो।
- Auth checks servlet में रखें ताकि unauthorized access न हो।
Error Handling & Transactions
DB operations में failures हो सकते हैं — हमेशा proper exception handling और user-friendly messages दें।
Multiple related updates के लिए transaction use करें ताकि consistency बनी रहे।
try(Connection conn = DbUtil.getConnection()) {
conn.setAutoCommit(false);
// multiple statements
conn.commit();
} catch(Exception e) {
conn.rollback();
throw e;
}
Testing & Debugging
Unit test नहीं आसान होता servlet से पर आप DAO methods के लिए unit tests लिख सकते हैं।
Manual testing के लिए postman या browser use करें और edge-cases check करें।
Common Issues
- ClassNotFoundException: JDBC driver missing
- 404 on JSP: path wrong या web.xml mapping issue
- Character encoding issue: request.setCharacterEncoding("UTF-8") use करें
Performance Tips
Connection pooling use करें ताकि हर request पर नया connection न बने और performance बढ़े।
Large result sets के लिए pagination implement करें ताकि page slow न हो।
Pagination Example
DAO में LIMIT और OFFSET लगाकर page-wise records fetch करें — exam में यह concept बहुत useful है।
SELECT * FROM students ORDER BY id DESC LIMIT ? OFFSET ?
Deployment
WAR file बनाकर Tomcat पर deploy करें — exam में deployment steps बताने से आपकी answer complete दिखेगा।
DB config production में environment variables से लें, code में hard-code न रखें।
Exam-focused Notes: Quick Points
यह section short और pointwise है — exam में जब time कम हो तो इन points को याद रखें।
CRUD in JSP and Servlets के लिए core चीजें: DAO, Servlet controller, JSP view, JDBC connection, validation।
- Use MVC pattern — separates concerns और clarity देती है।
- Prefer JSTL/EL over scriptlets in JSP.
- Handle exceptions gracefully and log errors for debugging.
- Use prepared statements and connection pooling for security और performance.
- Keep DB schema normalized लेकिन over-normalize मत करो — performance देखो।
Sample CRUD Flow (Step by Step)
नीचे एक short sequence है जो typical CRUD in JSP and Servlets app में होता है — इसे exam में लिखना आसान है।
Step-wise explain करो और diagram की तरह याद रखें।
- Browser -> HTTP GET /student?action=list -> StudentServlet -> StudentDao.getAll -> list.jsp render
- User clicks "Add" -> /student?action=new -> form.jsp shown
- Form submit -> POST /student?action=insert -> servlet reads params -> dao.save -> redirect to list
- Edit flow: fetch by id, populate form, submit update -> dao.update -> redirect
- Delete flow: /student?action=delete&id= -> dao.delete -> redirect
Sample Code Snippets Reference
Important code snippets दिये गये हैं जो exam में explain करने पर impressed दिखते हैं।
In-class explanation simple रखें और flow के साथ दिखाएँ।
Servlet doGet Helper (listStudent)
private void listStudent(HttpServletRequest req, HttpServletResponse resp) throws Exception {
StudentDao dao = new StudentDao();
List list = dao.findAll();
req.setAttribute("students", list);
req.getRequestDispatcher("list.jsp").forward(req, resp);
}
Common Questions You Might Face in Exam
यहाँ कुछ typical short-answer questions हैं और उनके concise answers ताकि आप revision कर सकें।
इनको memory में रखें — practical examples के साथ answer करते हुए marks बढ़ते हैं।
- Q: DAO pattern क्या है? A: Data access logic को encapsulate करने का pattern।
- Q: JSP में scriptlet क्यों avoid करें? A: Maintainability और separation of concerns के लिए।
- Q: PreparedStatement का फायदा? A: SQL injection prevention और better performance।
Cheat-sheet: Commands & Config
Quick reference commands और config statements — exam में small snippets useful होते हैं।
ये commands local testing के लिए हैं — real deployment में settings बदल सकते हैं।
| Action | Command/Code |
|---|---|
| Start Tomcat | catalina.bat run / startup.sh |
| Build WAR | mvn clean package (if using maven) |
| DB Connect URL | jdbc:mysql://localhost:3306/yourdb?useSSL=false&serverTimezone=UTC |
Final Implementation Tips (Exam Useful)
जब exam में पूरा flow लिखना हो तो flowchart-style steps और key code snippets दें।
CRUD in JSP and Servlets को MVC context में समझाएँ और security/performance notes ज़रूर जोड़ें।
- Code comments short रखें और clear रखें ताकि examiner को logic तुरंत समझ आए।
- Use meaningful variable names — e.g., studentDao, studentList — readability बढ़ती है।
- Edge cases mention करें: duplicate email, null inputs, DB connection failure।
References & Study Path
Start with small example — simple Create and Read बनाइए, फिर Update और Delete add करें।
Practice coding और manual testing दोनों करें; इससे आप exam में confident होंगे।
इस guide में हमने practical code, DB design और best practices cover किए ताकि आप CRUD in JSP and Servlets topic पर पूरी तरह तैयार हो।
अब इस structure को copy करके अपने IDE में implement करें और छोटे छोटे parts को अलग अलग test करें।