0% found this document useful (0 votes)
9 views1 page

Bookserverlet

The BookServlet class handles HTTP requests for managing books in a bookshop application. It retrieves a list of books for display and allows the addition of new books via POST requests, utilizing a BookDAO for data access. If a book is successfully added, it redirects to the book list; otherwise, it forwards to an admin page with an error message.

Uploaded by

haryzao03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Bookserverlet

The BookServlet class handles HTTP requests for managing books in a bookshop application. It retrieves a list of books for display and allows the addition of new books via POST requests, utilizing a BookDAO for data access. If a book is successfully added, it redirects to the book list; otherwise, it forwards to an admin page with an error message.

Uploaded by

haryzao03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

package [Link].

controller;

import [Link];
import [Link];

import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];

@WebServlet("/books/*") // Servlet mapping path


public class BookServlet extends HttpServlet {

private BookDAO bookDAO = new BookDAO(); // If not using a service, use DAO
directly

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String path = [Link]();

if (path == null || [Link]("/")) {


// Fetch books from DAO
List<Book> bookList = [Link]();
[Link]("books", bookList);
[Link]("/[Link]").forward(req, resp);
}
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String title = [Link]("title");
String author = [Link]("author");
double price = [Link]([Link]("price"));
String image = [Link]("image");

// Create and save new book


Book newBook = new Book();
[Link](title);
[Link](author);
[Link](price);
[Link](image);

boolean isAdded = [Link](newBook);

if (isAdded) {
[Link]("/books/"); // Redirect after adding the book
} else {
[Link]("errorMessage", "Failed to add book.");
[Link]("/[Link]").forward(req, resp);
}
}
}

You might also like