JAVA-3531 Move spring-mvc-xml module

This commit is contained in:
mikr
2020-12-30 22:26:14 +01:00
parent 190844d810
commit 6e197ea4a6
55 changed files with 85 additions and 86 deletions

View File

@@ -0,0 +1,21 @@
package com.baeldung.jsp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExampleOne extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>" + "<head>" + "<meta charset=\"UTF-8\" />" + "<title>HTML Rendered by Servlet</title>" + "</head>" + "<body>" + "<h1>HTML Rendered by Servlet</h1></br>" + "<p>This page was rendered by the ExampleOne Servlet!</p>"
+ "</body>" + "</html>");
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.jsp;
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 = "ExampleThree", description = "JSP Servlet With Annotations", urlPatterns = { "/ExampleThree" })
public class ExampleThree extends HttpServlet {
private static final long serialVersionUID = 1L;
private String instanceMessage;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = request.getParameter("message");
instanceMessage = request.getParameter("message");
request.setAttribute("text", message);
request.setAttribute("unsafeText", instanceMessage);
request.getRequestDispatcher("/jsp/ExampleThree.jsp").forward(request, response);
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ImportResource("classpath:webMvcConfig.xml")
@Configuration
@ComponentScan
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {
super();
}
// API
}

View File

@@ -0,0 +1,62 @@
package com.baeldung.spring;
import java.util.Locale;
import java.util.ResourceBundle;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.ViewResolver;
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;
//@EnableWebMvc
//@Configuration
@ComponentScan("com.baeldung.spring")
public class ClientWebConfigJava implements WebMvcConfigurer {
public ClientWebConfigJava() {
super();
}
@Bean
public MessageSource messageSource() {
final ResourceBundleMessageSource ms = new ResourceBundleMessageSource();
ms.setBasenames("messages");
return ms;
}
@Bean
public ResourceBundle getBeanResourceBundle() {
final Locale locale = Locale.getDefault();
return new MessageSourceResourceBundle(messageSource(), locale);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.spring.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.ConstraintViolationException;
@ControllerAdvice
public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e, WebRequest request) {
return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ErrorController {
@RequestMapping(value = "500Error", method = RequestMethod.GET)
public void throwRuntimeException() {
throw new NullPointerException("Throwing a null pointer exception");
}
@RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {
ModelAndView errorPage = new ModelAndView("errorPage");
String errorMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code : 400 . Bad Request";
break;
}
case 401: {
errorMsg = "Http Error Code : 401. Unauthorized";
break;
}
case 404: {
errorMsg = "Http Error Code : 404. Resource not found";
break;
}
// Handle other 4xx error codes.
case 500: {
errorMsg = "Http Error Code : 500. Internal Server Error";
break;
}
// Handle other 5xx error codes.
}
errorPage.addObject("errorMsg", errorMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest.getAttribute("javax.servlet.error.status_code");
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.spring.controller;
import java.io.IOException;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baeldung.spring.form.GeoIP;
import com.baeldung.spring.service.RawDBDemoGeoIPLocationService;
//@Controller
//add db file and uncomment to see the working example
public class GeoIPTestController {
private RawDBDemoGeoIPLocationService locationService;
public GeoIPTestController() throws IOException {
locationService = new RawDBDemoGeoIPLocationService();
}
@RequestMapping(value = "/GeoIPTest", method = RequestMethod.POST)
@ResponseBody
public GeoIP getLocation(@RequestParam(value = "ipAddress", required = true) String ipAddress) throws Exception {
return locationService.getLocation(ipAddress);
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class GreetingController {
@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String get(ModelMap model) {
model.addAttribute("message", "Hello, World!");
return "greeting";
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
return model;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloGuestController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using ControllerClassNameHandlerMapping.");
return model;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloWorldController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("msg", "Welcome to Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using BeanNameUrlHandlerMapping.");
return model;
}
}

View File

@@ -0,0 +1,61 @@
package com.baeldung.spring.controller;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
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;
import org.springframework.web.context.support.ServletContextResource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class ImageController {
@Autowired
private ServletContext servletContext;
@RequestMapping(value = "/image-view", method = RequestMethod.GET)
public String imageView() throws IOException {
return "image-download";
}
@RequestMapping(value = "/image-manual-response", method = RequestMethod.GET)
public void getImageAsByteArray(HttpServletResponse response) throws IOException {
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
@RequestMapping(value = "/image-byte-array", method = RequestMethod.GET)
@ResponseBody
public byte[] getImageAsByteArray() throws IOException {
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
return IOUtils.toByteArray(in);
}
@RequestMapping(value = "/image-response-entity", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImageAsResponseEntity() throws IOException {
ResponseEntity<byte[]> responseEntity;
final HttpHeaders headers = new HttpHeaders();
final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg");
byte[] media = IOUtils.toByteArray(in);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK);
return responseEntity;
}
@RequestMapping(value = "/image-resource", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> getImageAsResource() {
final HttpHeaders headers = new HttpHeaders();
Resource resource = new ServletContextResource(servletContext, "/WEB-INF/images/image-example.jpg");
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}

View File

@@ -0,0 +1,83 @@
package com.baeldung.spring.controller;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import com.baeldung.spring.form.Person;
import com.baeldung.spring.validator.PersonValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
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.servlet.ModelAndView;
@Controller
public class PersonController {
@Autowired
PersonValidator validator;
@RequestMapping(value = "/person", method = RequestMethod.GET)
public ModelAndView showForm(final Model model) {
initData(model);
return new ModelAndView("personForm", "person", new Person());
}
@RequestMapping(value = "/addPerson", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("person") final Person person, final BindingResult result, final ModelMap modelMap, final Model model) {
validator.validate(person, result);
if (result.hasErrors()) {
initData(model);
return "personForm";
}
modelMap.addAttribute("person", person);
return "personView";
}
private void initData(final Model model) {
final List<String> favouriteLanguageItem = new ArrayList<String>();
favouriteLanguageItem.add("Java");
favouriteLanguageItem.add("C++");
favouriteLanguageItem.add("Perl");
model.addAttribute("favouriteLanguageItem", favouriteLanguageItem);
final List<String> jobItem = new ArrayList<String>();
jobItem.add("Full time");
jobItem.add("Part time");
model.addAttribute("jobItem", jobItem);
final Map<String, String> countryItems = new LinkedHashMap<String, String>();
countryItems.put("US", "United Stated");
countryItems.put("IT", "Italy");
countryItems.put("UK", "United Kingdom");
countryItems.put("FR", "Grance");
model.addAttribute("countryItems", countryItems);
final List<String> fruit = new ArrayList<String>();
fruit.add("Banana");
fruit.add("Mango");
fruit.add("Apple");
model.addAttribute("fruit", fruit);
final List<String> books = new ArrayList<String>();
books.add("The Great Gatsby");
books.add("Nineteen Eighty-Four");
books.add("The Lord of the Rings");
model.addAttribute("books", books);
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.spring.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.*;
@Controller
@RequestMapping("/public/api/1")
@Validated
public class RequestAndPathVariableValidationController {
@GetMapping("/name-for-day")
public String getNameOfDayByNumberRequestParam(@RequestParam @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/name-for-day/{dayOfWeek}")
public String getNameOfDayByPathVariable(@PathVariable("dayOfWeek") @Min(1) @Max(7) Integer dayOfWeek) {
return dayOfWeek + "";
}
@GetMapping("/valid-name")
public void validStringRequestParam(@RequestParam @NotBlank @Size(max = 10) @Pattern(regexp = "^[A-Z][a-zA-Z0-9]+$") String name) {
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.spring.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("msg", " Baeldung's Spring Handler Mappings Guide.<br>This request was mapped" + " using SimpleUrlHandlerMapping.");
return model;
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.spring.form;
public class GeoIP {
private String ipAddress;
private String city;
private String latitude;
private String longitude;
public GeoIP() {
}
public GeoIP(String ipAddress) {
this.ipAddress = ipAddress;
}
public GeoIP(String ipAddress, String city, String latitude, String longitude) {
this.ipAddress = ipAddress;
this.city = city;
this.latitude = latitude;
this.longitude = longitude;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}

View File

@@ -0,0 +1,153 @@
package com.baeldung.spring.form;
import java.util.List;
import javax.validation.constraints.NotEmpty;
import org.springframework.web.multipart.MultipartFile;
public class Person {
private long id;
private String name;
private String email;
private String dateOfBirth;
@NotEmpty
private String password;
private String sex;
private String country;
private String book;
private String job;
private boolean receiveNewsletter;
private String[] hobbies;
private List<String> favouriteLanguage;
private List<String> fruit;
private String notes;
private MultipartFile file;
public Person() {
super();
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(final String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(final String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(final String country) {
this.country = country;
}
public String getJob() {
return job;
}
public void setJob(final String job) {
this.job = job;
}
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(final boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(final String[] hobbies) {
this.hobbies = hobbies;
}
public List<String> getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(final List<String> favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getNotes() {
return notes;
}
public void setNotes(final String notes) {
this.notes = notes;
}
public List<String> getFruit() {
return fruit;
}
public void setFruit(final List<String> fruit) {
this.fruit = fruit;
}
public String getBook() {
return book;
}
public void setBook(final String book) {
this.book = book;
}
public MultipartFile getFile() {
return file;
}
public void setFile(final MultipartFile file) {
this.file = file;
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.spring.service;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import com.baeldung.spring.form.GeoIP;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
public class RawDBDemoGeoIPLocationService {
private DatabaseReader dbReader;
public RawDBDemoGeoIPLocationService() throws IOException {
File database = new File("your-path-to-db-file");
dbReader = new DatabaseReader.Builder(database).build();
}
public GeoIP getLocation(String ip) throws IOException, GeoIp2Exception {
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = dbReader.city(ipAddress);
String cityName = response.getCity().getName();
String latitude = response.getLocation().getLatitude().toString();
String longitude = response.getLocation().getLongitude().toString();
return new GeoIP(ip, cityName, latitude, longitude);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.spring.validator;
import com.baeldung.spring.form.Person;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class PersonValidator implements Validator {
@Override
public boolean supports(final Class calzz) {
return Person.class.isAssignableFrom(calzz);
}
@Override
public void validate(final Object obj, final Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name");
}
}

View File

@@ -0,0 +1,42 @@
<?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">
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<context:component-scan base-package="com.baeldung.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/sample.html" view-name="sample" />
<!-- Content strategy using path extension -->
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
<property name="favorParameter" value="true"/>
<property name="parameterName" value="mediaType"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="application/json" />
<property name="useJaf" value="false" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
</beans>

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,2 @@
required.name = Name is required!
NotEmpty.person.password = Password is required!

View File

@@ -0,0 +1,38 @@
<?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"
>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>image/jpeg</value>
<value>image/png</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.baeldung.spring.controller"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:view-controller path="/sample.html" view-name="sample"/>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="messages" />
</bean>
</beans>

View File

@@ -0,0 +1,84 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Geo IP Test</title>
<!--jquery dep -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready (function () {
// getting the public ip address from api and setting on text box
// ip api : https://www.ipify.org/
$.get( "https://api.ipify.org?format=json", function( data ) {
console.log(data);
$("#ip").val(data.ip) ;
});
function showLocationOnMap (location) {
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: Number(location.latitude), lng: Number(location.longitude)},
zoom: 15
});
var marker = new google.maps.Marker({
position: {lat: Number(location.latitude), lng: Number(location.longitude)},
map: map,
title: "Public IP:"+location.ipAddress+" @ "+location.city
});
}
$( "#ipForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
url: "GeoIPTest",
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // send as JSON
data: $.param( {ipAddress : $("#ip").val()} ),
complete: function(data) {
console.log ("Request complete");
},
success: function(data) {
$("#status").html(JSON.stringify(data));
if (data.ipAddress !=null) {
console.log ("Success:"+data.ipAddress);
showLocationOnMap(data);
}
},
error: function(err) {
console.log(err);
$("#status").html("Error:"+JSON.stringify(data));
},
});
});
});
</script>
</head>
<body>
<form id="ipForm" action="GeoIPTest" method="POST">
<input type="text" name = "ipAddress" id = "ip"/>
<input type="submit" name="submit" value="submit" />
</form>
<div id="status"></div>
<div id="map" style="height: 500px; width:100%; position:absolute"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-MAPS-API-KEY"
async defer></script>
</body>
</html>

View File

@@ -0,0 +1,14 @@
import org.crsh.cli.Command;
import org.crsh.cli.Usage;
import org.crsh.cli.Option;
class message {
@Usage("show my own message")
@Command
Object main(@Usage("custom message") @Option(names=["m","message"]) String message) {
if (message == null)
message = "No message given...";
return message;
}
}

View File

@@ -0,0 +1,14 @@
import org.crsh.command.BaseCommand;
import org.crsh.cli.Usage;
import org.crsh.cli.Command;
import org.crsh.cli.Option;
public class message2 extends BaseCommand {
@Usage("show my own message using java")
@Command
public Object main(@Usage("custom message") @Option(names = { "m", "message" }) String message) {
if (message == null)
message = "No message given...";
return message;
}
}

View File

@@ -0,0 +1 @@
crash.telnet.port=50001

View File

@@ -0,0 +1,65 @@
############################
# Telnet daemon properties #
############################
#####################
# Terminals Section #
#####################
# List of terminals available and defined below
terminals=vt100,ansi,windoof,xterm
# vt100 implementation and aliases
term.vt100.class=net.wimpi.telnetd.io.terminal.vt100
term.vt100.aliases=default,vt100-am,vt102,dec-vt100
# ansi implementation and aliases
term.ansi.class=net.wimpi.telnetd.io.terminal.ansi
term.ansi.aliases=color-xterm,xterm-color,vt320,vt220,linux,screen
# windoof implementation and aliases
term.windoof.class=net.wimpi.telnetd.io.terminal.Windoof
term.windoof.aliases=
# xterm implementation and aliases
term.xterm.class=net.wimpi.telnetd.io.terminal.xterm
term.xterm.aliases=
##################
# Shells Section #
##################
# List of shells available and defined below
shells=simple
# shell implementations
shell.simple.class=org.crsh.telnet.term.TelnetHandler
#####################
# Listeners Section #
#####################
listeners=std
# std listener specific properties
#Basic listener and connection management settings (port is commented because CRaSH configures it)
# std.port=5000
std.floodprotection=5
std.maxcon=25
# Timeout Settings for connections (ms)
std.time_to_warning=3600000
std.time_to_timedout=60000
# Housekeeping thread active every 1 secs
std.housekeepinginterval=1000
std.inputmode=character
# Login shell
std.loginshell=simple
# Connection filter class
std.connectionfilter=none

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

View File

@@ -0,0 +1,66 @@
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.baeldung.spring.controller"/>
<!-- Start: Mapping by bean name (BeanNameUrlHandlerMapping) -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
<property name="order" value="1"/>
</bean>
<bean name="/hello*.htm" class="com.baeldung.spring.controller.HelloWorldController"/>
<!-- End: Mapping by bean name (BeanNameUrlHandlerMapping) -->
<!-- Start: Mapping by SimpleUrlHandlerMapping -->
<!-- Method 1 Using Value -->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings"> <value> /welcome.htm=welcomeController /welcome*=welcomeController
</value> </property> <property name="order" value="2" /> </bean> -->
<!-- Method 2 Using prop key -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
<prop key="/welcome*">welcomeController</prop>
<prop key="/hello*">helloController</prop>
</props>
</property>
<property name="order" value="2"/>
</bean>
<bean id="welcomeController" class="com.baeldung.spring.controller.WelcomeController"></bean>
<bean id="helloController" class="com.baeldung.spring.controller.HelloController"/>
<!-- End: Mapping by SimpleUrlHandlerMapping -->
<bean class="com.baeldung.spring.controller.HelloGuestController"/>
<!-- End: Mapping by ControllerClassNameHandlerMapping -->
<!-- Start: Mapping by ControllerClassNameHandlerMapping with prefix -->
<!-- <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="caseSensitive" value="true" /> <property name="order" value="0"
/> <property name="pathPrefix" value="/login" /> </bean> <bean class="com.baeldung.spring.controller.HelloGuestController"
/> -->
<!-- End: Mapping by ControllerClassNameHandlerMapping with prefix -->
<bean class="org.crsh.spring.SpringWebBootstrap">
<property name="cmdMountPointConfig"
value="war:/WEB-INF/crash/commands/" />
<property name="confMountPointConfig"
value="war:/WEB-INF/crash/" />
<property name="config">
<props>
<prop key="crash.telnet.port">5000</prop>
</props>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,20 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>SpringMVCExample</title>
</head>
<body>
<h3>Pleas enter the correct details</h3>
<table>
<tr>
<td><a href="employee">Retry</a></td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>${errorMsg}</h1>
</body>
</html>

View File

@@ -0,0 +1,9 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

View File

@@ -0,0 +1,15 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Hello World</title>
</head>
<body>
<h2>Hello ${msg}</h2>
<br>
<p>
<a href="spring-handler-index.jsp">Go to spring handler mappings homepage</a>
</body>
</html>

View File

@@ -0,0 +1,15 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Hello World</title>
</head>
<body>
<h2>Hello World ${msg}</h2>
<br>
<p>
<a href="spring-handler-index.jsp">Go to spring handler mappings homepage</a>
</body>
</html>

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Image download examples</title>
</head>
<body>
<h1>Image download examples</h1>
<ul>
<li><a href="<c:url value="/image-manual-response" />">Image manually add to response</a></li>
<li><a href="<c:url value="/image-byte-array.jpg" />">Image Download <i>byte[]</i> Example</a></li>
<li><a href="<c:url value="/image-response-entity.jpg" />">Image Download <i>ResponseEntity</i> Example</a></li>
<li><a href="<c:url value="/image-resource.jpg" />">Image Download <i>Resource</i> Example</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,120 @@
<%@ 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>Form Example - Register a Person</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorbox {
background-color: #ffEEEE;
border: 2px solid #ff0000;
}
</style>
<body>
<h3>Welcome, Enter the Person Details</h3>
<form:form method="POST" action="/spring-mvc-xml/addPerson" modelAttribute="person">
<form:errors path="*" cssClass="errorbox" element="div" />
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error" element="div"/></td>
</tr>
<tr>
<td><form:label path="email">E-mail</form:label></td>
<td><form:input type="email" path="email" /></td>
<td><form:errors path="email" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="dateOfBirth">Date of birth</form:label></td>
<td><form:input type="date" path="dateOfBirth" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" /></td>
<td><form:errors path="password" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="sex">Sex</form:label></td>
<td>
Male: <form:radiobutton path="sex" value="M"/> <br/>
Female: <form:radiobutton path="sex" value="F"/>
</td>
</tr>
<tr>
<td><form:label path="job">Job</form:label></td>
<td>
<form:radiobuttons items="${jobItem}" path="job" />
</td>
</tr>
<tr>
<td><form:label path="country">Country</form:label></td>
<td>
<form:select path="country" items="${countryItems}" />
</td>
</tr>
<tr>
<td><form:label path="book">Book</form:label></td>
<td>
<form:select path="book">
<form:option value="-" label="--Please Select"/>
<form:options items="${books}" />
</form:select>
</td>
</tr>
<tr>
<td><form:label path="fruit">Fruit</form:label></td>
<td>
<form:select path="fruit" items="${fruit}" multiple="true"/>
</td>
</tr>
<tr>
<td><form:label path="receiveNewsletter">Receive newsletter</form:label></td>
<td><form:checkbox path="receiveNewsletter" rows="3" cols="20"/></td>
</tr>
<tr>
<td><form:label path="hobbies">Hobbies</form:label></td>
<td>
Bird watching: <form:checkbox path="hobbies" value="Bird watching"/>
Astronomy: <form:checkbox path="hobbies" value="Astronomy"/>
Snowboarding: <form:checkbox path="hobbies" value="Snowboarding"/>
</td>
</tr>
<tr>
<td><form:label path="favouriteLanguage">Favourite languages</form:label></td>
<td>
<form:checkboxes items="${favouriteLanguageItem}" path="favouriteLanguage" />
</td>
</tr>
<tr>
<td><form:label path="notes">Notes</form:label></td>
<td><form:textarea path="notes" rows="3" cols="20"/></td>
</tr>
<tr>
<td><form:hidden path="id" value="12345"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,65 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Person Information</h2>
<table>
<tr>
<td>Id :</td>
<td>${person.id}</td>
</tr>
<tr>
<td>Name :</td>
<td>${person.name}</td>
</tr>
<tr>
<td>Date of birth :</td>
<td>${person.dateOfBirth}</td>
</tr>
<tr>
<td>Password :</td>
<td>${person.password}</td>
</tr>
<tr>
<td>Sex :</td>
<td>${person.sex}</td>
</tr>
<tr>
<td>Job :</td>
<td>${person.job}</td>
</tr>
<tr>
<td>Country :</td>
<td>${person.country}</td>
</tr>
<tr>
<td>Fruit :</td>
<td><c:forEach items="${person.fruit}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Book :</td>
<td>${person.book}</td>
</tr>
<tr>
<td>Receive Newsletter :</td>
<td>${person.receiveNewsletter}</td>
</tr>
<tr>
<td>Hobbies :</td>
<td><c:forEach items="${person.hobbies}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Favourite Languages :</td>
<td><c:forEach items="${person.favouriteLanguage}" var="current">[<c:out value="${current}" />]</c:forEach></td>
</tr>
<tr>
<td>Notes :</td>
<td>${person.notes}</td>
</tr>
</table>
</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,15 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Welcome Page</title>
</head>
<body>
<h2>Welcome to ${msg}</h2>
<br>
<p>
<a href="spring-handler-index.jsp">Go to spring handler mappings homepage</a>
</body>
</html>

View File

@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
>
<display-name>Spring MVC XML 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</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.crsh.plugin.WebPluginLifeCycle</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>
<!-- JSP Servlet -->
<servlet>
<servlet-name>ExampleOne</servlet-name>
<servlet-class>com.baeldung.jsp.ExampleOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExampleOne</servlet-name>
<url-pattern>/jsp/ExampleOne</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ExampleThree</servlet-name>
<servlet-class>com.baeldung.jsp.ExampleThree</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExampleThree</servlet-name>
<url-pattern>/jsp/ExampleThree</url-pattern>
</servlet-mapping>
<!-- additional config -->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<location>/errors</location>
</error-page>
</web-app>

View File

@@ -0,0 +1,20 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Spring MVC Examples</title>
</head>
<body>
<h1>Spring MVC Examples</h1>
<ul>
<li><a href="employee">Welcome Page</a></li>
<li><a href="spring-handler-index.jsp">Spring Handler Mapping Examples</a></li>
<li><a href="image-view">Image Download Examples</a></li>
</ul>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<head>
<title>Java Binding Example</title>
</head>
<body>
<h1>Bound Value</h1>
<p>You said: ${text}</p>
</body>
</html>

View File

@@ -0,0 +1,13 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<head>
<title>Java in Static Page Example</title>
</head>
<body>
<h1>Java in Static Page Example</h1>
<% String[] arr = {"What's up?", "Hello", "It's a nice day today!"};
String greetings = arr[(int)(Math.random() * arr.length)];
%>
<p><%= greetings %></p>
</body>
</html>

View File

@@ -0,0 +1,12 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>JSP Examples</title>
</head>
<body>
<h1>Simple JSP Examples</h1>
<p>Invoke HTML rendered by Servlet: <a href="ExampleOne" target="_blank">here</a></p>
<p>Java in static page: <a href="ExampleTwo.jsp" target="_blank">here</a></p>
<p>Java injected by Servlet: <a href="ExampleThree?message=hello!" target="_blank">here</a></p>
</body>
</html>

View File

@@ -0,0 +1,18 @@
<!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>Welcome</title>
</head>
<body>
<h2>Spring Handler Mapping Examples</h2>
<h3>Click each link below to see how the request is mapped using the specified mapping:
</h3>
<ol>
<li><a href="helloWorld.html">BeanNameUrlHandlerMapping - Mapping by bean name</a></li>
<li><a href="welcome.html">SimpleUrlHandlerMapping</a></li>
<li><a href="helloGuest.html">ControllerClassNameHandlerMapping - Mapping by controller name</a></li>
</ol>
<a href="index.jsp">Home</a>
</body>
</html>

View File

@@ -0,0 +1,32 @@
package com.baeldung.geoip;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import org.junit.Test;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
public class GeoIpIntegrationTest {
@Test
public void givenIP_whenFetchingCity_thenReturnsCityData() throws IOException, GeoIp2Exception {
ClassLoader classLoader = getClass().getClassLoader();
File database = new File(classLoader.getResource("GeoLite2-City.mmdb").getFile());
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("google.com");
CityResponse response = dbReader.city(ipAddress);
String countryName = response.getCountry().getName();
String cityName = response.getCity().getName();
String postal = response.getPostal().getCode();
String state = response.getLeastSpecificSubdivision().getName();
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.spring.controller;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.ClientWebConfig;
import com.baeldung.spring.ClientWebConfigJava;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfigJava.class)
@WebAppConfiguration
public class RequestAndPathVariableValidationControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(5)))
.andExpect(status().isOk());
}
@Test
public void getNameOfDayByNumberRequestParam_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day").param("dayOfWeek", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(5))).andExpect(status().isOk());
}
@Test
public void getNameOfDayByPathVariable_whenGetWithRequestParamOutOfRange_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/name-for-day/{dayOfWeek}", Integer.toString(15)))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithProperRequestParam_thenReturn200() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "John")).andExpect(status().isOk());
}
@Test
public void validStringRequestParam_whenGetWithTooLongRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "asdfghjklqw"))
.andExpect(status().isBadRequest());
}
@Test
public void validStringRequestParam_whenGetWithLowerCaseRequestParam_thenReturn400() throws Exception {
mockMvc.perform(get("/public/api/1/valid-name").param("name", "john")).andExpect(status().isBadRequest());
}
}

View File

@@ -0,0 +1,19 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.baeldung.spring.ClientWebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfig.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 MiB