Skip to content

Instantly share code, notes, and snippets.

@dimMaryanto93
Last active December 16, 2020 15:01
Show Gist options
  • Save dimMaryanto93/c0a51e92e23ada4ecb71f9c18c803fea to your computer and use it in GitHub Desktop.
Save dimMaryanto93/c0a51e92e23ada4ecb71f9c18c803fea to your computer and use it in GitHub Desktop.
Belajar Java WEB dengan Servlet
stages:
- test
- build
variables:
MAVEN_CLI_OPTS: "--show-version"
cache:
paths:
- .m2/repository
image: ${PRIVATE_REPOSITORY_PULL}/maven:3.6.3-jdk-8
building:
stage: build
script:
- mvn -s $M2_PROXY $MAVEN_CLI_OPTS package -DskipTests
after_script:
- mvn -s $M2_PROXY cargo:redeploy -Dcargo.remote.username=${TOMCAT_USERNAME} -Dcargo.remote.password=${TOMCAT_PASSWORD} -Dcargo.hostname=${TOMCAT_HOST} -Dcargo.servlet.port=${TOMCAT_PORT}
only:
- /-release/
tags:
- docker
artifacts:
paths:
- target/*.war
name: $CI_PROJECT_NAME-$CI_COMMIT_TAG
package com.maryanto.dimas.bootcamp.servlet.listener;
import com.maryanto.dimas.bootcamp.servlet.service.DatabaseService;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@Slf4j
@WebListener
public class DatabaseConnectionListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
log.info("web deployed");
context.setAttribute("db", new DatabaseService("root", "root", "jdbc:mysql://localhost:3306/testing"));
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
log.info("web un-deployed");
}
}
package com.maryanto.dimas.bootcamp.servlet.service;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DatabaseService {
private String username;
private String password;
private String driverClassName;
}
package belajar.java.web.controller;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
public class HaloController extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
res.getWriter().println("Halo selamat datang, saya dari servlet HaloController");
}
}
package com.maryanto.dimas.bootcamp.servlet.controller;
import javax.servlet.ServletContext;
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;
@WebServlet(name = "home-session-listener", urlPatterns = {"/listener/home"})
public class HomeSessionListenerController extends HttpServlet {
String html = "<!doctype html>\n" +
"<html lang='en'>\n" +
"<head>\n" +
" " +
"<meta charset='UTF-8'>\n" +
" <meta name='viewport'\n" +
" content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>\n" +
" <meta http-equiv='X-UA-Compatible' content='ie=edge'>\n" +
" <title>Home</title>\n" +
"</head>\n" +
"<body>\n" +
" <div>\n" +
" <label for='totalUser'>Total User</label>\n" +
" <input type='text' name='totalUser' id='totalUser' value='%s' readonly>\n" +
" " +
"</div>\n" +
" " +
"<div>\n" +
" <label for='currentUser'>Current User Login</label>\n" +
" <input type='text' name='currentUser' id='currentUser' value='%s' readonly>\n" +
" </div>\n" +
"</body>\n" +
"</html>";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = getServletContext();
// get data from session
Integer totalUser = (Integer) context.getAttribute("totalUser");
Integer currentUser = (Integer) context.getAttribute("currentUser");
resp.getWriter().print(String.format(html, totalUser, currentUser));
}
}
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Arrays" %>
<%@ page language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--init list value--%>
<%! List<String> items = Arrays.asList("Java 8", "Java Database Connectivity", "PostgreSQL", "Java Web", "Java Persistence API"); %>
<% request.setAttribute("technologies", items); %>
<c:set value="${999}" var="salary"/>
<html>
<head>
<title>Belajar JSP - JSTL Core</title>
</head>
<body>
<%-- if statement --%>
<div>
<c:if test="${salary < 1000 }">
<c:out value="Salary less than 1000"/>
</c:if>
</div>
<%-- switch case statement --%>
<div>
<c:choose>
<c:when test="${salary <= 0}">
Salary is very low to survive.
</c:when>
<c:when test="${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
No comment sir...
</c:otherwise>
</c:choose>
</div>
<ul>
<%-- menampilkan list dari array dengan jstl foreach--%>
<c:forEach items='${technologies}' var="item">
<li><c:out value="${item}"/></li>
</c:forEach>
</ul>
<%-- diarahin ke `/bootcamp-java-webapp/selamat-siang` --%>
<a href="<c:url value="/selamat-siang"/>">Pindah ke halaman</a>
</body>
</html>
<%@ page import="java.util.Date" %>
<%@ page import="java.math.BigDecimal" %>
<%@ page language="java" isELIgnored="false" %>
<%@taglib prefix="formatter" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--init value--%>
<% request.setAttribute("saldo", new BigDecimal(10000000)); %>
<% request.setAttribute("tanggal", new Date()); %>
<%-- set local to indonesia --%>
<formatter:setLocale value="in_ID" />
<html>
<head>
<title>Belajar JSP - JSTL Format</title>
</head>
<body>
<ul>
<li>Format Uang: <formatter:formatNumber value="${saldo}" groupingUsed="true" type="CURRENCY"/></li>
<li>Format Tanggal: <formatter:formatDate value="${tanggal}" pattern="dd/MMMM/yyyy"/></li>
<formatter:bundle basename="messages">
<li><formatter:message key="say.halo"/></li>
</formatter:bundle>
</ul>
</body>
</html>
package com.maryanto.dimas.bootcamp.servlet.controller;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "login-session-listener", urlPatterns = {"/listener/login"})
public class LoginSessionListenerController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//language=HTML
String html = "<!doctype html>\n" +
"<html lang='en'>\n" +
"<head>\n" +
" " +
"<meta charset='UTF-8'>\n" +
" <meta name='viewport'\n" +
" content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>\n" +
" <meta http-equiv='X-UA-Compatible' content='ie=edge'>\n" +
" <title>Login Form</title>\n" +
"</head>\n" +
"<body>\n" +
"<form action='/bootcamp-java-webapp/listener/login' method='post'>\n" +
" <div>\n" +
" <label for='username'>Username</label>\n" +
" <input type='text' name='username' id='username'>\n" +
" </div>\n" +
" <div>\n" +
" <label for='password'>Password</label>\n" +
" <input type='password' name='password' id='password'>\n" +
" </div>\n" +
" <div>\n" +
" <button type='submit'>Submit</button>\n" +
" <button type='reset'>Reset</button>\n" +
" </div>\n" +
"</form>\n" +
"</body>\n" +
"</html>";
resp.getWriter().print(html);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String userName = req.getParameter("username");
// create create data session
session.setAttribute("uname", userName);
resp.sendRedirect(req.getContextPath() + "/listener/home");
}
}
package com.maryanto.dimas.bootcamp.servlet.controller;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(name = "logout-session-listener", urlPatterns = {"/listener/logout"})
public class LogoutSessionListenerController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(false);
// session destroy
session.invalidate();
resp.sendRedirect(req.getContextPath() + "/listener/home");
}
}
<%@ page isELIgnored="false" language="java" contentType="text/html; ISO-8859-1" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Daftar Mahasiswa</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<td>No</td>
<td>Nama Lengkap</td>
<td>Tanggal Lahir</td>
<td>Saldo</td>
</tr>
</thead>
<tbody>
<%--@elvariable id="list" type="com.maryanto.dimas.bootcamp.Mahasiswa"--%>
<c:forEach var="list" items="${list}">
<tr>
<td></td>
<td><c:out value="${list.namaLengkap}"/></td>
<td><c:out value="${list.tanggalLahir}"/></td>
<td><c:out value="${list.saldo}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
package com.maryanto.dimas.bootcamp;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
@Builder
public class Mahasiswa {
private String namaLengkap;
private Date tanggalLahir;
private BigDecimal saldo;
}
package com.maryanto.dimas.bootcamp.controller;
import com.maryanto.dimas.bootcamp.Mahasiswa;
import com.maryanto.dimas.bootcamp.service.MahasiswaService;
import com.maryanto.dimas.bootcamp.service.impl.MahasiswaServiceImpl;
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.util.List;
@WebServlet(name = "mahasiswa-list-controller", urlPatterns = {"/mahasiswa/list"})
public class MahasiswaController extends HttpServlet {
private MahasiswaService service;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
service = new MahasiswaServiceImpl();
List<Mahasiswa> list = service.findAll();
req.setAttribute("list", list);
// send attribute to jsp
req.getRequestDispatcher("/WEB-INF/mahasiswa/list.jsp").forward(req, resp);
}
}
package com.maryanto.dimas.bootcamp.service;
import com.maryanto.dimas.bootcamp.Mahasiswa;
import java.util.List;
public interface MahasiswaService {
List<Mahasiswa> findAll();
Mahasiswa findById(String id);
Mahasiswa save(Mahasiswa value);
Mahasiswa update(Mahasiswa value);
boolean deleteById(String id);
}
package com.maryanto.dimas.bootcamp.service.impl;
import com.maryanto.dimas.bootcamp.Mahasiswa;
import com.maryanto.dimas.bootcamp.service.MahasiswaService;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class MahasiswaServiceImpl implements MahasiswaService {
@Override
public List<Mahasiswa> findAll() {
return Arrays.asList(
Mahasiswa.builder()
.namaLengkap("Dimas Maryanto")
.saldo(new BigDecimal(10000000))
.tanggalLahir(new Date(731091600000L))
.build(),
Mahasiswa.builder()
.namaLengkap("Muhamad Yusuf")
.saldo(new BigDecimal(1000000))
.tanggalLahir(new Date(699555600000L))
.build()
);
}
@Override
public Mahasiswa findById(String id) {
return Mahasiswa.builder()
.namaLengkap("Dimas Maryanto")
.saldo(new BigDecimal(10000000))
.tanggalLahir(new Date(731091600000L))
.build();
}
@Override
public Mahasiswa save(Mahasiswa value) {
return value;
}
@Override
public Mahasiswa update(Mahasiswa value) {
return value;
}
@Override
public boolean deleteById(String id) {
return true;
}
}
<html>
<head>
<title>Mengirim Daftar Value</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="kirim-values" method="get">
<label for="values">Hobi</label>
<select name="values" id="values" size="10" multiple="multiple">
<option value="bola">Sepak Bola</option>
<option value="basket">Basket</option>
<option value="traveling">Traveling</option>
<option value="touring">Touring</option>
</select>
<input type="submit" value="Kirim">
</form>
</body>
</html>
package belajar.java.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/kirim-values")
public class MultipleValueController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String[] values = req.getParameterValues("values");
PrintWriter out = resp.getWriter();
out.println("Nilai yang dipilih adalah ");
for (String value : values) {
out.print(value + ", ");
}
}
}
package com.maryanto.dimas.bootcamp.servlet.filter;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@Slf4j
@WebFilter(
dispatcherTypes = DispatcherType.REQUEST,
urlPatterns = "/*"
)
public class PreLoggingFilter implements Filter {
private FilterConfig config;
@Override
public void init(FilterConfig config) throws ServletException {
this.config = config;
log.info("filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String uri = request.getRequestURI();
log.info("request from: {hostname: {}, port: {}, httpMethod: {}, url: {}, requestDate:{}}",
servletRequest.getRemoteHost(),
servletRequest.getServerPort(),
request.getMethod(),
uri,
new Date());
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
log.info("filter destroy");
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Input Data Mahasiswa POST HTTP Method</title>
</head>
<body>
<form action="/bootcamp-java-webapp/kirim-file" method="post" enctype="multipart/form-data">
<div>
<label for="nim">NIM</label>
<input type="text" name="nim" id="nim" placeholder="Input your nim">
</div>
<div>
<label for="nama">Nama Lengkap Mahasiswa</label>
<input type="text" name="nama" id="nama" placeholder="Input your fullname">
</div>
<div>
<label for="kota">Kota</label>
<select name="kota" id="kota">
<option value="bandung">Kota Bandung</option>
<option value="jakarta">DKI Jakarta</option>
<option value="surabaya">Kota Surabaya</option>
<option value="solo">Kota Solo</option>
<option value="semarang">Kota Samarang</option>
</select>
</div>
<div>
<label for="tanggalLahir">Tanggal Lahir</label>
<input type="date" name="tanggalLahir" id="tanggalLahir">
</div>
<div>
<label for="fileFoto">File Foto</label>
<input type="file" name="foto" id="fileFoto">
</div>
<div>
<button type="submit">Kirim</button>
<button type="reset">Reset</button>
</div>
</form>
</body>
</html>
<%! Integer nilai = 0; %>
<html>
<head>
<title>Belajar JSP Declaration</title>
</head>
<body>
<% out.print("nilainya adalah " + nilai); %>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Belajar JSP Directive tag include</title>
</head>
<body>
<section id="sidebar">
<%@ include file="../layout/sidebar.jsp" %>
</section>
<section id="body">
ini adalah bagian body
</section>
<footer>
<%@ include file="../layout/sidebar.jsp" %>
</footer>
</body>
</html>
<%@ page import="java.sql.Date" %>
<%@ page contentType="text/html;charset=UTF-8"
language="java"
isELIgnored="false" %>
<jsp:useBean id="mhs" class="com.maryanto.dimas.bootcamp.entity.Mahasiswa">
<jsp:setProperty name="mhs" property="nim" value="10511148"/>
<jsp:setProperty name="mhs" property="namaLengkap" value="Dimas Maryanto"/>
<jsp:setProperty name="mhs" property="tanggalLahir" value='<%= Date.valueOf("1991-01-01") %>'/>
</jsp:useBean>
<html>
<head>
<title>Belajar JSP Action</title>
</head>
<body>
<div>
<form action="#">
<div>
<label for="nim">NIM</label>
<input type="text" id="nim" name="nim" readonly value="${mhs.nim}"/>
</div>
<div>
<label for="nama">Nama Lengkap</label>
<input type="text" name="namaLengkap" id="nama" readonly value="${mhs.namaLengkap}">
</div>
<div>
<label for="tanggal">Tanggal Lahir</label>
<input type="text" name="tanggal" id="tanggal" readonly value="${mhs.tanggalLahir.toString()}">
</div>
</form>
</div>
</body>
</html>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8"
language="java"
isELIgnored="false"
isErrorPage="true" %>
<html>
<head>
<title>Belajar JSP Directive tag page</title>
</head>
<body>
Sekarang adalah hari: <%= new Date().toLocaleString() %>
</body>
</html>
<html>
<head>
<title>Belajar JSP Expresion</title>
</head>
<body>
<%--ini contoh jsp expration--%>
Hari ini adalah hari <%= new java.util.Date().toLocaleString() %>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Belajar JSP Implicit Object</title>
</head>
<body>
<form action="#">
<div>
<label for="nim">NIM</label>
<input type="text" id="nim" name="nim" readonly value='<%= request.getParameter("nim") %>'/>
</div>
<div>
<label for="nama">Nama Lengkap</label>
<input type="text" name="namaLengkap" id="nama" readonly value='<%= request.getParameter("namaLengkap") %>'>
</div>
<div>
<label for="tanggal">Tanggal Lahir</label>
<input type="text" name="tanggal" id="tanggal" readonly value='<%= request.getParameter("tanggalLahir") %>'>
</div>
</form>
</body>
</html>
package belajar.java.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/servlet-annotation"}, name = "configAnnotation")
public class ServletAnnotation extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// lakukan proses get
}
}
package belajar.java.web.controller;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
@Slf4j
@WebServlet(name = "servlet-handle-file-request", urlPatterns = {"/kirim-file"})
@MultipartConfig
public class ServletHandleFileRequest extends HttpServlet {
//language=HTML
String html = "<!doctype html>\n" +
"<html lang='en'>\n" +
"<head>\n" +
" " +
"<meta charset='UTF-8'>\n" +
" <meta name='viewport'\n" +
" content='width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'>\n" +
" <meta http-equiv='X-UA-Compatible' content='ie=edge'>\n" +
" <title>Data Mahasiswa</title>\n" +
"</head>\n" +
"<body>\n" +
"<table>\n" +
" <thead>\n" +
" <tr>\n" +
" <td>NIM</td>\n" +
" <td>Nama</td>\n" +
" <td>Kota</td>\n" +
" <td>Tanggal Lahir</td>\n" +
" <td>Foto</td>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n" +
" " +
" <td>%s</td>\n" +
" " +
" <td>%s</td>\n" +
" " +
" <td>%s</td>\n" +
" " +
" <td>%s</td>\n" +
" " +
" <td>%s</td>\n" +
" " +
"</tr>\n" +
" </tbody>\n" +
"</table>\n" +
"</body>\n" +
"</html>";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String nim = req.getParameter("nim");
String nama = req.getParameter("nama");
String kota = req.getParameter("kota");
String tanggalLahir = req.getParameter("tanggalLahir");
Part file = req.getPart("foto");
String fileName = this.getSubmittedFileName(file);
log.info("data http POST: {nim: {}, nama: {}, kota: {}, tanggalLahir: {}, fileName: {}}",
nim, nama, kota, tanggalLahir, fileName);
StringBuilder url = new StringBuilder(System.getProperty("user.home")).append(File.separator)
.append("Downloads").append(File.separator)
.append(fileName);
File location = new File(url.toString());
try (InputStream stream = file.getInputStream()) {
Files.copy(stream, location.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
resp.getWriter().print(
String.format(html, nim, nama, kota, tanggalLahir, fileName)
);
}
private String getSubmittedFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
package com.maryanto.dimas.bootcamp.servlet.listener;
import com.maryanto.dimas.bootcamp.servlet.service.DatabaseService;
import lombok.extern.slf4j.Slf4j;
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.io.PrintWriter;
@Slf4j
@WebServlet(name = "servlet-listener-request", urlPatterns = {"/listener-service"})
public class ServletListenerRequest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DatabaseService service = (DatabaseService) getServletContext().getAttribute("db");
log.info("user: {}", service);
PrintWriter writer = resp.getWriter();
writer.print("OK!");
}
}
<html>
<head><title>Belajar Web Pages dengan JSP</title></head>
<body>
<!-- ini syntax JSP dengan xml format -->
<jsp:scriptlet>
out.println("Ini sintax JSP lagi");
</jsp:scriptlet>
<!-- ini syntax JSP dengan mode expresion -->
<% out.println("Ini sintax JSP"); %>
</body>
</html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="format" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="now" value="<%= new java.util.Date()%>"/>
<html>
<head>
<%-- include js and css with webjars --%>
<link rel="stylesheet" href="<c:url value="webjars/bootstrap/4.5.2/css/bootstrap.min.css"/>">
<link rel="stylesheet" href="<c:url value="webjars/datatables/1.10.21/css/dataTables.bootstrap4.min.css"/>">
<link rel="stylesheet" href="<c:url value="webjars/datatables-buttons/1.6.1/css/buttons.bootstrap4.min.css"/>">
<link rel="stylesheet" href="<c:url value="webjars/datatables-colreorder/1.5.1-1/css/colReorder.bootstrap4.min.css"/>">
<link rel="stylesheet" href="<c:url value="webjars/datatables-colvis/1.1.1/css/dataTables.colVis.css"/>">
<link rel="stylesheet" href="<c:url value="webjars/datatables-responsive/2.2.3/css/responsive.bootstrap4.min.css"/>">
<script src="<c:url value="webjars/bootstrap/4.5.2/js/bootstrap.bundle.min.js"/>"></script>
<script src="<c:url value="webjars/jquery/3.5.1/jquery.min.js"/>"></script>
<script src="<c:url value="webjars/popper.js"/>"></script>
<script src="<c:url value="webjars/datatables.net/1.10.19/js/jquery.dataTables.min.js"/>"></script>
<script src="<c:url value="webjars/datatables/1.10.21/js/dataTables.bootstrap4.min.js"/>"></script>
<script src="<c:url value="webjars/datatables-buttons/1.6.1/js/buttons.bootstrap4.min.js"/>"></script>
<script src="<c:url value="webjars/datatables-colreorder/1.5.1-1/js/colReorder.bootstrap4.min.js"/>"></script>
<script src="<c:url value="webjars/datatables-colvis/1.1.1/js/dataTables.colVis.js"/>"></script>
<script src="<c:url value="webjars/datatables-responsive/2.2.3/js/responsive.bootstrap4.min.js"/>"></script>
<title>Learning Styling for JSP</title>
</head>
<body class="container">
<h2>Belajar JSP dengan JSTL @ <format:formatDate value="${now}" pattern="dd/MMM/yyyy"/></h2>
<hr>
<h3>Card with Bootstrap </h3>
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's
content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
<h3>List with Bootstrap</h3>
<div class="card" style="width: 18rem;">
<ul class="list-group list-group-flush">
<li class="list-group-item">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
</div>
<hr>
<h3>Form With Bootstrap</h3>
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<hr>
<h3>Tables with JQuery Datatables</h3>
<table class="table" id="datatables">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
<%--include js & css--%>
<script>
$(document).ready(() => {
console.log('element jquery loaded!');
$('#datatables').dataTable();
});
</script>
</body>
</html>
<html>
<head>
<title>Mengirim data dengan GET</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Mengirim data menggunakan method GET</h3>
<form action="kirim-get" method="GET">
<div>
<label for="nim">NIM</label>
<input name="nim" id="nim" pattern="Input NIM" size="8" maxlength="8" />
</div>
<div>
<label for="nama">Nama</label>
<input name="nama" id="nama" pattern="Input Nama" size="25" maxlength="20"/>
</div>
<div>
<input type="submit" value="Kirim" />
</div>
</form>
</body>
</html>
package belajar.java.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/kirim-get"})
public class SubmitGetController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// untuk mendapatkan nilai dari parameter-parameter
String nim = req.getParameter("nim");
String nama = req.getParameter("nama");
// untuk menampilkan ke web browser
resp.getWriter().println("NIM: " + nim + ", Nama: " + nama);
}
}
<html>
<head>
<title>Mengirim data dengan POST</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Mengirim data menggunakan method POST</h3>
<form action="kirim-post" method="POST">
<div>
<label for="nim">NIM</label>
<input name="nim" id="nim" size="8" placeholder="Input NIM" maxlength="8" />
</div>
<div>
<label for="nama">Nama</label>
<input name="nama" id="nama" placeholder="Input Nama" size="25" maxlength="20"/>
</div>
<div>
<input type="submit" value="Kirim" />
</div>
</form>
</body>
</html>
package belajar.java.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/kirim-post")
public class SubmitPostController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// untuk mendapatkan nilai dari parameter-parameter
String nim = req.getParameter("nim");
String nama = req.getParameter("nama");
// untuk menampilkan ke web browser
resp.getWriter().println("NIM: " + nim + ", Nama: " + nama);
}
}
package com.maryanto.dimas.bootcamp.servlet.listener;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@Slf4j
@WebListener
public class UserLogonCountingListener implements HttpSessionListener {
private ServletContext context;
private Integer total = 0;
private Integer current = 0;
@Override
public void sessionCreated(HttpSessionEvent event) {
this.total += 1;
this.current += 1;
log.info("totalUser: {}, currentUser: {}", total, current);
this.context = event.getSession().getServletContext();
this.context.setAttribute("totalUser", total);
this.context.setAttribute("currentUser", current);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
current -= 1;
this.context.setAttribute("currentUser", current);
log.info("totalUser: {}, currentUser: {}", total, current);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment