JAVA-3522: Moved spring-mvc-forms-jsp to spring-web-modules

This commit is contained in:
sampadawagde
2020-12-27 12:17:36 +05:30
parent 0218b505d3
commit 1d061bc47b
35 changed files with 1 additions and 1 deletions

View File

@@ -0,0 +1,17 @@
package com.baeldung.jstl.bundles;
import java.util.ListResourceBundle;
public class CustomMessage_en extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"verb.go", "go"},
{"verb.come", "come"},
{"verb.sit", "sit"},
{"verb.stand", "stand"}
};
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.jstl.bundles;
import java.util.ListResourceBundle;
public class CustomMessage_fr_FR extends ListResourceBundle {
@Override
protected Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"verb.go", "aller"},
{"verb.come", "venir"},
{"verb.sit", "siéger"},
{"verb.stand", "se lever"}
};
}

View File

@@ -0,0 +1,126 @@
package com.baeldung.jstl.controllers;
import com.baeldung.jstl.dbaccess.SQLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.sql.*;
import java.util.Calendar;
@Controller
public class JSTLController {
private static final Logger LOGGER = LoggerFactory.getLogger(JSTLController.class.getName());
@Autowired
ServletContext servletContext;
@PostConstruct
public void init() {
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = SQLConnection.getConnection();
preparedStatement = connection.prepareStatement("create table IF NOT EXISTS USERS " +
"( id int not null primary key AUTO_INCREMENT," +
" email VARCHAR(255) not null, first_name varchar (255), last_name varchar (255), registered DATE)");
int status = preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement("SELECT COUNT(*) AS total FROM USERS;");
ResultSet result = preparedStatement.executeQuery();
if(result!=null) {
result.next();
if (result.getInt("total") == 0) {
generateDummy(connection);
}
} else {
generateDummy(connection);
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
}
}
}
@RequestMapping(value = "/core_tags", method = RequestMethod.GET)
public ModelAndView coreTags(final Model model) {
ModelAndView mv = new ModelAndView("core_tags");
return mv;
}
@RequestMapping(value = "/core_tags_redirect", method = RequestMethod.GET)
public ModelAndView coreTagsRedirect(final Model model) {
ModelAndView mv = new ModelAndView("core_tags_redirect");
return mv;
}
@RequestMapping(value = "/formatting_tags", method = RequestMethod.GET)
public ModelAndView formattingTags(final Model model) {
ModelAndView mv = new ModelAndView("formatting_tags");
return mv;
}
@RequestMapping(value = "/sql_tags", method = RequestMethod.GET)
public ModelAndView sqlTags(final Model model) {
ModelAndView mv = new ModelAndView("sql_tags");
return mv;
}
@RequestMapping(value = "/xml_tags", method = RequestMethod.GET)
public ModelAndView xmlTags(final Model model) {
System.out.println("dddddddddddddddddffffffffffffff");
ModelAndView mv = new ModelAndView("xml_tags");
return mv;
}
@RequestMapping(value = "/items_xml", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getFile(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/xml");
return new FileSystemResource(new File(servletContext.getRealPath("/WEB-INF/items.xsl")));
}
@RequestMapping(value = "/function_tags", method = RequestMethod.GET)
public ModelAndView functionTags(final Model model) {
ModelAndView mv = new ModelAndView("function_tags");
return mv;
}
private void generateDummy(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO USERS " +
"(email, first_name, last_name, registered) VALUES (?, ?, ?, ?);");
preparedStatement.setString(1, "patrick@baeldung.com");
preparedStatement.setString(2, "Patrick");
preparedStatement.setString(3, "Frank");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.addBatch();
preparedStatement.setString(1, "bfrank@baeldung.com");
preparedStatement.setString(2, "Benjamin");
preparedStatement.setString(3, "Franklin");
preparedStatement.setDate(4, new Date(Calendar.getInstance().getTimeInMillis()));
preparedStatement.executeBatch();
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.jstl.dbaccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class SQLConnection {
private static String userName = "root";
private static String password = "";
private static final Logger LOGGER = LoggerFactory.getLogger(SQLConnection.class.getName());
public static Connection getConnection() throws Exception {
LOGGER.error("connecting...");
Class.forName("com.mysql.cj.jdbc.Driver");
LOGGER.error("class checked...");
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false",
connectionProps);
LOGGER.info("Connected to database");
return conn;
}
}

View File

@@ -0,0 +1,57 @@
package com.baeldung.springmvcforms.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"})
public class ApplicationConfiguration implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public ResourceBundleMessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
// switch orders to server views from html over views directory
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(1);
return bean;
}
@Bean
public InternalResourceViewResolver htmlViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/html/");
bean.setSuffix(".html");
bean.setOrder(2);
return bean;
}
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(5242880);
return multipartResolver;
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.springmvcforms.configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ApplicationConfiguration.class);
ctx.setServletContext(container);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(ctx));
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
// @Override
// public void onStartup(ServletContext container) {
// // Create the 'root' Spring application context
// AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);
//
// // Manage the lifecycle of the root application context
// container.addListener(new ContextLoaderListener(rootContext));
//
// // Create the dispatcher servlet's Spring application context
// AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
// dispatcherServlet.register(MvcConfig.class);
//
// // Register and map the dispatcher servlet
// ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
// dispatcher.setLoadOnStartup(1);
// dispatcher.addMapping("/");
//
// }
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.springmvcforms.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.springmvcforms.domain.Customer;
import com.baeldung.springmvcforms.validator.CustomerValidator;
@Controller
public class CustomerController {
@Autowired
CustomerValidator validator;
@RequestMapping(value = "/customer", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("customerHome", "customer", new Customer());
}
@PostMapping("/addCustomer")
public String submit(@Valid @ModelAttribute("customer") final Customer customer, final BindingResult result, final ModelMap model) {
validator.validate(customer, result);
if (result.hasErrors()) {
return "customerHome";
}
model.addAttribute("customerId", customer.getCustomerId());
model.addAttribute("customerName", customer.getCustomerName());
model.addAttribute("customerContact", customer.getCustomerContact());
model.addAttribute("customerEmail", customer.getCustomerEmail());
return "customerView";
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.springmvcforms.controller;
import com.baeldung.springmvcforms.domain.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
@Controller
public class EmployeeController {
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.springmvcforms.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController implements HandlerExceptionResolver {
@RequestMapping(value = "/uploadFile", method = RequestMethod.GET)
public String getImageView() {
return "file";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(MultipartFile file) throws IOException{
ModelAndView modelAndView = new ModelAndView("file");
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
FileOutputStream f = new FileOutputStream(path.substring(0, path.length()-1)+ file.getOriginalFilename());
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
modelAndView.getModel().put("message", "File uploaded successfully!");
return modelAndView;
}
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) {
ModelAndView modelAndView = new ModelAndView("file");
if (exc instanceof MaxUploadSizeExceededException) {
modelAndView.getModel().put("message", "File size exceeds limit!");
}
return modelAndView;
}
}

View File

@@ -0,0 +1,59 @@
package com.baeldung.springmvcforms.controller;
import com.baeldung.springmvcforms.domain.User;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class UserController {
private List<User> users = Arrays.asList(
new User("ana@yahoo.com", "pass", "Ana", 20),
new User("bob@yahoo.com", "pass", "Bob", 30),
new User("john@yahoo.com", "pass", "John", 40),
new User("mary@yahoo.com", "pass", "Mary", 30));
@GetMapping("/userPage")
public String getUserProfilePage() {
return "user";
}
@PostMapping("/user")
@ResponseBody
public ResponseEntity<Object> saveUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
final List<String> errors = result.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return new ResponseEntity<>(errors, HttpStatus.OK);
} else {
if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) {
return new ResponseEntity<>(Collections.singletonList("Email already exists!"), HttpStatus.CONFLICT);
} else {
users.add(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
}
@GetMapping("/users")
@ResponseBody
public List<User> getUsers() {
return users;
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.springmvcforms.domain;
public class Customer {
private String customerId;
private String customerName;
private String customerContact;
private String customerEmail;
public Customer() {
super();
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerContact() {
return customerContact;
}
public void setCustomerContact(String customerContact) {
this.customerContact = customerContact;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.springmvcforms.domain;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Employee {
private long id;
@NotNull
@Size(min = 5)
private String name;
@NotNull
@Size(min = 7)
private String contactNumber;
public Employee() {
super();
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(final String contactNumber) {
this.contactNumber = contactNumber;
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.springmvcforms.domain;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotNull
@Email
private String email;
@NotNull
@Size(min = 4, max = 15)
private String password;
@NotBlank
private String name;
@Min(18)
@Digits(integer = 2, fraction = 0)
private int age;
public User() {
}
public User(String email, String password, String name, int age) {
super();
this.email = email;
this.password = password;
this.name = name;
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.springmvcforms.interceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class FileUploadExceptionAdvice {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){
ModelAndView modelAndView = new ModelAndView("file");
modelAndView.getModel().put("message", "File too large!");
return modelAndView;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.springmvcforms.validator;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.baeldung.springmvcforms.domain.Customer;
@Component
public class CustomerValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Customer.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerId", "error.customerId", "Customer Id is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerName", "error.customerName", "Customer Name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerContact", "error.customerNumber", "Customer Contact is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "customerEmail", "error.customerEmail", "Customer Email is required.");
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Users</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/user.css">
</head>
<body ng-app="app" ng-controller="UserCtrl">
<form name="userForm" method="POST" novalidate ng-class="{'form-error':submitted}" ng-submit="saveUser()" >
<label class="form-label">Email:</label>
<input type="email" name="email" required ng-model="user.email" class="form-input"/>
<div ng-messages="userForm.email.$error" ng-show="submitted && userForm.email.$invalid" class="error-messages">
<p ng-message="email">Invalid email!</p>
<p ng-message="required">Email is required!</p>
</div>
<div class="check" ng-show="submitted && userForm.email.$valid">&#x2713;</div>
<label class="form-label">Password:</label>
<input type="password" name="password" required ng-model="user.password" ng-minlength="4" ng-maxlength="15" class="form-input"/>
<div ng-messages="userForm.password.$error" ng-show="submitted && userForm.password.$invalid" class="error-messages">
<p ng-message="minlength">Password must be at least 4 characters!</p>
<p ng-message="maxlength">Password must not be longer than 15 characters!</p>
<p ng-message="required">Password is required!</p>
</div>
<div class="check" ng-show="submitted && userForm.password.$valid">&#x2713;</div>
<label class="form-label">Name:</label>
<input type="text" name="name" ng-model="user.name" ng-trim="true" required class="form-input" />
<div ng-messages="userForm.name.$error" ng-show="submitted && userForm.name.$invalid" class="error-messages">
<p ng-message="required">Name is required!</p>
</div>
<div class="check" ng-show="submitted && userForm.name.$valid">&#x2713;</div>
<label class="form-label">Age:</label>
<input type="number" name="age" ng-model="user.age" ng-min="18" class="form-input" required/>
<div ng-messages="userForm.age.$error" ng-show="submitted && userForm.age.$invalid" class="error-messages">
<p ng-message="min">Age must be greater than 18!</p>
<p ng-message="required">Age must be greater than 18!</p>
</div>
<div class="check" ng-show="submitted && userForm.age.$valid">&#x2713;</div>
<br />
<button type="submit" class="form-button-save" >Save</button>
<button type="reset" ng-click="resetForm()" class="form-button-reset">Reset</button>
</form>
<br />
<div style="color:red;font-weight:bold">{{errorMessage}}</div>
<div style="color:green;font-weight:bold">{{message}}</div>
<br />
All Users: <br />
<table id="users">
<tr>
<th>Email</th><th>Name</th><th>Age</th>
</tr>
<tr ng-repeat="usr in users">
<td>{{usr.email}}</td> <td>{{usr.name}}</td> <td>{{usr.age}}</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,27 @@
<?xml version = "1.0"?>
<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform" version = "1.0">
<xsl:output method = "html" indent = "yes"/>
<xsl:param name = "bgColor"/>
<xsl:template match = "/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match = "items">
<table border = "1" width = "40%" bgColor = "{$bgColor}">
<xsl:for-each select = "item">
<tr>
<td><i><xsl:value-of select = "name"/></i></td>
<td><xsl:value-of select = "category"/></td>
<td><xsl:value-of select = "price"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

View File

@@ -0,0 +1,92 @@
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<c:set value="JSTL Core Tags Example" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<h1>
<c:out value="${pageTitle}"/>
</h1>
<c:remove var="pageTitle"/>
<p><c:out value="${pageTitle}"/></p>
<div>
<h3>
<c:out value="<c:catch> Example"/>
</h3>
<c:catch var ="exceptionThrown">
<% int x = Integer.valueOf("a");%>
</c:catch>
<c:if test = "${exceptionThrown != null}">
<p>The exception is : ${exceptionThrown} <br />
There is an exception: ${exceptionThrown.message}</p>
</c:if>
</div>
<div>
<h3>
<c:out value="<c:choose> Example"/>
<c:set value="<%= Calendar.getInstance().get(Calendar.SECOND)%>" var="seconds"/>
</h3>
<p>
<c:choose>
<c:when test="${seconds le 30 }">
<c:out value="${seconds} is less than 30"/>
</c:when>
<c:when test="${seconds eq 30 }">
<c:out value="${seconds} is equal to 30"/>
</c:when>
<c:otherwise>
<c:out value="${seconds} is greater than 30"/>
</c:otherwise>
</c:choose>
</p>
</div>
<div>
<h3>
<c:out value="<c:import> Example"/>
</h3>
<c:import var = "data" url = "http://www.example.com"/>
<c:out value = "${data}"/>
</div>
<div>
<h3>
<c:out value="<c:forEach> Example"/>
</h3>
<c:forEach var = "i" items="1,4,5,6,7,8,9">
Item <c:out value = "No. ${i}"/><p>
</c:forEach>
</div>
<div>
<h3>
<c:out value="<c:forToken> Example"/>
</h3>
<c:forTokens items = "Patrick:Wilson:Ibrahima:Chris" delims = ":" var = "name">
<c:out value = "Name: ${name}"/><p>
</c:forTokens>
</div>
<div>
<h3>
<c:out value="<c:url> and <c:param> Example"/>
</h3>
<c:url value = "/core_tags" var = "myURL">
<c:param name = "parameter_1" value = "1234"/>
<c:param name = "parameter_2" value = "abcd"/>
</c:url>
<c:out value = "URL: ${myURL}"/>
</div>
</body>
</html>

View File

@@ -0,0 +1,16 @@
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<c:set value="JSTL Core Tags Examples" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<c:redirect url="/core_tags"/>
</body>
</html>

View File

@@ -0,0 +1,47 @@
<%@ 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 - Add Customer</title>
<style>
.error {
color: #ff0000;
font-weight: bold;
}
</style>
</head>
<body>
<h3>Welcome, Enter The Customer Details</h3>
<form:form method="POST" action="${pageContext.request.contextPath}/addCustomer" modelAttribute="customer">
<table>
<tr>
<td><form:label path="customerId">Customer Id</form:label></td>
<td><form:input path="customerId" /></td>
<td><form:errors path="customerId" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="customerName">Customer Name</form:label></td>
<td><form:input path="customerName" /></td>
<td><form:errors path="customerName" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="customerContact">Customer Contact</form:label></td>
<td><form:input path="customerContact"/></td>
<td><form:errors path="customerContact" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="customerEmail">Customer Email</form:label></td>
<td><form:input path="customerEmail" /></td>
<td><form:errors path="customerEmail" cssClass="error" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,28 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Customer Information</h2>
<table>
<tr>
<td>Customer Id :</td>
<td>${customerId}</td>
</tr>
<tr>
<td>Customer Name :</td>
<td>${customerName}</td>
</tr>
<tr>
<td>Customer Contact :</td>
<td>${customerContact}</td>
</tr>
<tr>
<td>Customer Email :</td>
<td>${customerEmail}</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,33 @@
<%@ 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 an Employee</title>
</head>
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST" action="${pageContext.request.contextPath}/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="contactNumber">Contact Number</form:label></td>
<td><form:input path="contactNumber" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@@ -0,0 +1,24 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>ID :</td>
<td>${id}</td>
</tr>
<tr>
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
</table>
</body>
</html>

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,23 @@
<%@ 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>Upload file</title>
</head>
<body>
<c:url value="/uploadFile" var="uploadFileUrl" />
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}">
<input type="file" name="file"/>
<input type="submit" value="Upload file"/>
</form>
<br />
${message }
<br /> <br />
<form method="GET" action="${uploadFileUrl}" >
<input type="submit" value="Reset" />
</form>
</body>
</html>

View File

@@ -0,0 +1,213 @@
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<c:set value="JSTL Formatting Tags Example" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<h1>
<c:out value="${pageTitle}"/>
</h1>
<div>
<h3>
<c:out value="<fmt:formatNumber> Example"/>
</h3>
<c:set var="fee" value="35050.1067"/>
<p>Formatted Number - Currency: <fmt:formatNumber value="${fee}"
type="currency"/></p>
<p>Formatted Number - Maximum Integer Digits: <fmt:formatNumber type="number"
maxIntegerDigits="2" value="${fee}"/></p>
<p>Formatted Number - Maximum Fraction Digits: <fmt:formatNumber type="number"
maxFractionDigits="2" value="${fee}"/></p>
<p>Formatted Number - Grouping: <fmt:formatNumber type="number"
groupingUsed="false" value="${fee}"/></p>
<p>Formatted Number - Percent with Maximum Integer Digits: <fmt:formatNumber type="percent"
maxIntegerDigits="3"
value="${fee}"/></p>
<p>Formatted Number - Percent with Minimum Fraction Digits: <fmt:formatNumber type="percent"
minFractionDigits="10"
value="${fee}"/></p>
<p>Formatted Number Percent with Minimum Integer Digits: <fmt:formatNumber type="percent"
minIntegerDigits="4" value="${fee}"/></p>
<p>Formatted Number - with Pattern: <fmt:formatNumber type="number"
pattern="###.##E0" value="${fee}"/></p>
<p>Formatted Number - Currency with Internationalization :
<fmt:setLocale value="en_US"/>
<fmt:formatNumber value="${fee}" type="currency"/>
</p>
</div>
<div>
<h3>
<c:out value="<fmt:parseNumber> Example"/>
</h3>
<fmt:parseNumber var="i" type="number" value="${fee}"/>
<p>Parsed Number : <c:out value="${i}"/></p>
<fmt:parseNumber var="i" integerOnly="true"
type="number" value="${fee}"/>
<p>Parsed Number - with Integer Only set to True: <c:out value="${i}"/></p>
</div>
<div>
<h3>
<c:out value="<fmt:formatDate> Example"/>
<c:set var="now" value="<%= new java.util.Date()%>"/>
</h3>
<p>Formatted Date - with type set to time: <fmt:formatDate type="time"
value="${now}"/></p>
<p>Formatted Date - with type set to date: <fmt:formatDate type="date"
value="${now}"/></p>
<p>Formatted Date - with type set to both: <fmt:formatDate type="both"
value="${now}"/></p>
<p>Formatted Date - with short style for both date and time: <fmt:formatDate type="both"
dateStyle="short" timeStyle="short"
value="${now}"/></p>
<p>Formatted Date - with medium style for both date and time: <fmt:formatDate type="both"
dateStyle="medium" timeStyle="medium"
value="${now}"/></p>
<p>Formatted Date - with long style for both date and time: <fmt:formatDate type="both"
dateStyle="long" timeStyle="long"
value="${now}"/></p>
<p>Formatted Date - with pattern: <fmt:formatDate pattern="yyyy-MM-dd"
value="${now}"/></p>
</div>
<div>
<h3>
<c:out value="<fmt:parseDate> Example"/>
</h3>
<c:set var="today" value="28-03-2018"/>
<fmt:parseDate value="${today}" var="parsedDate" pattern="dd-MM-yyyy"/>
<p>Parsed Date: <c:out value="${parsedDate}"/></p>
</div>
<div>
<h3>
<c:out value="<fmt:bundle> and <fmt:message> Example"/>
</h3>
<p>
<fmt:bundle basename="com.baeldung.jstl.bundles.CustomMessage" prefix="verb.">
<fmt:message key="go"/><br/>
<fmt:message key="come"/><br/>
<fmt:message key="sit"/><br/>
<fmt:message key="stand"/><br/>
</fmt:bundle>
</p>
</div>
<div>
<h3>
<c:out value="<fmt:setLocale> Example"/>
</h3>
<p>
<fmt:setLocale value="fr_FR"/>
<fmt:bundle basename="com.baeldung.jstl.bundles.CustomMessage" prefix="verb.">
<fmt:message key="go"/><br/>
<fmt:message key="come"/><br/>
<fmt:message key="sit"/><br/>
<fmt:message key="stand"/><br/>
</fmt:bundle>
</p>
</div>
<div>
<h3>
<c:out value="<fmt:setBundle> Example"/>
</h3>
<p>
<fmt:setLocale value="En"/>
<fmt:setBundle basename="com.baeldung.jstl.bundles.CustomMessage" var="lang"/>
<fmt:message key="verb.go" bundle="${lang}"/><br/>
<fmt:message key="verb.come" bundle="${lang}"/><br/>
<fmt:message key="verb.sit" bundle="${lang}"/><br/>
<fmt:message key="verb.stand" bundle="${lang}"/><br/>
</p>
</div>
<div>
<h3>
<c:out value="<fmt:timeZone> Example"/>
</h3>
<table border="1" width="40%">
<tr>
<td width="100%" colspan="2">
<p align="center">
<b>
<font size="4">Time being formatted:
<fmt:formatDate value="${now}" type="both"
timeStyle="long" dateStyle="long"/>
</font>
</b>
</p>
</td>
</tr>
<c:forEach var="zone"
items="<%= java.util.TimeZone.getAvailableIDs()%>" end="4">
<tr>
<td width="51%">
<c:out value="${zone}"/>
</td>
<td width="49%">
<fmt:timeZone value="${zone}">
<fmt:formatDate value="${now}" timeZone="${zn}"
type="both"/>
</fmt:timeZone>
</td>
</tr>
</c:forEach>
</table>
</div>
<div>
<h3>
<c:out value="<fmt:setTimeZone> Example"/>
</h3>
<p>Current Date with Default Time Zone: <fmt:formatDate value="${now}"
type="both" timeStyle="long" dateStyle="long"/></p>
<p>Change Time Zone to GMT+9</p>
<fmt:setTimeZone value="GMT+9"/>
<p>Date in Changed Zone: <fmt:formatDate value="${now}"
type="both" timeStyle="long" dateStyle="long"/></p>
</div>
<div>
<h3>
<c:out value="<fmt:requestEncoding> Example"/>
</h3>
<fmt:requestEncoding value = "UTF-8" />
<fmt:setLocale value = "fr_FR"/>
<fmt:setBundle basename = "com.baeldung.jstl.bundles.CustomMessage" var = "lang"/>
<fmt:message key="verb.go" bundle="${lang}"/><br/>
<fmt:message key="verb.come" bundle="${lang}"/><br/>
<fmt:message key="verb.sit" bundle="${lang}"/><br/>
<fmt:message key="verb.stand" bundle="${lang}"/><br/>
</div>
</body>
</html>

View File

@@ -0,0 +1,151 @@
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "fn"
uri = "http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<c:set value="JSTL Function Tags Example" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<h1>
<c:out value="${pageTitle}"/>
</h1>
<c:set var = "string1" value = "This is first string"/>
<c:set var = "string2" value = "This is second string with <tag>test XML</tag>"/>
<div>
<h3>
<c:out value="fn:contains() Example"/>
</h3>
<c:if test = "${fn:contains(string1, 'first')}">
<p>Found 'first' in string<p>
</c:if>
</div>
<div>
<h3>
<c:out value="fn:containsIgnoreCase() Example"/>
</h3>
<c:if test = "${fn:containsIgnoreCase(string1, 'first')}">
<p>Found 'first' string<p>
</c:if>
<c:if test = "${fn:containsIgnoreCase(string1, 'FIRST')}">
<p>Found 'FIRST' string<p>
</c:if>
</div>
<div>
<h3>
<c:out value="fn:endsWith() Example"/>
</h3>
<c:if test = "${fn:endsWith(string1, 'string')}">
<p>String ends with 'string'<p>
</c:if>
</div>
<div>
<h3>
<c:out value="fn:escapeXml() Example"/>
</h3>
<p>With escapeXml() Function:</p>
<p>string (1) : ${fn:escapeXml(string1)}</p>
<p>string (2) : ${fn:escapeXml(string2)}</p>
<p>Without escapeXml() Function:</p>
<p>string (1) : ${string1}</p>
<p>string (2) : ${string2}</p>
</div>
<div>
<h3>
<c:out value="fn:indexOf() Example"/>
</h3>
<p>Index (1) : ${fn:indexOf(string1, "first")}</p>
<p>Index (2) : ${fn:indexOf(string2, "second")}</p>
</div>
<div>
<h3>
<c:out value="fn:join() and fn:split() Example"/>
</h3>
<c:set var = "string3" value = "${fn:split(string1, ' ')}" />
<c:set var = "string4" value = "${fn:join(string3, '-')}" />
<p>Final String : ${string4}</p>
</div>
<div>
<h3>
<c:out value="fn:length() Example"/>
</h3>
<p>Length of String (1) : ${fn:length(string1)}</p>
<p>Length of String (2) : ${fn:length(string2)}</p>
</div>
<div>
<h3>
<c:out value="fn:replace() Example"/>
</h3>
<c:set var = "string3" value = "${fn:replace(string1, 'first', 'third')}" />
<p>Final String : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:startsWith() Example"/>
</h3>
<c:if test = "${fn:startsWith(string1, 'This')}">
<p>String starts with 'This'</p>
</c:if>
</div>
<div>
<h3>
<c:out value="fn:substring() Example"/>
</h3>
<c:set var = "string3" value = "${fn:substring(string1, 5, 15)}" />
<p>Final sub string : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:substringAfter() Example"/>
</h3>
<c:set var = "string3" value = "${fn:substringAfter(string1, 'is')}" />
<p>Final sub string : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:substringBefore() Example"/>
</h3>
<c:set var = "string3" value = "${fn:substringBefore(string1, 'is')}" />
<p>Final sub string : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:toLowerCase() Example"/>
</h3>
<c:set var = "string3" value = "${fn:toLowerCase(string1)}" />
<p>Final string : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:toUpperCase() Example"/>
</h3>
<c:set var = "string3" value = "${fn:toUpperCase(string1)}" />
<p>Final string : ${string3}</p>
</div>
<div>
<h3>
<c:out value="fn:trim() Example"/>
</h3>
<c:set var = "string1" value = "This is first String "/>
<p>String (1) Length : ${fn:length(string1)}</p>
<c:set var = "string2" value = "${fn:trim(string1)}" />
<p>String (2) Length : ${fn:length(string2)}</p>
<p>Final string : "${string2}"</p>
</div>
</body>
</html>

View File

@@ -0,0 +1,198 @@
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<html>
<head>
<c:set value="JSTL SQL Tags Example" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<h1>
<c:out value="${pageTitle}"/>
</h1>
<!--
sql:setDataSource Example
-->
<sql:setDataSource var="dataSource" driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password=""/>
<div>
<h3>
<c:out value="<sql:query> Example"/>
</h3>
<sql:query dataSource="${dataSource}" var="result">
SELECT * from USERS;
</sql:query>
<table border="1" width="50%">
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Registered</th>
</tr>
<c:forEach var="user" items="${result.rows}" varStatus="iterator">
<tr>
<td><c:out value="${iterator.index + 1}"/></td>
<td><c:out value="${user.first_name}"/></td>
<td><c:out value="${user.last_name}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.registered}"/></td>
</tr>
</c:forEach>
</table>
</div>
<div>
<h3>
<c:out value="<sql:update> Example"/>
</h3>
<sql:update dataSource="${dataSource}" var="count">
INSERT INTO USERS(first_name, last_name, email) VALUES ('Grace', 'Adams', 'gracea@domain.com');
</sql:update>
<sql:query dataSource="${dataSource}" var="result">
SELECT * from USERS;
</sql:query>
<table border="1" width="50%">
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Registered</th>
</tr>
<c:forEach var="user" items="${result.rows}" varStatus="iterator">
<tr>
<td><c:out value="${iterator.index + 1}"/></td>
<td><c:out value="${user.first_name}"/></td>
<td><c:out value="${user.last_name}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.registered}"/></td>
</tr>
</c:forEach>
</table>
</div>
<div>
<h3>
<c:out value="<sql:param> Example"/>
</h3>
<sql:update dataSource = "${dataSource}" var = "count">
DELETE FROM USERS WHERE email = ?
<sql:param value = "gracea@domain.com" />
</sql:update>
<sql:query dataSource="${dataSource}" var="result">
SELECT * from USERS;
</sql:query>
<table border="1" width="50%">
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Registered</th>
</tr>
<c:forEach var="user" items="${result.rows}" varStatus="iterator">
<tr>
<td><c:out value="${iterator.index + 1}"/></td>
<td><c:out value="${user.first_name}"/></td>
<td><c:out value="${user.last_name}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.registered}"/></td>
</tr>
</c:forEach>
</table>
</div>
<div>
<h3>
<c:out value="<sql:dateParam> Example"/>
</h3>
<%
Date registered = new Date("2018/03/31");
String email = "patrick@baeldung.com";
%>
<sql:update dataSource = "${dataSource}" var = "count">
UPDATE Users SET registered = ? WHERE email = ?
<sql:dateParam value = "<%=registered%>" type = "DATE" />
<sql:param value = "<%=email%>" />
</sql:update>
<sql:query dataSource="${dataSource}" var="result">
SELECT * from USERS;
</sql:query>
<table border="1" width="50%">
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Registered</th>
</tr>
<c:forEach var="user" items="${result.rows}" varStatus="iterator">
<tr>
<td><c:out value="${iterator.index + 1}"/></td>
<td><c:out value="${user.first_name}"/></td>
<td><c:out value="${user.last_name}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.registered}"/></td>
</tr>
</c:forEach>
</table>
</div>
<div>
<h3>
<c:out value="<sql:transaction> Example"/>
</h3>
<sql:transaction dataSource = "${dataSource}">
<sql:update var = "count">
UPDATE Users SET first_name = 'Patrick-Ellis' WHERE email='patrick@baeldung.com'
</sql:update>
<sql:update var = "count">
UPDATE Users SET last_name = 'Nelson' WHERE email = 'patrick@baeldung.com'
</sql:update>
<sql:update var = "count">
INSERT INTO Users(first_name, last_name, email) VALUES ('Grace', 'Adams', 'gracea@domain.com');
</sql:update>
</sql:transaction>
<sql:query dataSource="${dataSource}" var="result">
SELECT * from USERS;
</sql:query>
<table border="1" width="50%">
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Registered</th>
</tr>
<c:forEach var="user" items="${result.rows}" varStatus="iterator">
<tr>
<td><c:out value="${iterator.index + 1}"/></td>
<td><c:out value="${user.first_name}"/></td>
<td><c:out value="${user.last_name}"/></td>
<td><c:out value="${user.email}"/></td>
<td><c:out value="${user.registered}"/></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>

View File

@@ -0,0 +1,99 @@
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.util.Calendar" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<c:set value="JSTL XML Tags Example" var="pageTitle"/>
<title>
<c:out value="${pageTitle}"/>
</title>
</head>
<body>
<h1>
<c:out value="${pageTitle}"/>
</h1>
<c:remove var="pageTitle"/>
<p><c:out value="${pageTitle}"/></p>
<div>
<h3>
<c:out value="<x:transform>, <x::param>, <x:parse>, <x:set>, <x:out>, and <x:if> Examples"/>
</h3>
<h3>Store Items:</h3>
<c:set var="xmltext">
<items>
<item>
<name>Steve Madden</name>
<category>Sneakers</category>
<price>34</price>
</item>
<item>
<name>Pearl Izumi</name>
<category>Sneakers</category>
<price>80</price>
</item>
<item>
<name>Katy Perry</name>
<category>Heels</category>
<price>72</price>
</item>
</items>
</c:set>
<x:parse xml="${xmltext}" var="output"/>
<b>The name of the first item listed in the store is</b>:
<x:out select="$output/items/item[1]/name"/> with price $<x:out select="$output/items/item[1]/price"/>
<br>
<x:set var="fragment" select="$output//item"/>
<b>The second item is </b>:
<c:out value="${fragment}"/>
<x:if select="$output//item">
Document has at least one
<item> element.
</x:if>
<br/>
<c:import url="/items_xml" var="xslt"/>
<x:transform xml="${xmltext}" xslt="${xslt}">
<x:param name="bgColor" value="blue"/>
</x:transform>
</div>
<div>
<h3>
<c:out value="<x:forEach> Example"/>
</h3>
<ul class="items">
<x:forEach select="$output/items/item/name" var="item">
<li>Item Name: <x:out select="$item"/></li>
</x:forEach>
</ul>
</div>
<div>
<h3>
<c:out value="<x:choose>, <x:when> and <x:otherwise> Example"/>
</h3>
<x:choose>
<x:when select="$output//item/category = 'Sneakers'">
Item category is Sneakers
</x:when>
<x:when select="$output//item/category = 'Heels'">
Item category is Heels
</x:when>
<x:otherwise>
Unknown category.
</x:otherwise>
</x:choose>
</div>
</body>
</html>

View File

@@ -0,0 +1,77 @@
.form-label {
display:block;
margin-top:16px;
font-weight:bold;
}
.form-input {
border-radius:5px;
display:inline;
}
.form-input p {
margin:0;
}
.form-button {
margin:5px;
}
.form-error input.ng-invalid {
border-color:red;
}
.check {
display:inline;
color:green;
font-weight:bold;
}
.error-messages {
color:red;
}
.error-messages p {
margin:0;
}
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#users td, #users th {
border: 1px solid dodgerblue;
border-collapse:collapse;
padding: 4px;
width:200px;
}
#users tr:nth-child(even){background-color: lavender;}
#users th {
padding-top: 10px;
padding-bottom: 10px;
text-align: left;
background-color: dodgerblue;
}
#users {
border-collapse:collapse;
}
button {
border-radius:5px;
cursor:pointer;
margin:10px;
padding:5px;
}
.form-button-save {
background-color:lightgreen;
}
.form-button-reset {
background-color:lightpink;
}

View File

@@ -0,0 +1,70 @@
var app = angular.module('app', ['ngMessages']);
app.controller('UserCtrl', ['$scope','UserService', function ($scope,UserService) {
$scope.submitted = false;
$scope.getUsers = function() {
UserService.getUsers().then( function(data){
$scope.users = data;
});
}
$scope.saveUser = function () {
$scope.submitted = true;
if ($scope.userForm.$valid){
UserService.saveUser($scope.user)
.then (function success(response){
$scope.message = 'User added!';
$scope.errorMessage = '';
$scope.getUsers();
$scope.user = null;
$scope.submitted = false;
},
function error(response){
if (response.status == 409){
$scope.errorMessage = response.data[0];
}
else {
$scope.errorMessage = 'Error adding user!';
}
$scope.message = '';
});
}
}
$scope.getUsers();
$scope.resetForm = function () {
$scope.userForm.$setPristine();
$scope.user=null;
$scope.message='';
$scope.errorMessage='';
$scope.submitted = false;
}
}]);
app.service('UserService',['$http', function ($http) {
this.saveUser = function saveUser(user){
return $http({
method: 'POST',
url: 'user',
params: {email:user.email, password:user.password, name:user.name, age:user.age},
headers: 'Accept:application/json'
});
}
this.getUsers = function getUsers(){
return $http({
method: 'GET',
url: 'users',
headers:'Accept:application/json'
}).then( function(response){
return response.data;
} );
}
}]);

View File

@@ -0,0 +1,19 @@
package com.baeldung;
import com.baeldung.springmvcforms.configuration.ApplicationConfiguration;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfiguration.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}