Can you do it? Java EE

Let's make something using Java Servlet ** for school assignments! A story like ** came in, so that's the story.

I use Laravel a lot, and I felt that it could be used like that, so I will introduce it while making it compatible.

Servlet stands like a controller

package servlets;

import models.Room;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/")
public class RoomServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Room> rooms;
        try {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            rooms = Room.index();
        } catch (SQLException | ClassNotFoundException e) {
            request.setAttribute("error", e);
            request.getRequestDispatcher("/WEB-INF/jsp/views/rooms/room-list.jsp").forward(request, response);
            return;
        }

        request.setAttribute("rooms", rooms);
        request.getRequestDispatcher("/WEB-INF/jsp/views/rooms/room-list.jsp").forward(request, response);
    }
}

You can route with the @WebServlet annotation. Besides, it is not possible to rewrite web.xml and route it, but it is troublesome because the amount of writing increases a little.

The doGet method processes in response to the GET of the HTTP request. request is packed with necessary items such as parameters and request headers. Since response hasgetWriter (), it can also be rendered from Servlet.

Add parameters internally (?) With request.setAttribute ("attributeName ", value) and use request.getRequestDispatcher ("/path/to/page.jsp ") etc. to use other Servlets Processing can be transferred to JSP. You can get it by doing request.getAttribute ("attributeName ") at the destination.

You can pass any request.setAttribute (String, obj). Since the return value of request.getAttribute (String) is Object type, it is necessary to receive the value and upcast it.

There are also doPost (), doPut (), doDelete (), etc., so you can easily create a REST API instead.

JSP can be used like a template engine

<%@ page import="models.Room" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<jsp:include page="/WEB-INF/jsp/views/base/head.jsp">
    <jsp:param name="title" value="Thread list"/>
</jsp:include>
<body class="bg-light">
<jsp:include page="/WEB-INF/jsp/views/base/navber.jsp"/>
<div class="container">
    <h1 class="font-weight-bold">Thread list</h1>

    <% if (request.getAttribute("error") != null) {
        Exception e = (Exception) request.getAttribute("error");
    %>
    <div class="text-danger">
        <%=e.getMessage()%>
    </div>
    <% } else {
        List<Room> rooms = (List<Room>) request.getAttribute("rooms");
    %>

    <div class="row">
        <%
            for (Room it : rooms) {
                request.setAttribute("room", it);
        %>
        <div class="col-12 mb-3">

            <jsp:include page="/WEB-INF/jsp/components/room-card.jsp"/>
        </div>
        <% } %>
    </div>

    <% } %>
</div>
</body>
</html>

You can embed other JSPs using <jsp: include page =" path / to / page.jsp "/>. This embedding feels like adding the JSP of another file as it is and rendering it, so you can use it like a single file component of Vue.js. You can also pass parameters by using the <jsp: param> tag as a child element of the <jsp: include> tag. This is synonymous with request.setAttribute () of Servlet, and is read from the embedded JSP using request.getAttribute ().

Like <slot> in Vue.js, it seems to be difficult to use the outline of the UI as one JSP and put View as a child element in it.

Also, the template syntax (which doesn't seem to be correct) uses the Java syntax as is. It doesn't require any effort to learn new template syntax, but it's not as simple as Flask, and I got the impression that it was messy.

Also, since you can use any Java syntax, you can write anything in JSP. If you don't weight yourself, it will look like PHP, so you should be careful.

... I wouldn't stop if I made everything with JSP.

Also, the WEB-INF / directory is a directory that cannot be accessed from a browser. JSPs that are embedded or supposed to be used by the dispatcher should be placed in the WEB-INF / directory.

Filter feels like middleware

Filter can intervene processing before it is passed to the routed class. For example, if you are not logged in, you can redirect to the login page or correct the character encoding.

package filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "CharacterEncodingFilter")
public class CharacterEncodingFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

DoFilter () is the essential filtering part. The argument req could also be upcast to the HttpServletRequest class.

I haven't investigated it in detail, so I don't know any more, but I think I can enjoy it in various ways.

To make Filter work, specify <url-pattern> in the web.xml file.

Let's do our best to design the model layer

Java EE doesn't have a CLI like Laravel's artisan, and no design patterns are considered. Therefore, you need to design the so-called "model" part used by Servlet, JSP, and Filter by yourself.

With the seasoning here, you will be able to build the entire application with your favorite architecture. Since you have to build your own favorite architecture, it takes time and responsibility for the programmer.

Impressions

The effort of deploying is similar

After all, most web applications are operated by borrowing the functions of the web server. Flask of Python has a server for the time being, but when doing it in a production environment, it is mostly linked with a web server with uWSGI, and I think that it is acceptable to use Tomcat etc.

It's a lot of work

If you are used to something convenient like Laravel, you will find it troublesome with just plain Java EE.

If you want to enhance the front end, you need to set webpack and node by yourself, and since there is no function such as authentication system and CSRF protection, you need to program by yourself. Also, since JSP does not have an escape function, there is a danger of XSS.

I don't think it's a comparison because the times they were made are different.

However, since the session was fairly easy and easy to handle, it may not be a problem in the case where you do not need an authentication system but you want to identify the accessing user to some extent.

But when it comes to moving for a long time ...

I'm worried about the maintenance situation

The latest release of Java EE seems to be September 21, 2017. [^ 1]

Also Tomcat. When I specified JDK 13 to run Tomcat 8.5.47, I got an error saying that it is not supported. By specifying JRE 1.8, I'm getting things done, but I'm worried.

I haven't tried Tomcat 9 [^ 2], so maybe it's supported.

Summary

I thought it would be unavoidable to do it in the lecture, but I thought that Servlet was well done. However, I want to use Laravel because it has more functions and is easier to make! I didn't think.

Recommended Posts

Can you do it? Java EE
You can do it with copy! Aspect-oriented programming (Android)
[Java] Can you explain this phenomenon?
Do you use Stream in Java?
[Good news] You can still go with Java 8 !!
Do you need a memory-aware implementation of Java?
[Even beginners can do it! ] How to create Java environment on Windows 10 (JDK14.0.1)
Notify the build result with slack with CircleCI. You can do it in 5 minutes.
[JavaScript] Java programmers! You can understand JavaScript closures very easily!
[Even beginners can do it! ] How to write Javadoc
Do you know Decorator?
Do you need dotenv-rails?
You can do it right away with Serverless Framework Serverless on AWS (API + Lambda [java] is easy to set up)
[Even beginners can do it! ] How to install Eclipse on Windows 10 (Java environment construction)
Java reserved word summary that you do not know unexpectedly
It's winter but do you want fireworks? ?? Then implement it
I can read it! RxJava
Enable Java EE with NetBeans 9
[Java] Make it a constant
Java thread safe for you
The first thing to do before you can use Rails6 Ajax