JAVA-3526: Moved spring-mvc-java inside spring-web-modules

This commit is contained in:
sampadawagde
2020-12-29 23:44:00 +05:30
parent a2e1762319
commit 9b1344a054
80 changed files with 2 additions and 2 deletions

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,16 @@
## Spring MVC with Java Configuration
This module contains articles about Spring MVC with Java configuration
### The Course
The "REST With Spring" Classes: https://bit.ly/restwithspring
### Relevant Articles:
- [Integration Testing in Spring](https://www.baeldung.com/integration-testing-in-spring)
- [File Upload with Spring MVC](https://www.baeldung.com/spring-file-upload)
- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit)
- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files)
- [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config)
- [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml)
- [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js)

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,270 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-mvc-java</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-java</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${javax-servlet-api.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- common -->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>${htmlunit.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
<exclusion>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
<version>${json-path.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<configuration>
<wait>false</wait>
</configuration>
<executions>
<execution>
<id>start-server</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- persistence -->
<hibernate.version>6.0.10.Final</hibernate.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
<!-- various -->
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-fileupload.version>1.3.2</commons-fileupload.version>
<commons-io.version>2.5</commons-io.version>
<commons-fileupload.version>1.4</commons-fileupload.version>
<jsonpath.version>2.2.0</jsonpath.version>
<!-- testing -->
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<rest-assured.version>3.0.7</rest-assured.version>
<net.sourceforge.htmlunit>2.23</net.sourceforge.htmlunit>
<!-- maven plugins -->
<maven-war-plugin.version>3.2.2</maven-war-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<maven-resources-plugin.version>3.1.0</maven-resources-plugin.version>
<!-- AspectJ -->
<aspectj.version>1.9.1</aspectj.version>
<!-- excel -->
<poi.version>3.16-beta1</poi.version>
<javax.el.version>3.0.1-b09</javax.el.version>
<javax.version>4.0.1</javax.version>
<javax-servlet-api.version>2.3.3</javax-servlet-api.version>
<htmlunit.version>2.32</htmlunit.version>
<json-path.version>2.4.0</json-path.version>
<start-class>com.baeldung.SpringMVCApplication</start-class>
</properties>
</project>

View File

@@ -0,0 +1,12 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class SpringMVCApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringMVCApplication.class, args);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.accessparamsjs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.accessparamsjs;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* Sample rest controller for the tutorial article
* "Access Spring MVC Model object in JavaScript".
*
* @author Andrew Shcherbakov
*
*/
@RestController
public class Controller {
/**
* Define two model objects (one integer and one string) and pass them to the view.
*
* @param model
* @return
*/
@RequestMapping("/index")
public ModelAndView thymeleafView(Map<String, Object> model) {
model.put("number", 1234);
model.put("message", "Hello from Spring MVC");
return new ModelAndView("thymeleaf/index");
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.cache;
import com.baeldung.model.Book;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
public class BookService {
@Cacheable(value="books", keyGenerator="customKeyGenerator")
public List<Book> getBooks() {
List<Book> books = new ArrayList<Book>();
books.add(new Book(1, "The Counterfeiters", "André Gide"));
books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
return books;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.cache;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
public class CustomKeyGenerator implements KeyGenerator {
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getSimpleName() + "_" + method.getName() + "_"
+ StringUtils.arrayToDelimitedString(params, "_");
}
}

View File

@@ -0,0 +1,185 @@
package com.baeldung.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.DateUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class ExcelPOIHelper {
public Map<Integer, List<MyCell>> readExcel(String fileLocation) throws IOException {
Map<Integer, List<MyCell>> data = new HashMap<>();
FileInputStream fis = new FileInputStream(new File(fileLocation));
if (fileLocation.endsWith(".xls")) {
data = readHSSFWorkbook(fis);
} else if (fileLocation.endsWith(".xlsx")) {
data = readXSSFWorkbook(fis);
}
int maxNrCols = data.values().stream()
.mapToInt(List::size)
.max()
.orElse(0);
data.values().stream()
.filter(ls -> ls.size() < maxNrCols)
.forEach(ls -> {
IntStream.range(ls.size(), maxNrCols)
.forEach(i -> ls.add(new MyCell("")));
});
return data;
}
private String readCellContent(Cell cell) {
String content;
switch (cell.getCellTypeEnum()) {
case STRING:
content = cell.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
content = cell.getDateCellValue() + "";
} else {
content = cell.getNumericCellValue() + "";
}
break;
case BOOLEAN:
content = cell.getBooleanCellValue() + "";
break;
case FORMULA:
content = cell.getCellFormula() + "";
break;
default:
content = "";
}
return content;
}
private Map<Integer, List<MyCell>> readHSSFWorkbook(FileInputStream fis) throws IOException {
Map<Integer, List<MyCell>> data = new HashMap<>();
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
HSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
HSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
short[] rgbColor = bgColor.getTriplet();
myCell.setBgColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
HSSFFont font = cell.getCellStyle()
.getFont(workbook);
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
HSSFColor textColor = font.getHSSFColor(workbook);
if (textColor != null) {
short[] rgbColor = textColor.getTriplet();
myCell.setTextColor("rgb(" + rgbColor[0] + "," + rgbColor[1] + "," + rgbColor[2] + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
private Map<Integer, List<MyCell>> readXSSFWorkbook(FileInputStream fis) throws IOException {
XSSFWorkbook workbook = null;
Map<Integer, List<MyCell>> data = new HashMap<>();
try {
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<>());
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
XSSFCell cell = row.getCell(j);
if (cell != null) {
XSSFCellStyle cellStyle = cell.getCellStyle();
MyCell myCell = new MyCell();
XSSFColor bgColor = cellStyle.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgbColor = bgColor.getRGB();
myCell.setBgColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
XSSFFont font = cellStyle.getFont();
myCell.setTextSize(font.getFontHeightInPoints() + "");
if (font.getBold()) {
myCell.setTextWeight("bold");
}
XSSFColor textColor = font.getXSSFColor();
if (textColor != null) {
byte[] rgbColor = textColor.getRGB();
myCell.setTextColor("rgb(" + (rgbColor[0] < 0 ? (rgbColor[0] + 0xff) : rgbColor[0]) + "," + (rgbColor[1] < 0 ? (rgbColor[1] + 0xff) : rgbColor[1]) + "," + (rgbColor[2] < 0 ? (rgbColor[2] + 0xff) : rgbColor[2]) + ")");
}
myCell.setContent(readCellContent(cell));
data.get(i)
.add(myCell);
} else {
data.get(i)
.add(new MyCell(""));
}
}
}
}
} finally {
if (workbook != null) {
workbook.close();
}
}
return data;
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.excel;
public class MyCell {
private String content;
private String textColor;
private String bgColor;
private String textSize;
private String textWeight;
public MyCell() {
}
public MyCell(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTextColor() {
return textColor;
}
public void setTextColor(String textColor) {
this.textColor = textColor;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextWeight() {
return textWeight;
}
public void setTextWeight(String textWeight) {
this.textWeight = textWeight;
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.filters;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/uppercase")
public class EmptyParamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
String inputString = servletRequest.getParameter("input");
if (inputString != null && inputString.matches("[A-Za-z0-9]+")) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
servletResponse.getWriter().println("Missing input parameter");
}
}
@Override
public void destroy() {
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
context.setAttribute("counter", 0);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent event) {
}
@Override
public void requestDestroyed(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest)event.getServletRequest();
if (!request.getServletPath().equals("/counter")) {
ServletContext context = event.getServletContext();
context.setAttribute("counter", (int)context.getAttribute("counter") + 1);
}
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.model;
public class Article {
public static final Article DEFAULT_ARTICLE = new Article(12);
private Integer id;
public Article(Integer articleId) {
this.id = articleId;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "Article [id=" + id + "]";
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.model;
public class Book {
private int id;
private String author;
private String title;
public Book() {
}
public Book(int id, String author, String title) {
this.id = id;
this.author = author;
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.model;
import org.springframework.web.multipart.MultipartFile;
public class FormDataWithFile {
private String name;
private String email;
private MultipartFile file;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.model;
public class Greeting {
private int id;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.model;
public class User {
private String firstname;
private String lastname;
private String emailId;
public String getFirstname() {
return firstname;
}
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(final String lastname) {
this.lastname = lastname;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(final String emailId) {
this.emailId = emailId;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.servlets;
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;
@WebServlet(urlPatterns = "/counter", name = "counterServlet")
public class CounterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
int count = (int)request.getServletContext().getAttribute("counter");
out.println("Request counter: " + count);
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.servlets;
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;
@WebServlet(urlPatterns = "/uppercase", name = "uppercaseServlet")
public class UppercaseServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String inputString = request.getParameter("input").toUpperCase();
PrintWriter out = response.getWriter();
out.println(inputString);
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.spring.web.config;
import com.baeldung.cache.CustomKeyGenerator;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@EnableCaching
@Configuration
public class ApplicationCacheConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
Cache booksCache = new ConcurrentMapCache("books");
cacheManager.setCaches(Arrays.asList(booksCache));
return cacheManager;
}
@Bean("customKeyGenerator")
public KeyGenerator keyGenerator() {
return new CustomKeyGenerator();
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.spring.web.config;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MainWebAppInitializer implements WebApplicationInitializer {
private String TMP_FOLDER = "/tmp";
private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024;
@Override
public void onStartup(ServletContext sc) throws ServletException {
ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(
new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER,
MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
appServlet.setMultipartConfig(multipartConfigElement);
}
}

View File

@@ -0,0 +1,132 @@
package com.baeldung.spring.web.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.util.UrlPathHelper;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
import com.baeldung.excel.ExcelPOIHelper;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.baeldung.web.controller" })
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ITemplateResolver templateResolver() {
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(byteArrayHttpMessageConverter());
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
@Override
public void configurePathMatch(final PathMatchConfigurer configurer) {
final UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
@Bean
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();
}
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanA {
@Autowired
private BeanB b;
public BeanA() {
super();
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.web;
import org.springframework.stereotype.Component;
@Component
public class BeanB {
public BeanB() {
super();
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.baeldung.excel.*;
import java.util.Map;
import java.util.List;
import javax.annotation.Resource;
@Controller
public class ExcelController {
private String fileLocation;
@Resource(name = "excelPOIHelper")
private ExcelPOIHelper excelPOIHelper;
@RequestMapping(method = RequestMethod.GET, value = "/excelProcessing")
public String getExcelProcessingPage() {
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/uploadExcelFile")
public String uploadFile(Model model, MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename();
FileOutputStream f = new FileOutputStream(fileLocation);
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!");
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readPOI")
public String readPOI(Model model) throws IOException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xlsx") || fileLocation.endsWith(".xls")) {
Map<Integer, List<MyCell>> data = excelPOIHelper.readExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid excel file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.baeldung.model.FormDataWithFile;
@Controller
public class FileUploadController {
@RequestMapping(value = "/fileUpload", method = RequestMethod.GET)
public String displayForm() {
return "fileUploadForm";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) {
modelMap.addAttribute("file", file);
return "fileUploadView";
}
@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) {
modelMap.addAttribute("files", files);
return "fileUploadView";
}
@RequestMapping(value = "/uploadFileWithAddtionalData", method = RequestMethod.POST)
public String submit(@RequestParam final MultipartFile file, @RequestParam final String name, @RequestParam final String email, final ModelMap modelMap) {
modelMap.addAttribute("name", name);
modelMap.addAttribute("email", email);
modelMap.addAttribute("file", file);
return "fileUploadView";
}
@RequestMapping(value = "/uploadFileModelAttribute", method = RequestMethod.POST)
public String submit(@ModelAttribute final FormDataWithFile formDataWithFile, final ModelMap modelMap) {
modelMap.addAttribute("formDataWithFile", formDataWithFile);
return "fileUploadView";
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.web.controller;
import com.baeldung.model.Greeting;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class GreetController {
@RequestMapping(value = "/homePage", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/greet", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Greeting greet() {
Greeting greeting = new Greeting();
greeting.setId(1);
greeting.setMessage("Hello World!!!");
return greeting;
}
@RequestMapping(value = "/greetWithPathVariable/{name}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Greeting greetWithPathVariable(@PathVariable("name") String name) {
Greeting greeting = new Greeting();
greeting.setId(1);
greeting.setMessage("Hello World " + name + "!!!");
return greeting;
}
@RequestMapping(value = "/greetWithQueryVariable", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Greeting greetWithQueryVariable(@RequestParam("name") String name) {
Greeting greeting = new Greeting();
greeting.setId(1);
greeting.setMessage("Hello World " + name + "!!!");
return greeting;
}
@RequestMapping(value = "/greetWithPost", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Greeting greetWithPost() {
Greeting greeting = new Greeting();
greeting.setId(1);
greeting.setMessage("Hello World!!!");
return greeting;
}
@RequestMapping(value = "/greetWithPostAndFormData", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Greeting greetWithPostAndFormData(@RequestParam("id") int id, @RequestParam("name") String name) {
Greeting greeting = new Greeting();
greeting.setId(id);
greeting.setMessage("Hello World " + name + "!!!");
return greeting;
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.web.controller;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ImageController {
@Autowired
ServletContext servletContext;
@RequestMapping(value = "/image-byte-array", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public @ResponseBody byte[] getImageAsByteArray() throws IOException {
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
return IOUtils.toByteArray(in);
}
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.web.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class MultipartFileUploadStubController {
@PostMapping("/stub/multipart")
public ResponseEntity<UploadResultResource> uploadFile(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) {
UploadResultResource result = new UploadResultResource(file, text, text1, text2, upstream);
return new ResponseEntity<>(result, HttpStatus.OK);
}
public static class UploadResultResource {
private final String file;
private final String text;
private final String text1;
private final String text2;
private final String upstream;
public UploadResultResource(MultipartFile file, String text, String text1, String text2, MultipartFile upstream) {
this.file = format(file);
this.text = text;
this.text1 = text1;
this.text2 = text2;
this.upstream = format(upstream);
}
private static String format(MultipartFile file) {
return file == null ? null : file.getOriginalFilename() + " (size: " + file.getSize() + " bytes)";
}
public String getFile() {
return file;
}
public String getText() {
return text;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
public String getUpstream() {
return upstream;
}
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SampleController {
@GetMapping("/sample")
public String showForm() {
return "sample";
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.web.controller;
import com.baeldung.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class UserController {
@GetMapping("/")
public String showForm(final Model model) {
final User user = new User();
user.setFirstname("John");
user.setLastname("Roy");
user.setEmailId("John.Roy@gmail.com");
model.addAttribute("user", user);
return "index";
}
@PostMapping("/processForm")
public String processForm(@ModelAttribute(value = "user") final User user, final Model model) {
// Insert User into DB
model.addAttribute("name", user.getFirstname() + " " + user.getLastname());
return "hello";
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.web.controller.message;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/message")
public class MessageController {
@RequestMapping(value = "/showForm", method = RequestMethod.GET)
public String showForm() {
return "message";
}
@RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@RequestParam("message") final String message, final Model model) {
model.addAttribute("message", message);
return "message";
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.web.controller.optionalpathvars;
import static com.baeldung.model.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.model.Article;
@RestController
public class ArticleViewerController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id") Integer articleId) {
if (articleId != null) {
return new Article(articleId);
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.web.controller.optionalpathvars;
import static com.baeldung.model.Article.DEFAULT_ARTICLE;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.model.Article;
@RestController
@RequestMapping(value = "/mapParam")
public class ArticleViewerWithMapParamController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable Map<String, String> pathVarsMap) {
String articleId = pathVarsMap.get("id");
if (articleId != null) {
return new Article(Integer.valueOf(articleId));
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.web.controller.optionalpathvars;
import static com.baeldung.model.Article.DEFAULT_ARTICLE;
import java.util.Optional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.model.Article;;
@RestController
@RequestMapping("/optionalParam")
public class ArticleViewerWithOptionalParamController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id") Optional<Integer> optionalArticleId) {
if(optionalArticleId.isPresent()) {
Integer articleId = optionalArticleId.get();
return new Article(articleId);
}else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.web.controller.optionalpathvars;
import static com.baeldung.model.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.model.Article;;
@RestController
@RequestMapping(value = "/requiredAttribute")
public class ArticleViewerWithRequiredAttributeController {
@RequestMapping(value = {"/article", "/article/{id}"})
public Article getArticle(@PathVariable(name = "id", required = false) Integer articleId) {
if (articleId != null) {
return new Article(articleId);
} else {
return DEFAULT_ARTICLE;
}
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.web.controller.optionalpathvars;
import static com.baeldung.model.Article.DEFAULT_ARTICLE;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.model.Article;
@RestController
@RequestMapping(value = "/seperateMethods")
public class ArticleViewerWithTwoSeparateMethodsController {
@RequestMapping(value = "/article/{id}")
public Article getArticle(@PathVariable(name = "id") Integer articleId) {
return new Article(articleId);
}
@RequestMapping(value = "/article")
public Article getDefaultArticle() {
return DEFAULT_ARTICLE;
}
}

View File

@@ -0,0 +1 @@
engine.fuelType=petrol

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.baeldung.annotations.Bike" name="bike">
<property name="color" value="green" />
</bean>
</beans>

View File

@@ -0,0 +1,5 @@
server.servlet.context-path=/spring-mvc-java
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=1MB
spring.servlet.multipart.enabled=true
spring.servlet.multipart.location=${java.io.tmpdir}

View File

@@ -0,0 +1,19 @@
<?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>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1 @@
welcome.text=Hello

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="org.baeldung.controller.xml" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Access Spring MVC params</title>
<script src="/js/jquery.js"></script>
<script src="/js/script-async.js"></script>
<script src="/js/script-async-jquery.js"></script>
<script>
var number = [[${number}]];
var message = "[[${message}]]";
</script>
</head>
<body>
Number=
<span th:text="${number}" th:remove="tag"></span>
<br /> Message=
<span th:text="${message}" th:remove="tag"></span>
<h2>Data from the external JS file (due to loading order)</h2>
<div id="number-ext"></div>
<div id="message-ext"></div>
<h2>Asynchronous loading from external JS file (plain JS)</h2>
<div id="number-async"></div>
<div id="message-async"></div>
<h2>Asynchronous loading from external JS file (jQuery)</h2>
<div id="number-async-jquery"></div>
<div id="message-async-jquery"></div>
</body>
<script src="/js/script.js"></script>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

View File

@@ -0,0 +1,5 @@
<html>
<body>
<h1>Spring MVC - Integration Testing</h1>
</body>
</html>

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<mvc:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

View File

@@ -0,0 +1,6 @@
<!DOCTYPE html>
<html>
<body>
<div th:fragment="footer1">&copy; 2013 Footer</div>
</body>
</html>

View File

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
</head>
<body>
<span th:text="#{welcome.text}">Hi</span>
<span th:text="${name}"> John </span>!
<span custom:name="James">Test</span>
<div th:replace="footer :: footer1">&copy; 2013 The Static
Templates</div>
</body>
</html>

View File

@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Thymeleaf Spring Example</title>
</head>
<body>
Hello John!
<br></br>
<div>Please confirm your details</div>
<br></br>
<form action="#" th:action="@{/processForm}" th:object="${user}"
method="post">
<table>
<tr>
<td>Firstname :</td>
<td><input type="text" value="Firstname"
th:field="*{firstname}" /></td>
</tr>
<tr>
<td>Lastname :</td>
<td><input type="text" value="Lastname"
th:field="*{lastname}" /></td>
</tr>
<tr>
<td>EmailId :</td>
<td><input type="text" value="emailId"
th:field="*{emailId}" /></td>
</tr>
<tr>
<td align="center"><input type="submit" /></td>
</tr>
</table>
</form>
</body>
</html>

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
</head>
<body>
<form action="#" th:action="@{/message/processForm}" method="post">
Message: <input type="text" value="message" id="message" name="message"/>
<input type="submit" />
</form>
<span th:text="${message}" id="received"></span>
</body>
</html>

View File

@@ -0,0 +1,50 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ 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=ISO-8859-1">
<title>Excel Processing</title>
</head>
<body>
<c:url value="/uploadExcelFile" var="uploadFileUrl" />
<c:url value="/excelProcessing" var="resetUrl" />
<c:url value="/readPOI" var="readPOIUrl" />
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}">
<input type="file" name="file" accept=".xls,.xlsx" />
<input type="submit" value="Upload file" />
</form>
<br />
<form method="GET" action="${resetUrl}">
<input type="submit" value="Reset" />
</form>
<br /> ${message }
<br />
<br />
<form action="${readPOIUrl }">
<input type="submit" value="Display file content" />
</form>
<br />
<br />
<c:if test="${not empty data}">
<table style="border: 1px solid black; border-collapse: collapse;">
<c:forEach items="${data}" var="row">
<tr>
<c:forEach items="${row.value}" var="cell">
<td style="border:1px solid black;height:20px;width:100px;
background-color:${cell.bgColor};color:${cell.textColor};
font-weight:${cell.textWeight};font-size:${cell.textSize}pt;">
${cell.content}
</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

View File

@@ -0,0 +1,107 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload Example</title>
</head>
<body>
<h3>Enter The File to Upload (Single file)</h3>
<form:form method="POST" action="/spring-mvc-java/uploadFile" enctype="multipart/form-data">
<table>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
<br />
<h3>Enter The Files to Upload (Multiple files)</h3>
<form:form method="POST" action="/spring-mvc-java/uploadMultiFile" enctype="multipart/form-data">
<table>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="files" /></td>
</tr>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="files" /></td>
</tr>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="files" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
<br />
<h3>Fill the Form and Select a File (<code>@RequestParam</code>)</h3>
<form:form method="POST" action="/spring-mvc-java/uploadFileWithAddtionalData" enctype="multipart/form-data">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
<br />
<h3>Fill the Form and Select a File (<code>@ModelAttribute</code>)</h3>
<form:form method="POST" action="/spring-mvc-java/uploadFileModelAttribute" enctype="multipart/form-data">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Select a file to upload</td>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,79 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Spring MVC File Upload</title>
</head>
<body>
<h2>Submitted File (Single)</h2>
<table>
<tr>
<td>OriginalFileName :</td>
<td>${file.originalFilename}</td>
</tr>
<tr>
<td>Type :</td>
<td>${file.contentType}</td>
</tr>
</table>
<br />
<h2>Submitted Files (Multiple)</h2>
<table>
<c:forEach items="${files}" var="file">
<tr>
<td>OriginalFileName :</td>
<td>${file.originalFilename}</td>
</tr>
<tr>
<td>Type :</td>
<td>${file.contentType}</td>
</tr>
</c:forEach>
</table>
<br />
<h2>Submitted File with Data (<code>@RequestParam</code>)</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>Email :</td>
<td>${email}</td>
</tr>
<tr>
<td>OriginalFileName :</td>
<td>${file.originalFilename}</td>
</tr>
<tr>
<td>Type :</td>
<td>${file.contentType}</td>
</tr>
</table>
<br />
<h2>Submitted File with Data (<code>@ModelAttribute</code>)</h2>
<table>
<tr>
<td>Name :</td>
<td>${formDataWithFile.name}</td>
</tr>
<tr>
<td>Email :</td>
<td>${formDataWithFile.email}</td>
</tr>
<tr>
<td>OriginalFileName :</td>
<td>${formDataWithFile.file.originalFilename}</td>
</tr>
<tr>
<td>Type :</td>
<td>${formDataWithFile.file.contentType}</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,66 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Company Data</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('#ResponseBody-button').click(function() {
$.ajax({
url: 'http://localhost:8080/spring-mvc-java/companyResponseBody?callback=getCompanyData',
data: {
format: 'json'
},
type: 'GET',
jsonpCallback:'getCompanyData',
dataType: 'jsonp',
error: function() {
$('#infoResponseBody').html('<p>An error has occurred</p>');
},
success: function(data) {
console.log("sucess");
}
});
});
$('#ResponseEntity-button').click(function() {
console.log("ResponseEntity");
$.ajax({
url: 'http://localhost:8080/spring-mvc-java/companyResponseEntity?callback=getCompanyData',
data: {
format: 'json'
},
type: 'GET',
jsonpCallback:'getCompanyData',
dataType: 'jsonp',
error: function() {
$('#infoResponseEntity').html('<p>An error has occurred</p>');
},
success: function(data) {
console.log("sucess");
}
});
});
});
function getCompanyData(data) {
$("#response").append("<b>ID:</b> "+data.id+"<br/>");
$("#response").append("<b>NAME:</b> "+data.name+"<br/>");
$("#response").append("<br/>");
}
</script>
</head>
<body>
<!--Using @ResponseBody -->
<button id="ResponseBody-button">Send AJAX JSON-P request!</button>
<div id="response"></div>
</body>
</html>

View File

@@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@@ -0,0 +1,41 @@
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring MVC Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.spring.web.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
$(function() {
var node1 = document.createTextNode("message = " + message);
var node2 = document.createTextNode("number = " + number);
document.getElementById('message-async-jquery').append(node1);
document.getElementById('number-async-jquery').append(node2);
});

View File

@@ -0,0 +1,6 @@
window.onload = function() {
var node1 = document.createTextNode("message = " + message);
var node2 = document.createTextNode("number = " + number);
document.getElementById('message-async').append(node1);
document.getElementById('number-async').append(node2);
};

View File

@@ -0,0 +1,4 @@
var node1 = document.createTextNode("message = " + message);
var node2 = document.createTextNode("number = " + number);
document.getElementById('message-ext').append(node1);
document.getElementById('number-ext').append(node2);

View File

@@ -0,0 +1,29 @@
package com.baeldung.accessparamsjs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerUnitTest {
@Autowired
private MockMvc mvc;
@Test
public void whenRequestThymeleaf_thenStatusOk() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/index")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.htmlunit;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitAndJUnitLiveTest {
private WebClient webClient;
@Before
public void init() throws Exception {
webClient = new WebClient();
}
@After
public void close() throws Exception {
webClient.close();
}
@Test
public void givenAClient_whenEnteringBaeldung_thenPageTitleIsOk() throws Exception {
webClient.getOptions().setThrowExceptionOnScriptError(false);
HtmlPage page = webClient.getPage("http://www.baeldung.com/");
Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText());
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.htmlunit;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
import org.springframework.web.context.WebApplicationContext;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { TestConfig.class })
public class HtmlUnitAndSpringLiveTest {
@Autowired
private WebApplicationContext wac;
private WebClient webClient;
@Before
public void setup() {
webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build();
}
@Test
public void givenAMessage_whenSent_thenItShows() throws Exception {
String text = "Hello world!";
HtmlPage page;
String url = "http://localhost/message/showForm";
page = webClient.getPage(url);
HtmlTextInput messageText = page.getHtmlElementById("message");
messageText.setValueAttribute(text);
HtmlForm form = page.getForms().get(0);
HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit");
HtmlPage newPage = submit.click();
String receivedText = newPage.getHtmlElementById("received").getTextContent();
Assert.assertEquals(receivedText, text);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.htmlunit;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class HtmlUnitWebScrapingLiveTest {
private WebClient webClient;
@Before
public void init() throws Exception {
webClient = new WebClient();
}
@After
public void close() throws Exception {
webClient.close();
}
@Test
public void givenBaeldungArchive_whenRetrievingArticle_thenHasH1() throws Exception {
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(false);
final String url = "http://www.baeldung.com/full_archive";
final HtmlPage page = webClient.getPage(url);
final String xpath = "(//ul[@class='car-monthlisting']/li)[1]/a";
final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0);
final HtmlPage postPage = latestPostLink.click();
final List<Object> h1 = postPage.getByXPath("//h1");
Assert.assertTrue(h1.size() > 0);
}
}

View File

@@ -0,0 +1,47 @@
package com.baeldung.htmlunit;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.baeldung.web.controller.message" })
public class TestConfig implements WebMvcConfigurer {
@Autowired
private ServletContext ctx;
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public ServletContextTemplateResolver templateResolver() {
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
}

View File

@@ -0,0 +1,90 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import javax.servlet.ServletContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class, WebConfig.class })
public class GreetControllerIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
private static final String CONTENT_TYPE = "application/json";
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenWac_whenServletContext_thenItProvidesGreetController() {
final ServletContext servletContext = wac.getServletContext();
Assert.assertNotNull(servletContext);
Assert.assertTrue(servletContext instanceof MockServletContext);
Assert.assertNotNull(wac.getBean("greetController"));
}
@Test
public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/homePage")).andDo(print()).andExpect(MockMvcResultMatchers.view().name("index"));
}
@Test
public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
final MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/greet")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!")).andReturn();
Assert.assertEquals(CONTENT_TYPE, mvcResult.getResponse().getContentType());
}
@Test
public void givenGreetURIWithPathVariable_whenMockMVC_thenResponseOK() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John!!!"));
}
@Test
public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithPathVariable/{name}", "Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World Doe!!!"));
}
@Test
public void givenGreetURIWithQueryParameter_whenMockMVC_thenResponseOK() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!"));
}
@Test
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE))
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World!!!"));
}
@Test
public void givenGreetURIWithPostAndFormData_whenMockMVC_thenResponseOK() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1));
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.web.controller;
import io.restassured.RestAssured;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static io.restassured.RestAssured.given;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
@TestPropertySource(properties = {"spring.main.allow-bean-definition-overriding=true", "server.servlet.context-path=/"})
public class GreetControllerRealIntegrationTest {
@LocalServerPort
private int port;
@Before
public void setUp() {
RestAssured.port = port;
}
@Test
public void givenGreetURI_whenSendingReq_thenVerifyResponse() {
given().get("/greet")
.then()
.statusCode(200);
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
public class GreetControllerUnitTest {
private MockMvc mockMvc;
private static final String CONTENT_TYPE = "application/json";
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new GreetController()).build();
}
@Test
public void givenHomePageURI_whenMockMVC_thenReturnsIndexJSPViewName() throws Exception {
this.mockMvc.perform(get("/homePage")).andExpect(view().name("index"));
}
@Test
public void givenGreetURI_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(get("/greet")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!"));
}
@Test
public void givenGreetURIWithPathVariable_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(get("/greetWithPathVariable/John")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John!!!"));
}
@Test
public void givenGreetURIWithPathVariable_2_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(get("/greetWithPathVariable/{name}", "Doe")).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World Doe!!!"));
}
@Test
public void givenGreetURIWithQueryParameter_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(get("/greetWithQueryVariable").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World John Doe!!!"));
}
@Test
public void givenGreetURIWithPost_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPost")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE)).andExpect(jsonPath("$.message").value("Hello World!!!"));
}
@Test
public void givenGreetURIWithPostAndFormData_whenMockMVC_thenVerifyResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/greetWithPostAndFormData").param("id", "1").param("name", "John Doe")).andDo(print()).andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE))
.andExpect(jsonPath("$.message").value("Hello World John Doe!!!")).andExpect(jsonPath("$.id").value(1));
}
}

View File

@@ -0,0 +1,2 @@
### Relevant Articles:
- [WebAppConfiguration in Spring Tests](http://www.baeldung.com/spring-webappconfiguration)

View File

@@ -0,0 +1,55 @@
package com.baeldung.web.controller.optionalpathvars;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void whenIdPathVariableIsNotPassed_thenResponse500() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/article"))
.andExpect(MockMvcResultMatchers.status().isInternalServerError());
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.web.controller.optionalpathvars;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.model.Article;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerWithOptionalParamIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenOPtionalParam_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 154;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/optionalParam/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenOPtionalParam_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/optionalParam/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.web.controller.optionalpathvars;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.model.Article;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerControllerWithRequiredAttributeIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenRequiredAttributeIsFalse_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 154;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/requiredAttribute/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenRequiredAttributeIsFalse_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/requiredAttribute/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.web.controller.optionalpathvars;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.model.Article;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerWithMapParamIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenPathVarsMapParam_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/mapParam/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenPathVarsMapParam_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/mapParam/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.web.controller.optionalpathvars;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.model.Article;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebConfig.class })
public class ArticleViewerWithTwoSeparateMethodsIntegrationTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void givenTwoSeparateMethods_whenIdPathVariableIsPassed_thenResponseOK() throws Exception {
int articleId = 5;
this.mockMvc
.perform(MockMvcRequestBuilders.get("/seperateMethods/article/{id}", articleId))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId));
}
@Test
public void givenTwoSeparateMethods_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception {
this.mockMvc
.perform(MockMvcRequestBuilders.get("/seperateMethods/article"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId()));
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@@ -0,0 +1,21 @@
<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>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>