Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // simple tutorial i followed:
- // https://www.baeldung.com/mvc-servlet-jsp
- // filename: Student (I renamed this to Student.java)
- public class Student {
- // Student is the Model Layer (other Model Layer is StudentService) of the MVC Pattern
- private int id;
- private String firstName;
- private String lastName;
- // constructors, getters and setters go here
- }
- // filename: StudentService (I reanamed this to StudentService.java)
- public class StudentService {
- // StudentService is the Model Layer (other Model Layer is Student) of the MVC Pattern
- public Optional<Student> getStudent(int id){
- switch(id) {
- case 1:
- return Optional.of(new Student(1, "John", "Doe"));
- case 2:
- return Optional.of(new Student(2, "Jane", "Goodall"));
- case 3:
- return Optional.of(new Student(3, "Max", "Born"));
- default:
- return Optional.empty();
- }
- }
- }
- // filename: StudentServlet (I renamed to StudentServlet.java)
- @WebServlet(
- name = "StudentServlet",
- urlPatterns = "/student-record")
- public class StudentServlet extends HttpServlet {
- // StudentServlet is our Controller Layer of the MVC pattern
- private StudentService studentService = new StudentService();
- private void processRequest(
- HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String studentID = request.getParameter("id");
- if (studentID != null) {
- int id = Integer.parseInt(studentID);
- studentService.getStudent(id).ifPresent(s -> request.setAttribute("studentRecord", s));
- }
- RequestDispatcher dispatcher = request.getRequestDispatcher(
- "/WEB-INF/jsp/student-record.jsp");
- dispatcher.forward(request, response);
- }
- @Override
- protected void doGet(
- HttpServletRequest request, HttpServletresponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- @Override
- protected void doPost(
- HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- }
- // filename: student-record.jsp
- <html>
- <head>
- <title>Student Record</title>
- </head>
- <body>
- <%
- if (request.getAttribute("studentRecord") != null) {
- Student student = (Student) request.getAttribute("studentRecord");
- %>
- <h1>Student Record</h1>
- <div>ID: <%= student.getId()%></div>
- <div> First Name: <%= student.getFirstName()%></div>
- <div> Last Name: <%= student.getLastName()%></div>
- <%
- } else {
- %>
- <h1>No Student Record Found.</h1>
- <% } %>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement