Saturday, February 23, 2013

JSP, Servlet, MVC in a nutshell

In a nutshell, this is how you can use JSP and Servlets with the MVC pattern.  

  • Model: A POJO (Email.java) 
  • View: A JSP (email-list.jsp)  
  • Controller: A Servlet (EmailListServlet.java)

Email.java (The Model)


public class Email {
    private String from;
    private String subject;
    private String message;
 
    public Email(String from, String subject, String message) {
 this.from = from;
 this.subject = subject;
 this.message = message;
    }
    
    // Getters and Setters...
    
}

email-list.jsp (The View)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Email List</title>
</head>

<body>
    <table>
        <tr><th>From</th><th>Subject</th><th>Message</th></tr>
 
        <c:forEach var="email" items="${emails}">
     <tr>
         <td>${email.from}</td>
  <td>${email.subject}</td>
  <td>${email.message}</td>
     </tr>
 </c:forEach>
    </table>
</body>
</html>

EmailListServlet.java (The Controller)


public class EmailListServlet extends HttpServlet {
 
 private static final long serialVersionUID = 1L;
 
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  
  List<Email> emails = yourMethodThatReturnsEmailList();
  req.setAttribute("emails", emails);
  getServletContext().getRequestDispatcher("/email-list.jsp").forward(req, resp);
 }

}

The servlet mappings in web.xml


<servlet>
  <servlet-name>EmailList</servlet-name>
  <servlet-class>com.test.servlet.EmailListServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>EmailList</servlet-name>
  <url-pattern>/email</url-pattern>
</servlet-mapping>

Then just access the servlet i.e www.mydomain.com/email

1 comment:

  1. Hello, and thanks for all the information you are providing me on Jsp and servlets.
    Also i I've worked a lot on FFT and use of Jitter to handle FFT data. But I didn't dive to deeply in Jitter, because I'm not really interested in images. What I'd like to do is to have the possibility to make some operations on matrix based on Symmetry applications of Group Theory,
    In a way to modify the spectral informations held in the matrix. Someone could argue if this could be done in Max, or could be better to work on it learning JAva and programming specific Externals? For that I am trying to go for 6 week training http://www.wiziq.com/course/12145-the-6-week-complete-java-primer-with-training-certificate wonder this course
    will help me out
    Thanks.

    ReplyDelete