[JAVA-13854] Half list moved (#12598)
* [JAVA-13854] added parent module * [JAVA-13854] moved apache-tapestry(submodule) to web-modules(parent) * [JAVA-13854] moved bootique(submodule) to web-modules(parent) * [JAVA-13854] moved dropwizard(submodule) to web-modules(parent) * [JAVA-13854] moved blade(submodule) to web-modules(parent) * [JAVA-13854] moved java-lite(submodule) to web-modules(parent) * [JAVA-13854] moved jooby(submodule) to web-modules(parent) * [JAVA-13854] moved linkrest(submodule) to web-modules(parent) * [JAVA-13854] moved ninja(submodule) to web-modules(parent) * [JAVA-13854] moved ratpack(submodule) to web-modules(parent) * [JAVA-13854] moved resteasy(submodule) to web-modules(parent) * [JAVA-13854] moved restx(submodule) to web-modules(parent) * [JAVA-13854] moved spark-java(submodule) to web-modules(parent) * [JAVA-13854] moved vraptor(submodule) to web-modules(parent) * [JAVA-13854] delete modules that were moved * [JAVA-13854] * [JAVA-13854] * [JAVA-13854] delete ninja submodule + moved raml(submodule) to web-modules(parent) * [JAVA-13854] moved gwt(submodule) to web-modules(parent) * [JAVA-13854] moved jakarta-ee(submodule) to web-modules(parent) * [JAVA-13854] moved javax-servlets(submodule) to web-modules(parent) * [JAVA-13854] moved javax-servlets-2(submodule) to web-modules(parent) * [JAVA-13854] moved jee-7(submodule) to web-modules(parent) * [JAVA-13854] moved play-framework(not a module) to web-modules * [JAVA-13854] fix failing test * [JAVA-13854] moved struts-2(submodule) to web-modules(parent) * [JAVA-13854] moved wicket(submodule) to web-modules(parent) * [JAVA-13854] deleted modules that were moved to web-modules * JAVA-13854 Removed moved modules from the main pom.xml Co-authored-by: panagiotiskakos <panagiotis.kakos@libra-is.com> Co-authored-by: Dhawal Kapil <dhawalkapil@gmail.com>
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package com.baeldung;
|
||||
|
||||
public class Constants {
|
||||
|
||||
public static final String UPLOAD_DIRECTORY = "upload";
|
||||
public static final String DEFAULT_FILENAME = "default.file";
|
||||
|
||||
public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
|
||||
public static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
|
||||
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.controller;
|
||||
|
||||
import com.baeldung.service.StudentService;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
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 = "StudentServlet", urlPatterns = "/student-record")
|
||||
public class StudentServlet extends HttpServlet {
|
||||
|
||||
private final 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private String department;
|
||||
private long salary;
|
||||
|
||||
public Employee(int id, String name, String department, long salary) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.department = department;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + id;
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Employee other = (Employee) obj;
|
||||
if (id != other.id)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public void setDepartment(String department) {
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public long getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(long salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
public class Student {
|
||||
|
||||
private int id;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Student(int id, String firstName, String lastName) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.service;
|
||||
|
||||
import com.baeldung.model.Student;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class StudentService {
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*
|
||||
* Class which simplifies reading cookies from request.
|
||||
*/
|
||||
public class CookieReader {
|
||||
|
||||
private HttpServletRequest request;
|
||||
|
||||
/**
|
||||
* The constructor.
|
||||
*
|
||||
* @param request request from which cookies will be read
|
||||
*/
|
||||
public CookieReader(HttpServletRequest request) {
|
||||
this.request = request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads cookie by key from request.
|
||||
*
|
||||
* @param key the key of a cookie
|
||||
* @return returns cookie value
|
||||
*/
|
||||
public Optional<String> readCookie(String key) {
|
||||
return Arrays.stream(request.getCookies())
|
||||
.filter(c -> key.equals(c.getName()))
|
||||
.map(Cookie::getValue)
|
||||
.findAny();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet("/download")
|
||||
public class DownloadServlet extends HttpServlet {
|
||||
private final int ARBITARY_SIZE = 1048;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||
resp.setContentType("text/plain");
|
||||
resp.setHeader("Content-disposition", "attachment; filename=sample.txt");
|
||||
|
||||
try (InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt");
|
||||
OutputStream out = resp.getOutputStream()) {
|
||||
|
||||
byte[] buffer = new byte[ARBITARY_SIZE];
|
||||
|
||||
int numBytesRead;
|
||||
while ((numBytesRead = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, numBytesRead);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
|
||||
@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
|
||||
public class EmployeeServlet extends HttpServlet {
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
@Override
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException {
|
||||
|
||||
Employee employee = new Employee(1, "Karan", "IT", 5000);
|
||||
String employeeJsonString = this.gson.toJson(employee);
|
||||
|
||||
PrintWriter out = response.getWriter();
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
out.print(employeeJsonString);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
import static javax.servlet.RequestDispatcher.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/errorHandler")
|
||||
public class ErrorHandlerServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
resp.setContentType("text/html; charset=utf-8");
|
||||
try (PrintWriter writer = resp.getWriter()) {
|
||||
writer.write("<html><head><title>Error description</title></head><body>");
|
||||
writer.write("<h2>Error description</h2>");
|
||||
writer.write("<ul>");
|
||||
Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE)
|
||||
.forEach(e ->
|
||||
writer.write("<li>" + e + ":" + req.getAttribute(e) + " </li>")
|
||||
);
|
||||
writer.write("</ul>");
|
||||
writer.write("</html></body>");
|
||||
}
|
||||
|
||||
Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION);
|
||||
if (IllegalArgumentException.class.isInstance(exception)) {
|
||||
getServletContext().log("Error on an application argument", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
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 = "FormServlet", urlPatterns = "/calculateServlet")
|
||||
public class FormServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
|
||||
|
||||
String height = request.getParameter("height");
|
||||
String weight = request.getParameter("weight");
|
||||
try {
|
||||
double bmi = calculateBMI(Double.parseDouble(weight), Double.parseDouble(height));
|
||||
request.setAttribute("bmi", bmi);
|
||||
response.setHeader("Test", "Success");
|
||||
response.setHeader("BMI", String.valueOf(bmi));
|
||||
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
|
||||
} catch (Exception e) {
|
||||
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
|
||||
dispatcher.forward(request, response);
|
||||
}
|
||||
|
||||
private Double calculateBMI(Double weight, Double height) {
|
||||
return weight / (height * height);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.*;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@WebServlet(name = "LoginServlet", urlPatterns = "/login")
|
||||
public class LoginServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
CookieReader cookieReader = new CookieReader(request);
|
||||
Optional<String> uiColor = cookieReader.readCookie("uiColor");
|
||||
Optional<String> userName = cookieReader.readCookie("userName");
|
||||
|
||||
request.setAttribute("uiColor", uiColor.orElse("blue"));
|
||||
|
||||
if (!userName.isPresent()) {
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/login.jsp");
|
||||
dispatcher.forward(request, response);
|
||||
} else {
|
||||
response.sendRedirect("/welcome");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
HttpSession session = request.getSession();
|
||||
session.setAttribute("sampleKey", "Sample Value");
|
||||
|
||||
String uiColor = request.getParameter("color");
|
||||
String userName = request.getParameter("name");
|
||||
|
||||
Cookie uiColorCookie = new Cookie("uiColor", uiColor);
|
||||
response.addCookie(uiColorCookie);
|
||||
|
||||
Cookie userNameCookie = new Cookie("userName", userName);
|
||||
response.addCookie(userNameCookie);
|
||||
|
||||
response.sendRedirect("/welcome");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
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("/main")
|
||||
public class MainServlet extends HttpServlet {
|
||||
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import com.baeldung.Constants;
|
||||
|
||||
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.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
import static com.baeldung.Constants.UPLOAD_DIRECTORY;
|
||||
|
||||
@WebServlet(
|
||||
name = "MultiPartServlet",
|
||||
urlPatterns = {"/multiPartServlet"}
|
||||
)
|
||||
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
|
||||
public class MultipartServlet extends HttpServlet {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String getFileName(Part part) {
|
||||
for (String content : part.getHeader("content-disposition").split(";")) {
|
||||
if (content.trim().startsWith("filename"))
|
||||
return content.substring(content.indexOf("=") + 2, content.length() - 1);
|
||||
}
|
||||
return Constants.DEFAULT_FILENAME;
|
||||
}
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
|
||||
File uploadDir = new File(uploadPath);
|
||||
if (!uploadDir.exists())
|
||||
uploadDir.mkdir();
|
||||
|
||||
try {
|
||||
String fileName = "";
|
||||
for (Part part : request.getParts()) {
|
||||
fileName = getFileName(part);
|
||||
part.write(uploadPath + File.separator + fileName);
|
||||
}
|
||||
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
|
||||
} catch (FileNotFoundException fne) {
|
||||
request.setAttribute("message", "There was an error: " + fne.getMessage());
|
||||
}
|
||||
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet(name = "MyHttpServlet", urlPatterns = "/servlet-mapping")
|
||||
public class MyHttpServlet extends HttpServlet {
|
||||
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println(request.getParameter("function"));
|
||||
if ("getContextPath".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getContextPath());
|
||||
} else if ("getLocalAddr".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getLocalAddr());
|
||||
} else if ("getLocalName".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getLocalName());
|
||||
} else if ("getLocalPort".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getLocalPort());
|
||||
} else if ("getMethod".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getMethod());
|
||||
} else if ("getParameterNames".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getParameterNames());
|
||||
} else if ("getPathInfo".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getPathInfo());
|
||||
} else if ("getProtocol".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getProtocol());
|
||||
} else if ("getQueryString".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getQueryString());
|
||||
} else if ("getRequestedSessionId".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getRequestedSessionId());
|
||||
} else if ("getRequestURI".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getRequestURI());
|
||||
} else if ("getRequestURL".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getRequestURL());
|
||||
} else if ("getScheme".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getScheme());
|
||||
} else if ("getServerName".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getServerName());
|
||||
} else if ("getServerPort".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getServerPort());
|
||||
} else if ("getServletPath".equals(request.getParameter("function"))) {
|
||||
writer.println(request.getServletPath());
|
||||
} else {
|
||||
writer.println("INVALID FUNCTION");
|
||||
}
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.*;
|
||||
import javax.servlet.http.*;
|
||||
|
||||
@WebServlet(urlPatterns = "/randomError")
|
||||
public class RandomErrorServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, final HttpServletResponse resp) {
|
||||
throw new IllegalStateException("Random error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
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;
|
||||
|
||||
@WebServlet("/update")
|
||||
public class UpdateServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
HttpSession session = request.getSession(false);
|
||||
|
||||
if (session != null) {
|
||||
|
||||
session.setAttribute("userName", request.getParameter("userName"));
|
||||
session.setAttribute("age", request.getParameter("age"));
|
||||
|
||||
request.setAttribute("sessionData", session);
|
||||
}
|
||||
|
||||
request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static com.baeldung.Constants.*;
|
||||
|
||||
@WebServlet(
|
||||
name = "UploadServlet",
|
||||
urlPatterns = {"/uploadFile"}
|
||||
)
|
||||
public class UploadServlet extends HttpServlet {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
|
||||
if (ServletFileUpload.isMultipartContent(request)) {
|
||||
|
||||
DiskFileItemFactory factory = new DiskFileItemFactory();
|
||||
factory.setSizeThreshold(MEMORY_THRESHOLD);
|
||||
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
|
||||
|
||||
ServletFileUpload upload = new ServletFileUpload(factory);
|
||||
upload.setFileSizeMax(MAX_FILE_SIZE);
|
||||
upload.setSizeMax(MAX_REQUEST_SIZE);
|
||||
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
|
||||
File uploadDir = new File(uploadPath);
|
||||
if (!uploadDir.exists()) {
|
||||
uploadDir.mkdir();
|
||||
}
|
||||
|
||||
try {
|
||||
List<FileItem> formItems = upload.parseRequest(request);
|
||||
|
||||
if (formItems != null && formItems.size() > 0) {
|
||||
for (FileItem item : formItems) {
|
||||
if (!item.isFormField()) {
|
||||
String fileName = new File(item.getName()).getName();
|
||||
String filePath = uploadPath + File.separator + fileName;
|
||||
File storeFile = new File(filePath);
|
||||
item.write(storeFile);
|
||||
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
request.setAttribute("message", "There was an error: " + ex.getMessage());
|
||||
}
|
||||
getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
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(name = "UploadWelcomeServlet", urlPatterns = "/uploadwelcome")
|
||||
public class UploadWelcomeServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
request.getRequestDispatcher("/upload.jsp").forward(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
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;
|
||||
|
||||
@WebServlet("/u_login")
|
||||
public class UserLoginServlet extends HttpServlet {
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
HttpSession session = request.getSession();
|
||||
|
||||
session.setAttribute("userId", request.getParameter("userId"));
|
||||
|
||||
request.setAttribute("id", session.getAttribute("userId"));
|
||||
|
||||
request.getRequestDispatcher("/WEB-INF/jsp/userlogin.jsp").forward(request, response);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebInitParam;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet(name = "UserServlet", urlPatterns = "/userServlet", initParams={
|
||||
@WebInitParam(name="name", value="Not provided"),
|
||||
@WebInitParam(name="email", value="Not provided")})
|
||||
public class UserServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
processRequest(request, response);
|
||||
forwardRequest(request, response, "/WEB-INF/jsp/result.jsp");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
}
|
||||
|
||||
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
request.setAttribute("name", getRequestParameter(request, "name"));
|
||||
request.setAttribute("email", getRequestParameter(request, "email"));
|
||||
request.setAttribute("province", getContextParameter("province"));
|
||||
request.setAttribute("country", getContextParameter("country"));
|
||||
}
|
||||
|
||||
protected String getRequestParameter(HttpServletRequest request, String name) {
|
||||
String param = request.getParameter(name);
|
||||
return !param.isEmpty() ? param : getInitParameter(name);
|
||||
}
|
||||
|
||||
protected String getContextParameter(String name) {
|
||||
return getServletContext().getInitParameter(name);
|
||||
}
|
||||
|
||||
protected void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path)
|
||||
throws ServletException, IOException {
|
||||
request.getRequestDispatcher(path).forward(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Created by adam.
|
||||
*/
|
||||
@WebServlet(name = "WelcomeServlet", urlPatterns = "/welcome")
|
||||
public class WelcomeServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
CookieReader cookieReader = new CookieReader(request);
|
||||
Optional<String> uiColor = cookieReader.readCookie("uiColor");
|
||||
Optional<String> userName = cookieReader.readCookie("userName");
|
||||
|
||||
if (!userName.isPresent()) {
|
||||
response.sendRedirect("/login");
|
||||
} else {
|
||||
request.setAttribute("uiColor", uiColor.orElse("blue"));
|
||||
request.setAttribute("userName", userName.get());
|
||||
request.setAttribute("sessionAttribute", request.getSession()
|
||||
.getAttribute("sampleKey"));
|
||||
|
||||
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/welcome.jsp");
|
||||
dispatcher.forward(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
Cookie userNameCookieRemove = new Cookie("userName", "");
|
||||
userNameCookieRemove.setMaxAge(0);
|
||||
response.addCookie(userNameCookieRemove);
|
||||
|
||||
response.sendRedirect("/login");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,26 @@
|
||||
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
|
||||
<html>
|
||||
<head>
|
||||
<title>Calculate BMI</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<form name="bmiForm" action="calculateServlet" method="POST">
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td>Your Weight (kg) :</td>
|
||||
<td><input type="text" name="weight"/></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Your Height (m) :</td>
|
||||
<td><input type="text" name="height"/></td>
|
||||
</tr>
|
||||
<th><input type="submit" value="Submit" name="find"/></th>
|
||||
<th><input type="reset" value="Reset" name="reset" /></th>
|
||||
</table>
|
||||
<h2>${bmi}</h2>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%@ page contentType="text/html;charset=UTF-8"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello New User:</title>
|
||||
</head>
|
||||
<body style="background: ${uiColor}">
|
||||
<form name="userForm" action="login" method="POST">
|
||||
<label>Your Name:</label>
|
||||
<input type="text" name="name"/>
|
||||
|
||||
<label>UI Color:</label>
|
||||
<input type="text" name="color"/>
|
||||
|
||||
<button type="submit">Confirm</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
</head>
|
||||
<body>
|
||||
<form action="u_login">
|
||||
<p>Enter your User Id and Password</p>
|
||||
User ID: <input type="text" name="userId" /><br />
|
||||
Password: <input type="password" name="password" /> <br /> <input type="submit" value="Login" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>User Data</title>
|
||||
</head>
|
||||
<body>
|
||||
<h2>User Information</h2>
|
||||
<p><strong>Name:</strong> ${name}</p>
|
||||
<p><strong>Email:</strong> ${email}</p>
|
||||
<p><strong>Province:</strong> ${province}</p>
|
||||
<p><strong>Country:</strong> ${country}</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
|
||||
<%@ page import="com.baeldung.model.Student"%>
|
||||
<!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=ISO-8859-1">
|
||||
<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>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Hi, User : ${sessionData.getAttribute("userId")}
|
||||
|
||||
<br> Your User Data has been updated as below :
|
||||
<br> User Name: ${sessionData.getAttribute("userName")}
|
||||
<br> Age : ${sessionData.getAttribute("age")}
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
|
||||
pageEncoding="ISO-8859-1"%>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="ISO-8859-1">
|
||||
</head>
|
||||
<body>
|
||||
<p>Update your User Details:</p>
|
||||
|
||||
<form action="update">
|
||||
User ID: <input type="text" name="userId"
|
||||
value='<%=request.getAttribute("id")%>' disabled /><br /> User Name:
|
||||
<input type="text" name="userName" /> Age: <input type="number"
|
||||
name="age" /> <br /> <input type="submit" value="Update" />
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
<%@ page contentType="text/html;charset=UTF-8"%>
|
||||
<html>
|
||||
<head>
|
||||
<title>Hello Known User:</title>
|
||||
</head>
|
||||
<body style="background: ${uiColor}">
|
||||
<form action="welcome" method="POST">
|
||||
<label>Your name: ${userName}</label>
|
||||
<label>Session param: ${sessionAttribute}</label>
|
||||
<button type="submit">Logout</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
nice simple text file
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
|
||||
version="3.1">
|
||||
<context-param>
|
||||
<param-name>province</param-name>
|
||||
<param-value>Mendoza</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>country</param-name>
|
||||
<param-value>Argentina</param-value>
|
||||
</context-param>
|
||||
<error-page>
|
||||
<error-code>404</error-code>
|
||||
<location>/error-404.html</location> <!-- /src/main/webapp/error-404.html-->
|
||||
</error-page>
|
||||
|
||||
<error-page>
|
||||
<exception-type>java.lang.Exception</exception-type>
|
||||
<location>/errorHandler</location>
|
||||
</error-page>
|
||||
</web-app>
|
||||
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Error page</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h2>Error: Page not found</h2>
|
||||
|
||||
<a href="./">Go back home</a>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
|
||||
<!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>Upload Result</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h2>${message}</h2>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
|
||||
<!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>File Upload Demo</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div>Apache FileUpload</div>
|
||||
<form method="post" action="uploadFile" enctype="multipart/form-data">
|
||||
Choose a file: <input type="file" name="uploadFile"/><input type="submit" value="Upload"/>
|
||||
</form>
|
||||
|
||||
</br>
|
||||
|
||||
<div>Servlet Multipart</div>
|
||||
<form method="post" action="multiPartServlet" enctype="multipart/form-data">
|
||||
Choose a file: <input type="file" name="multiPartServlet"/><input type="submit" value="Upload"/>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Context and Servlet Initialization Parameters</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
</head>
|
||||
<body>
|
||||
<h2>Please fill the form below:</h2>
|
||||
<form action="${pageContext.request.contextPath}/userServlet" method="post">
|
||||
<label for="name"><strong>Name:</strong></label>
|
||||
<input type="text" name="name" id="name">
|
||||
<label for="email"><strong>Email:</strong></label>
|
||||
<input type="text" name="email" id="email">
|
||||
<input type="submit" value="Send">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.servlets;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.model.Employee;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EmployeeServletIntegrationTest {
|
||||
|
||||
@Mock
|
||||
HttpServletRequest httpServletRequest;
|
||||
|
||||
@Mock
|
||||
HttpServletResponse httpServletResponse;
|
||||
|
||||
Employee employee;
|
||||
|
||||
@Test
|
||||
public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception {
|
||||
|
||||
//Given
|
||||
int id = 1;
|
||||
String name = "Karan Khanna";
|
||||
String department = "IT";
|
||||
long salary = 5000;
|
||||
employee = new Employee(id, name, department, salary);
|
||||
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
when(httpServletResponse.getWriter()).thenReturn(pw);
|
||||
|
||||
EmployeeServlet employeeServlet = new EmployeeServlet();
|
||||
employeeServlet.doGet(httpServletRequest, httpServletResponse);
|
||||
|
||||
String employeeJsonString = sw.getBuffer().toString().trim();
|
||||
Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class);
|
||||
assertEquals(fetchedEmployee, employee);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class FormServletLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenPostRequestUsingHttpClient_thenCorrect() throws Exception {
|
||||
|
||||
HttpClient client = HttpClientBuilder.create().build();
|
||||
HttpPost method = new HttpPost("http://localhost:8080/calculateServlet");
|
||||
|
||||
List<BasicNameValuePair> nvps = new ArrayList<>();
|
||||
nvps.add(new BasicNameValuePair("height", String.valueOf(2)));
|
||||
nvps.add(new BasicNameValuePair("weight", String.valueOf(80)));
|
||||
|
||||
method.setEntity(new UrlEncodedFormEntity(nvps));
|
||||
HttpResponse httpResponse = client.execute(method);
|
||||
|
||||
assertEquals("Success", httpResponse.getHeaders("Test")[0].getValue());
|
||||
assertEquals("20.0", httpResponse.getHeaders("BMI")[0].getValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.test;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class UserServletUnitTest {
|
||||
|
||||
private static HttpServletRequest request;
|
||||
private static HttpServletResponse response;
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpHttpServletRequestMockInstance() {
|
||||
request = mock(HttpServletRequest.class);
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpHttpServletResponsetMockInstance() {
|
||||
response = mock(HttpServletResponse.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenCalledAtLeastOnce() {
|
||||
request.getParameter("name");
|
||||
verify(request, atLeast(1)).getParameter("name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpServletRequestMockInstance_whenCalledgetParameter_thenOneAssertion() {
|
||||
when(request.getParameter("name")).thenReturn("username");
|
||||
assertThat(request.getParameter("name")).isEqualTo("username");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenCalledAtLeastOnce() {
|
||||
response.getContentType();
|
||||
verify(response, atLeast(1)).getContentType();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHttpServletResponseMockInstance_whenCalledgetContentType_thenOneAssertion() {
|
||||
when(response.getContentType()).thenReturn("text/html");
|
||||
assertThat(response.getContentType()).isEqualTo("text/html");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user