V
V
Vladislav2015-08-04 21:46:41
Java
Vladislav, 2015-08-04 21:46:41

Can a servlet handle multiple pages?

The question is: do I need to create a separate servlet for each page of the site, or can one servlet process several pages? For example: there are /contact and /about pages, do I need to create ServletContact and ServletAbout or should I use another approach? Thank you.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
E
Evhen, 2015-08-05
@MrBikus

Use the Model-View-Controller pattern.
For example, you have the Contacts app.
The servlet will be the controller handling various contact manipulations.
To display results, forms, lists - use jsp
Here is a simple example of a controller (servlet) that handles CRUD operations with contacts

@WebServlet(urlPatterns = "/contact")
public class ContactController extends HttpServlet {

  private ContactDao contactDao = new HashMapContactDao();
  
  @Override
  protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    contactDao.removeById(Long.valueOf(req.getParameter("id")));
    this.doGet(req, resp);
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    List<Contact> contactList = contactDao.findAll();
    req.setAttribute("contactList", contactList);
    req.getRequestDispatcher("view/contact.jsp").forward(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    Contact newContact = new Contact();
    newContact.setLastName(req.getParameter("lastName"));
    newContact.setFirstName(req.getParameter("firstName"));
    newContact.setPhone(req.getParameter("phone"));
    
    this.contactDao.add(newContact);

    this.doGet(req, resp);
  }

  @Override
  protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    Contact newContact = new Contact();
    newContact.setId(Long.valueOf(req.getParameter("id")));
    newContact.setLastName(req.getParameter("lastName"));
    newContact.setFirstName(req.getParameter("firstName"));
    newContact.setPhone(req.getParameter("phone"));

    this.contactDao.update(newContact);
    
    super.doPut(req, resp);
  }
}

Display (view) contacts view/contact.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Список контактов</title>
<style type="text/css">
table {
  border-collapse: collapse;
}

table, td, th {
  border: 1px solid black;
}
</style>
</head>
<body>

  <h1>Список контактов</h1>

  <form method="post">
    <fieldset>
      <legend>Новый контакт</legend>
      <p>
        <label>Фамилия: <input type="text" name="lastName" /></label>
      </p>
      <p>
        <label>Имя: <input type="text" name="firstName" /></label>
      </p>
      <p>
        <label>Номер телефона: <input type="text" name="phone" /></label>
      </p>
      <p>
        <button>Создать</button>
      </p>
    </fieldset>
  </form>

  <table style="border: 1px solid black;">
    <tr>
      <th>№</th>
      <th>Фамилия</th>
      <th>Имя</th>
      <th>Номер телефона</th>
    </tr>


    <c:if test="${contactList != null}">
      <c:forEach items="${contactList}" var="c">

        <tr>
          <td>${c.id}</td>
          <td>${c.lastName}</td>
          <td>${c.firstName}</td>
          <td>${c.phone}</td>
        </tr>

      </c:forEach>
    </c:if>
  </table>

</body>
</html>

public class Contact {

  private Long id;
  private String lastName;
  private String firstName;
  private String phone;

  public Contact() {
  }

  public Contact(String lastName, String firstName, String phone) {
    this.lastName = lastName;
    this.firstName = firstName;
    this.phone = phone;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }


  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
  }
}

And we separate access to data and their manipulations with a DAO layer (a simple implementation based on HashMap). Thanks to the interface, in the future we will be able to substitute any implementation, such as storing contacts in a database.
public class HashMapContactDao implements ContactDao {

  private AtomicLong idCounter = new AtomicLong();
  private Map<Long, Contact> map = new ConcurrentHashMap<Long, Contact>();
  
  @Override
  public List<Contact> findAll() {
    return new ArrayList<Contact>(this.map.values());
  }

  @Override
  public void removeById(Long id) {
    this.map.remove(id);
  }

  @Override
  public Contact add(Contact contact) {
    Long newId = this.idCounter.incrementAndGet();
    contact.setId(newId);
    this.map.put(newId, contact);
    return contact;
  }

  @Override
  public void update(Contact contact) {
    this.map.put(contact.getId(), contact);
  }
}

Although this is a "low level", but it needs to be dealt with. Then of course it's better to use Spring MVC

A
Andrey Nikiforov, 2015-08-04
@eoffsock

<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <uri-mapping>/*</uri-mapping>
</servlet-mapping>

class MyServlet extends HttpServlet{

      public void doGet(HttpReq req, HttpResp resp){
               StringBuffer requestURL = req.getRequestURL();
               // Тут сравниваете requestURL с необходимым и далее обрабатываете как хотите
      }

}

But in general it is a crutch, IMHO.

N
nagibator8000, 2015-08-05
@nagibator8000

Servlets are a low-level thing. It's better to use Spring MVC or something that implements JAX-RS like Jersey or RESTEasy.

N
Noobkesan, 2015-08-05
@Noobkesan

Did it like this:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>my</servlet-name>
        <servlet-class>ru.test.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>my</servlet-name>
        <url-pattern>/my1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>my</servlet-name>
        <url-pattern>/my2</url-pattern>
    </servlet-mapping>
</web-app>

Works.

M
MrBe, 2016-08-13
@MrBe

Use patterns.
FrontController(Mediator) + Strategy
Very well written about it here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question