Size: 22761
Comment:
|
← Revision 40 as of 2024-01-19 20:56:39 ⇥
Size: 48229
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
## page was renamed from Spring <<TableOfContents(2)>> |
|
Line 10: | Line 14: |
== REST service == | == ApplicationContextAware == * https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationContextAware.html ApplicationContextAware, Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. {{{#!highlight java void setApplicationContext(ApplicationContext applicationContext) // applicationContext.getBean() // applicationContext.getEnvironment() }}} == ResourceLoaderAware == * https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ResourceLoaderAware.html ResourceLoaderAware, Interface to be implemented by any object that wishes to be notified of the ResourceLoader (typically the ApplicationContext) that it runs in. {{{#!highlight java void setResourceLoader(ResourceLoader resourceLoader) // resourceLoader.getClassLoader() // resourceLoader.getResource(String location) }}} == EnvironmentAware == * https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html EnvironmentAware, Interface to be implemented by any bean that wishes to be notified of the Environment that it runs in. {{{#!highlight java void setEnvironment(Environment environment) // environment.containsProperty() // environment.getProperty() // environment.getActiveProfiles() }}} == REST service (SpringBoot) == |
Line 24: | Line 61: |
`-- target |-- classes | `-- hello | |-- Application.class | |-- Greeting.class | `-- GreetingController.class |-- generated-sources | `-- annotations |-- gs-rest-service-0.1.0.jar |-- gs-rest-service-0.1.0.jar.original `-- maven-archiver `-- pom.properties |
|
Line 40: | Line 64: |
* mkdir -p /tmp/greetingSpring * mkdir -p /tmp/greetingSpring/src/main/java/hello * mkdir -p /tmp/greetingSpring/target * cd /tmp/greetingSpring |
{{{#!highlight sh mkdir -p /tmp/greetingSpring mkdir -p /tmp/greetingSpring/src/main/java/hello mkdir -p /tmp/greetingSpring/target cd /tmp/greetingSpring }}} |
Line 47: | Line 72: |
{{{#!highlihht xml | {{{#!highlight xml |
Line 149: | Line 174: |
import org.springframework.web.context.request.async.DeferredResult; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; |
|
Line 151: | Line 181: |
private ExecutorService es = Executors.newFixedThreadPool(50); public class MyCall implements Runnable { private DeferredResult df; private String template; private String name; private AtomicLong counter; public MyCall(DeferredResult df, String template, String name, AtomicLong counter){ this.df = df; this.template=template; this.name=name; this.counter = counter; } @Override public void run(){ Greeting g = new Greeting(this.counter.incrementAndGet(), String.format(this.template, this.name)); this.df.setResult(g); } } |
|
Line 157: | Line 209: |
return new Greeting(counter.incrementAndGet(), String.format(template, name)); |
return new Greeting(counter.incrementAndGet(), String.format(template, name)); } @RequestMapping("/greetingdf") public DeferredResult<Greeting> greetingdf(@RequestParam(value="name", required=false, defaultValue="World") String name) { DeferredResult<Greeting> deferredResult = new DeferredResult<Greeting>(); MyCall mc = new MyCall( deferredResult , template,name,counter ); es.execute(mc); return deferredResult; |
Line 318: | Line 377: |
* catalina.sh start * tail -f catalina.out |
|
Line 321: | Line 382: |
== Spring MVC == | == Spring MVC (SpringBoot) == |
Line 384: | Line 445: |
* cd src/main/java/hello/ * nano GreetingController.java |
* nano src/main/java/hello/GreetingController.java |
Line 462: | Line 523: |
{{{ | {{{#!highlight xml |
Line 497: | Line 558: |
{{{ | {{{#!highlight java |
Line 519: | Line 580: |
{{{ | {{{#!highlight xml |
Line 541: | Line 602: |
{{{ | {{{#!highlight xml |
Line 555: | Line 616: |
{{{ | {{{#!highlight xml |
Line 589: | Line 650: |
== testSpringThymeleaf == Maven Structure |
== testSpringThymeleaf ( Spring MVC + Thymeleaf + Bootstrap + JQuery + Tomcat ) == '''Maven Structure''' |
Line 601: | Line 662: |
| | |-- HelloController.java | | | `-- HelloController.java |
Line 603: | Line 664: |
| `-- WEB-INF | |-- mvc-dispatcher-servlet.xml | |-- pages | | |-- greeting.html | |-- web.xml }}} pom.xml |
| |-- WEB-INF | | |-- mvc-dispatcher-servlet.xml | | |-- pages | | | |-- greeting.html | | |-- web.xml | |-- css | | `-- bootstrap-3.3.2.min.css | `-- js | |-- bootstrap-3.3.2.min.js | |-- greeting.js | `-- jquery-1.11.2.min.js }}} '''pom.xml''' |
Line 612: | Line 679: |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
Line 619: | Line 689: |
Line 621: | Line 690: |
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>2.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.10</version> </dependency> |
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>2.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.10</version> </dependency> |
Line 657: | Line 724: |
HelloController.java | '''HelloController.java''' |
Line 678: | Line 745: |
mvc-dispatcher-servlet.xml | '''mvc-dispatcher-servlet.xml''' |
Line 681: | Line 748: |
xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" |
xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" |
Line 687: | Line 755: |
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="org.allowed.bitarus.hello" /> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML5" /> <property name="cacheable" value="false" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="order" value="1" /> </bean> |
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="org.allowed.bitarus.hello" /> <!-- Enabling Spring MVC configuration through annotations --> <mvc:annotation-driven /> <!-- Mapping Static Resources --> <mvc:resources mapping="/js/**" location="/js/" /> <mvc:resources mapping="/css/**" location="/css/" /> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML5" /> <property name="cacheable" value="false" /> <property name="characterEncoding" value="UTF-8" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="order" value="1" /> <property name="characterEncoding" value="UTF-8" /> </bean> |
Line 705: | Line 783: |
greeting.html | '''greeting.html''' |
Line 709: | Line 787: |
<head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'Hello, ' + ${name} + '!'" /> </body> |
<head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"/> <script th:src="@{/js/jquery-1.11.2.min.js}"></script> <script th:src="@{/js/bootstrap-3.3.2.min.js}"></script> <script th:src="@{/js/greeting.js}"></script> <link rel="stylesheet" th:href="@{/css/bootstrap-3.3.2.min.css}"/> </head> <body> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <ul class="nav navbar-nav" style="width: 100%;"> <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> </ul> </li> </ul> <h1>My First Bootstrap Page</h1> <p>This part is inside a .container class.</p> <p>The .container class provides a responsive fixed width container.</p> <p th:text="'Hello, ' + ${name} + '!'" /> <div class="row"> <div class="col-sm-4">.col-sm-4</div> <div class="col-sm-4">.col-sm-4</div> <div class="col-sm-4">.col-sm-4</div> </div> <div class="row"> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> <div class="col-md-4">.col-md-4</div> </div> <ul class="nav nav-tabs"> <li role="presentation" class="tabHome"><a href="#">Home</a></li> <li role="presentation" class="tabProfile"><a href="#">Profile</a></li> <li role="presentation" class="tabMessages"><a href="#">Messages</a></li> </ul> <div class="panel panel-primary panelHome"> <div class="panel-heading"> <h3 class="panel-title">Panel home</h3> </div> <div class="panel-body"> This is a Basic panel home <form role="form"> <div class="form-group"> <label for="email">Email address:</label> <input type="email" class="form-control" id="email"/> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" id="pwd"/> </div> <div class="checkbox"> <label><input type="checkbox"/> Remember me</label> </div> <button id="submitButton" type="submit" class="btn btn-default">Click to show modal</button> </form> </div> </div> <div class="panel panel-primary panelProfile"> <div class="panel-heading"> <h3 class="panel-title">Panel profile</h3> </div> <div class="panel-body"> </div> </div> <div class="panel panel-primary panelMessages"> <div class="panel-heading"> <h3 class="panel-title">Panel messages</h3> </div> <div class="panel-body"> </div> </div> </div> <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">Confirmation</h4> </div> <div class="modal-body"> <p>Do you want to save changes you made to document before closing?</p> <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </nav> </body> |
Line 719: | Line 894: |
web.xml | '''web.xml''' |
Line 722: | Line 897: |
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring MVC Application + Thymeleaf</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> |
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring MVC Application + Thymeleaf</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> |
Line 739: | Line 911: |
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> |
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> |
Line 751: | Line 918: |
'''greeting.js''' {{{#!highlight java $(document).ready(greetingReady); function greetingReady(){ console.log("greeting ready !!!!"); $('.tabHome').click(homeClicked); $('.tabProfile').click(profileClicked); $('.tabMessages').click(messagesClicked); $('.tabHome').addClass('active'); $('.panelHome').show(); $('.panelProfile').hide(); $('.panelMessages').hide(); $('.panel-heading').click(headingClicked); $('#submitButton').click(submitClicked); } function submitClicked(event){ $('#myModal').modal('show'); } function headingClicked(){ $('.panel-body').toggle(); } function homeClicked(event){ event.preventDefault(); event.stopPropagation(); $('.panelHome').show(); $('.panelProfile').hide(); $('.panelMessages').hide(); $('.tabHome').addClass('active'); $('.tabProfile').removeClass('active'); $('.tabMessages').removeClass('active'); } function profileClicked(event){ event.preventDefault(); event.stopPropagation(); $('.panelHome').hide(); $('.panelProfile').show(); $('.panelMessages').hide(); $('.tabHome').removeClass('active'); $('.tabProfile').addClass('active'); $('.tabMessages').removeClass('active'); } function messagesClicked(event){ event.preventDefault(); event.stopPropagation(); $('.panelHome').hide(); $('.panelProfile').hide(); $('.panelMessages').show(); $('.tabHome').removeClass('active'); $('.tabProfile').removeClass('active'); $('.tabMessages').addClass('active'); } }}} |
|
Line 752: | Line 980: |
* Access in Tomcat http://localhost:8081/testSpringMVCThymeleaf-0.1.0/hello?name=agh | * Deploy in Tomcat listening in 8081. Access in Tomcat http://localhost:8081/testSpringMVCThymeleaf-0.1.0/hello?name=agh == spring-mvc-html == Project structure: {{{ . |-- pom.xml |-- src | `-- main | |-- java | | `-- org | | `-- allowed | | `-- bitarus | | `-- spring | | `-- mvc | | `-- html | | |-- ConfigX.java | | |-- ContextServletListener.java | | |-- HelloController.java | | |-- TestDAO.java | | `-- ThreadTimer.java | |-- resources | | |-- log4j.properties | | `-- test.sql | `-- webapp | `-- WEB-INF | |-- applicationContext.xml | |-- mvc-dispatcher-servlet.xml | |-- pages | | `-- greeting.jsp | `-- web.xml }}} Uses Spring 4, Tomcat 7.0.X, commons-dbcp, MariaDB, Gson and log4j. === pom.xml === {{{#!highlight xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.allowed.bitarus</groupId> <artifactId>spring-mvc-html</artifactId> <version>0.1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>1.4.4</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> </project> }}} === web.xml === {{{#!highlight xml <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring MVC- HTML</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> }}} === applicationContext.xml === {{{#!highlight xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> </beans> }}} === mvc-dispatcher-servlet.xml === {{{#!highlight xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="org.allowed.bitarus.spring.mvc.html" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- <bean id="testDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.mariadb.jdbc.Driver" /> <property name="url" value="jdbc:mariadb://localhost:3306/springmvchtml" /> <property name="username" value="usertest" /> <property name="password" value="????????" /> </bean> --> <bean id="testDatasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" > <property name="driverClassName" value="org.mariadb.jdbc.Driver"/> <!--<property name="url" value="jdbc:mariadb://localhost:3306/springmvchtml"/>--> <!--export JAVA_OPTS=-DspringJdbcUrl=jdbc:mariadb://localhost:3306/springmvchtml--> <property name="url" value="#{systemProperties['springJdbcUrl']}"/> <property name="username" value="usertest"/> <property name="password" value="????????"/> <property name="initialSize" value="3"/> </bean> <bean id="configx" class="org.allowed.bitarus.spring.mvc.html.ConfigX"> <property name="viewList"> <list> <value>greeting</value> </list> </property> </bean> <bean id="threadTimer" class="org.allowed.bitarus.spring.mvc.html.ThreadTimer" init-method="start" destroy-method="destroy"> <constructor-arg index="0" value="30000" /> </bean> <bean id="testJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg index="0" ref="testDatasource" /> </bean> <bean id="testDAO" class="org.allowed.bitarus.spring.mvc.html.TestDAO"/> </beans> }}} === log4j.properties === {{{#!highlught bash log4j.rootLogger = ALL, rootLogger log4j.appender.rootLogger=org.apache.log4j.FileAppender log4j.appender.rootLogger.File=/tmp/testlog.out log4j.appender.rootLogger.layout=org.apache.log4j.PatternLayout log4j.appender.rootLogger.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.rootLogger.Threshold=ALL log4j.appender.rootLogger.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.HelloController=ALL,helloConsConsole log4j.appender.helloConsConsole=org.apache.log4j.ConsoleAppender log4j.appender.helloConsConsole.layout=org.apache.log4j.PatternLayout log4j.appender.helloConsConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.helloConsConsole.Threshold=DEBUG log4j.appender.helloConsConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.ThreadTimer=ALL,threadTimerConsole log4j.appender.threadTimerConsole=org.apache.log4j.ConsoleAppender log4j.appender.threadTimerConsole.layout=org.apache.log4j.PatternLayout log4j.appender.threadTimerConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.threadTimerConsole.Threshold=DEBUG log4j.appender.threadTimerConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.TestDAO=ALL,testDAOConsole log4j.appender.testDAOConsole=org.apache.log4j.ConsoleAppender log4j.appender.testDAOConsole.layout=org.apache.log4j.PatternLayout log4j.appender.testDAOConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.testDAOConsole.Threshold=DEBUG log4j.appender.testDAOConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.ConfigX=ALL,configXConsole log4j.appender.configXConsole=org.apache.log4j.ConsoleAppender log4j.appender.configXConsole.layout=org.apache.log4j.PatternLayout log4j.appender.configXConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.configXConsole.Threshold=DEBUG log4j.appender.configXConsole.Threshold=INFO }}} === test.sql === {{{#!highlight sql --JDBC URL: jdbc:mariadb://localhost:3306/springmvchtml create database springmvchtml; create user 'usertest'@'%' identified by '????????'; create user 'usertest'@'localhost' identified by '????????'; grant all on springmvchtml.* to 'usertest'@'%'; grant all on springmvchtml.* to 'usertest'@'localhost'; show grants for 'usertest'@'%'; show grants for 'usertest'@'localhost'; create table springmvchtml.dummy (name varchar(255) ) ; insert into springmvchtml.dummy (name) values('aaaa'); insert into springmvchtml.dummy (name) values('bbbb'); commit; }}} === TestDAO.java === {{{#!highlight java package org.allowed.bitarus.spring.mvc.html; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.JdbcTemplate; public class TestDAO { @Autowired @Qualifier("testJdbcTemplate") private JdbcTemplate jdbcTemplate; private Logger logger; public TestDAO() { this.logger = Logger.getLogger(TestDAO.class); logger.info("Created " + this.getClass().getSimpleName()); } public String getNameFromDummy() { return this.jdbcTemplate.queryForObject("select name from dummy limit 1", String.class); } } }}} === ThreadTimer.java === {{{#!highlight java package org.allowed.bitarus.spring.mvc.html; import java.text.MessageFormat; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; public class ThreadTimer extends Thread { private int delaySeconds; private Logger logger; private boolean running; @Autowired TestDAO testDAO; public ThreadTimer(int delaySeconds) { this.logger = Logger.getLogger(ThreadTimer.class); logger.info("Created instance of " + this.getClass().getSimpleName()); this.running = true; this.delaySeconds = delaySeconds; this.setName(this.getClass().getSimpleName() + "_" + this.getName()); } public void run() { while (running) { try { Thread.sleep(this.delaySeconds); logger.info("Delay " + this.getClass().getSimpleName()); if (testDAO != null) { logger.info(MessageFormat.format("{0}", testDAO.getNameFromDummy())); } } catch (InterruptedException e) { logger.info("ThreadTimer interrupted exception:" + e.getMessage() ); } catch (Exception e) { logger.info("ThreadTimer exception:" + e.getMessage() ); stopRunning(); } } logger.info("Exited " + this.getClass().getSimpleName()); } public void startRunning() { this.running = true; } public void stopRunning() { this.running = false; } public void destroy(){ logger.info("Called destroy"); this.stopRunning(); this.interrupt(); } } }}} === ConfigX.java === {{{#!highlight java package org.allowed.bitarus.spring.mvc.html; import java.util.List; import org.apache.log4j.Logger; public class ConfigX { private Logger logger; private List<String> viewList; public ConfigX() { this.logger = Logger.getLogger(ConfigX.class); this.logger.info("Created instance of ConfigX"); } public List<String> getViewList() { return viewList; } public void setViewList(List<String> viewList) { this.viewList = viewList; } } }}} === ContextServletListener.java === {{{#!highlight java package org.allowed.bitarus.spring.mvc.html; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; import javax.servlet.annotation.WebListener; import java.sql.Driver; import java.sql.DriverManager; @WebListener public class ContextServletListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce){ System.out.println("ContextServletListener init"); } public void contextDestroyed(ServletContextEvent sce) { //export JAVA_OPTS=-DspringJdbcUrl=jdbc:mariadb://localhost:3306/springmvchtml System.out.println("ContextServletListener destroyed"); try { //Driver mySqlDriver = DriverManager.getDriver("jdbc:mariadb://localhost:3306/springmvchtml"); Driver mySqlDriver = DriverManager.getDriver( System.getProperty("springJdbcUrl") ); DriverManager.deregisterDriver(mySqlDriver); } catch(Exception ex){ System.out.println(ex.getMessage()); } } } }}} === HelloController.java === {{{#!highlight java package org.allowed.bitarus.spring.mvc.html; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; @Controller public class HelloController { protected class JsonObj { private String fieldX; public String getFieldX() { return fieldX; } public void setFieldX(String fieldX) { this.fieldX = fieldX; } } @Autowired @Qualifier("configx") private ConfigX configx; private Logger logger; public HelloController() { this.logger = Logger.getLogger(HelloController.class); logger.info("Created " + this.getClass().getSimpleName()); } @RequestMapping("/helloVal/{name}") public String helloVal(@PathVariable(value = "name") String name, Model model) { // http://localhost:8081/spring-mvc-html-0.1.0/helloVal/asd logger.info("helloVal with " + name); model.addAttribute("name", name); // set data in model return configx.getViewList().get(0); // view JSP } @RequestMapping(value = "/hello", produces = "application/json") @ResponseBody public String hellox(@RequestParam(value = "name", required = false, defaultValue = "World") String name) { // http://localhost:8081/spring-mvc-html-0.1.0/hello?name=asdkkk logger.info("hellox with " + name); JsonObj jo = new JsonObj(); jo.setFieldX(name); return new Gson().toJson(jo); } } }}} === greeting.jsp === {{{#!highlight html <html> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Hello ${name}</p> </body> </html> }}} |
Contents
Spring
Spring helps development teams everywhere build simple, portable, fast and flexible JVM-based systems and applications.
http://spring.io/guides/gs/serving-web-content/
http://spring.io/guides/gs/convert-jar-to-war-maven/
ApplicationContextAware
ApplicationContextAware, Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
ResourceLoaderAware
ResourceLoaderAware, Interface to be implemented by any object that wishes to be notified of the ResourceLoader (typically the ApplicationContext) that it runs in.
EnvironmentAware
EnvironmentAware, Interface to be implemented by any bean that wishes to be notified of the Environment that it runs in.
REST service (SpringBoot)
spring.io/guides/gs/rest-service/
Structure
. |-- pom.xml |-- src | `-- main | `-- java | `-- hello | |-- Application.java | |-- Greeting.java | `-- GreetingController.java
Steps
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 http://maven.apache.org/xsd/maven-4.0.0.xsd">
6 <modelVersion>4.0.0</modelVersion>
7 <groupId>org.springframework</groupId>
8 <artifactId>gs-rest-service</artifactId>
9 <version>0.1.0</version>
10 <parent>
11 <groupId>org.springframework.boot</groupId>
12 <artifactId>spring-boot-starter-parent</artifactId>
13 <version>1.1.5.RELEASE</version>
14 </parent>
15 <dependencies>
16 <dependency>
17 <groupId>org.springframework.boot</groupId>
18 <artifactId>spring-boot-starter-web</artifactId>
19 </dependency>
20 </dependencies>
21 <properties>
22 <start-class>hello.Application</start-class>
23 </properties>
24 <build>
25 <plugins>
26 <plugin>
27 <artifactId>maven-compiler-plugin</artifactId>
28 <version>2.3.2</version>
29 </plugin>
30 <plugin>
31 <groupId>org.springframework.boot</groupId>
32 <artifactId>spring-boot-maven-plugin</artifactId>
33 </plugin>
34 </plugins>
35 </build>
36 <repositories>
37 <repository>
38 <id>spring-releases</id>
39 <url>http://repo.spring.io/libs-release</url>
40 </repository>
41 </repositories>
42 <pluginRepositories>
43 <pluginRepository>
44 <id>spring-releases</id>
45 <url>http://repo.spring.io/libs-release</url>
46 </pluginRepository>
47 </pluginRepositories>
48 </project>
src/main/java/hello/Application.java
1 package hello;
2
3 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
4 import org.springframework.boot.SpringApplication;
5 import org.springframework.context.annotation.ComponentScan;
6
7 @ComponentScan
8 @EnableAutoConfiguration
9 public class Application {
10
11 public static void main(String[] args) {
12 SpringApplication.run(Application.class, args);
13 }
14 }
src/main/java/hello/Greeting.java
1 package hello;
2
3 public class Greeting {
4
5 private final long id;
6 private final String content;
7
8 public Greeting(long id, String content) {
9 this.id = id;
10 this.content = content;
11 }
12
13 public long getId() {
14 return id;
15 }
16
17 public String getContent() {
18 return content;
19 }
20 }
src/main/java/hello/GreetingController.java
1 package hello;
2
3 import java.util.concurrent.atomic.AtomicLong;
4 import org.springframework.web.bind.annotation.RequestMapping;
5 import org.springframework.web.bind.annotation.RequestParam;
6 import org.springframework.web.bind.annotation.RestController;
7
8 import org.springframework.web.context.request.async.DeferredResult;
9 import java.util.concurrent.Callable;
10 import java.util.concurrent.ExecutorService;
11 import java.util.concurrent.Executors;
12
13 @RestController
14 public class GreetingController {
15 private ExecutorService es = Executors.newFixedThreadPool(50);
16
17 public class MyCall implements Runnable {
18
19 private DeferredResult df;
20 private String template;
21 private String name;
22 private AtomicLong counter;
23
24 public MyCall(DeferredResult df, String template, String name, AtomicLong counter){
25 this.df = df;
26 this.template=template;
27 this.name=name;
28 this.counter = counter;
29 }
30
31 @Override
32 public void run(){
33 Greeting g = new Greeting(this.counter.incrementAndGet(), String.format(this.template, this.name));
34 this.df.setResult(g);
35 }
36 }
37
38 private static final String template = "Hello, %s!";
39 private final AtomicLong counter = new AtomicLong();
40
41 @RequestMapping("/greeting")
42 public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) {
43 return new Greeting(counter.incrementAndGet(), String.format(template, name));
44 }
45
46 @RequestMapping("/greetingdf")
47 public DeferredResult<Greeting> greetingdf(@RequestParam(value="name", required=false, defaultValue="World") String name) {
48 DeferredResult<Greeting> deferredResult = new DeferredResult<Greeting>();
49 MyCall mc = new MyCall( deferredResult , template,name,counter );
50 es.execute(mc);
51 return deferredResult;
52 }
53 }
Build with
- mvn clean compile package
Run with:
- jar -tf target/gs-rest-service-0.1.0.jar # check JAR contents
- java -jar target/gs-rest-service-0.1.0.jar
open URL http://localhost:8080/greeting
Tomcat REST service
Structure
. |-- pom.xml |-- src `-- main `-- java `-- hello |-- Application.java |-- Greeting.java `-- GreetingController.java
pom.xml
1 <project xmlns="http://maven.apache.org/POM/4.0.0"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <modelVersion>4.0.0</modelVersion>
6 <groupId>org.springframework</groupId>
7 <artifactId>gs-rest-service-tomcat</artifactId>
8 <version>0.1.0</version>
9 <packaging>war</packaging>
10
11 <parent>
12 <groupId>org.springframework.boot</groupId>
13 <artifactId>spring-boot-starter-parent</artifactId>
14 <version>1.1.5.RELEASE</version>
15 </parent>
16
17 <dependencies>
18 <dependency>
19 <groupId>org.springframework.boot</groupId>
20 <artifactId>spring-boot-starter-web</artifactId>
21 <scope>compile</scope>
22 </dependency>
23 </dependencies>
24
25 <properties>
26 <start-class>hello.Application</start-class>
27 </properties>
28 <build>
29 <plugins>
30 <plugin>
31 <artifactId>maven-compiler-plugin</artifactId>
32 <version>2.3.2</version>
33 </plugin>
34 </plugins>
35 </build>
36 <repositories>
37 <repository>
38 <id>spring-releases</id>
39 <url>http://repo.spring.io/libs-release</url>
40 </repository>
41 </repositories>
42 <pluginRepositories>
43 <pluginRepository>
44 <id>spring-releases</id>
45 <url>http://repo.spring.io/libs-release</url>
46 </pluginRepository>
47 </pluginRepositories>
48 </project>
src/main/java/hello/Application.java
1 package hello;
2
3 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
4 import org.springframework.boot.SpringApplication;
5 import org.springframework.context.annotation.ComponentScan;
6 import org.springframework.boot.context.web.SpringBootServletInitializer;
7 import org.springframework.boot.builder.SpringApplicationBuilder;
8 import org.springframework.context.annotation.Configuration;
9
10 @ComponentScan
11 @EnableAutoConfiguration
12 @Configuration
13 public class Application extends SpringBootServletInitializer {
14
15 public static void main(String[] args) {
16 SpringApplication.run(appClass, args);
17 }
18
19 @Override
20 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
21 return application.sources(appClass);
22 }
23
24 private static Class<Application> appClass = Application.class;
25 }
src/main/java/hello/Greeting.java
1 package hello;
2
3 public class Greeting {
4
5 private final long id;
6 private final String content;
7
8 public Greeting(long id, String content) {
9 this.id = id;
10 this.content = content;
11 }
12
13 public long getId() {
14 return id;
15 }
16
17 public String getContent() {
18 return content;
19 }
20 }
src/main/java/hello/GreetingController.java
1 package hello;
2
3 import java.util.concurrent.atomic.AtomicLong;
4 import org.springframework.web.bind.annotation.RequestMapping;
5 import org.springframework.web.bind.annotation.RequestParam;
6 import org.springframework.web.bind.annotation.RestController;
7
8 @RestController
9 public class GreetingController {
10
11 private static final String template = "Hello Tomcat, %s!";
12 private final AtomicLong counter = new AtomicLong();
13
14 @RequestMapping("/greetingTomcat")
15 public Greeting greeting(@RequestParam(value="name", required=false, defaultValue="World") String name) {
16 return new Greeting(counter.incrementAndGet(), String.format(template, name));
17 }
18 }
Build and deploy
- mvn clean compile package install
- cp target/gs-rest-service-tomcat-0.1.0.war /usr/local/tomcat/webapps/
- cp target/gs-rest-service-tomcat-0.1.0.war /opt/apache-tomcat-7.0.53/webapps/ # in alternative
- catalina.sh start
- tail -f catalina.out
Open http://localhost:8080/gs-rest-service-tomcat-0.1.0/greetingTomcat
Spring MVC (SpringBoot)
Structure:
. |-- pom.xml |-- src `-- main |-- java | `-- hello | |-- Application.java | `-- GreetingController.java `-- resources `-- templates `-- greeting.html
- mkdir -p src/main/java/hello
- mkdir -p src/main/resources/templates/
- nano pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5 <groupId>org.springframework</groupId>
6 <artifactId>gs-serving-web-content</artifactId>
7 <version>0.1.0</version>
8 <parent>
9 <groupId>org.springframework.boot</groupId>
10 <artifactId>spring-boot-starter-parent</artifactId>
11 <version>1.1.8.RELEASE</version>
12 </parent>
13 <dependencies>
14 <dependency>
15 <groupId>org.springframework.boot</groupId>
16 <artifactId>spring-boot-starter-thymeleaf</artifactId>
17 </dependency>
18 </dependencies>
19 <properties>
20 <start-class>hello.Application</start-class>
21 </properties>
22 <build>
23 <plugins>
24 <plugin>
25 <groupId>org.springframework.boot</groupId>
26 <artifactId>spring-boot-maven-plugin</artifactId>
27 </plugin>
28 </plugins>
29 </build>
30 <repositories>
31 <repository>
32 <id>spring-milestone</id>
33 <url>http://repo.spring.io/libs-release</url>
34 </repository>
35 </repositories>
36 <pluginRepositories>
37 <pluginRepository>
38 <id>spring-milestone</id>
39 <url>http://repo.spring.io/libs-release</url>
40 </pluginRepository>
41 </pluginRepositories>
42 </project>
- nano src/main/java/hello/GreetingController.java
1 package hello;
2
3 import org.springframework.stereotype.Controller;
4 import org.springframework.ui.Model;
5 import org.springframework.web.bind.annotation.RequestMapping;
6 import org.springframework.web.bind.annotation.RequestParam;
7
8 @Controller
9 public class GreetingController {
10
11 @RequestMapping("/greeting")
12 public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
13 model.addAttribute("name", name);
14 return "greeting";
15 }
16
17 }
- nano src/main/resources/templates/greeting.html
- nano src/main/java/hello/Application.java
1 package hello;
2
3 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
4 import org.springframework.boot.SpringApplication;
5 import org.springframework.context.annotation.ComponentScan;
6
7 @ComponentScan
8 @EnableAutoConfiguration
9 public class Application {
10
11 public static void main(String[] args) {
12 SpringApplication.run(Application.class, args);
13 }
14
15 }
- mvn clean compile package install
- java -jar target/gs-serving-web-content-0.1.0.jar
testSpringMVCJSP
Structure Maven:
. |-- pom.xml |-- src | `-- main | |-- java | | `-- org | | `-- allowed | | `-- bitarus | | `-- hello | | `-- HelloController.java | `-- webapp | `-- WEB-INF | |-- mvc-dispatcher-servlet.xml | |-- pages | | `-- greeting.jsp | `-- web.xml
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 http://maven.apache.org/xsd/maven-4.0.0.xsd">
6 <modelVersion>4.0.0</modelVersion>
7 <groupId>org.allowed.bitarus</groupId>
8 <artifactId>testSpringMVCJSP</artifactId>
9 <version>0.1.0</version>
10 <packaging>war</packaging>
11
12 <dependencies>
13 <dependency>
14 <groupId>org.springframework</groupId>
15 <artifactId>spring-core</artifactId>
16 <version>4.1.4.RELEASE</version>
17 </dependency>
18
19 <dependency>
20 <groupId>org.springframework</groupId>
21 <artifactId>spring-web</artifactId>
22 <version>4.1.4.RELEASE</version>
23 </dependency>
24
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-webmvc</artifactId>
28 <version>4.1.4.RELEASE</version>
29 </dependency>
30 </dependencies>
31 </project>
HelloController.java
1 package org.allowed.bitarus.hello;
2
3 import org.springframework.stereotype.Controller;
4 import org.springframework.ui.Model;
5 import org.springframework.web.bind.annotation.RequestMapping;
6 import org.springframework.web.bind.annotation.RequestParam;
7
8 @Controller
9 public class HelloController {
10
11 @RequestMapping("/hello")
12 public String hellox(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
13 model.addAttribute("name", name);
14 return "greeting";
15 }
16
17 }
mvc-dispatcher-servlet.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="
5 http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/context
8 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
9 <context:component-scan base-package="org.allowed.bitarus.hello" />
10 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
11 <property name="prefix">
12 <value>/WEB-INF/pages/</value>
13 </property>
14 <property name="suffix">
15 <value>.jsp</value>
16 </property>
17 </bean>
18 </beans>
greeting.jsp
web.xml
1 <web-app id="WebApp_ID" version="2.4"
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6
7 <display-name>Spring MVC Application + JSP</display-name>
8 <servlet>
9 <servlet-name>mvc-dispatcher</servlet-name>
10 <servlet-class>
11 org.springframework.web.servlet.DispatcherServlet
12 </servlet-class>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>mvc-dispatcher</servlet-name>
17 <url-pattern>/</url-pattern>
18 </servlet-mapping>
19 <context-param>
20 <param-name>contextConfigLocation</param-name>
21 <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
22 </context-param>
23 <listener>
24 <listener-class>
25 org.springframework.web.context.ContextLoaderListener
26 </listener-class>
27 </listener>
28 </web-app>
- mvn clean compile package
Access in Tomcat http://localhost:8081/testSpringMVCJSP-0.1.0/hello?name=asd
testSpringThymeleaf ( Spring MVC + Thymeleaf + Bootstrap + JQuery + Tomcat )
Maven Structure
. |-- pom.xml |-- src | `-- main | |-- java | | `-- org | | `-- allowed | | `-- bitarus | | `-- hello | | `-- HelloController.java | `-- webapp | |-- WEB-INF | | |-- mvc-dispatcher-servlet.xml | | |-- pages | | | |-- greeting.html | | |-- web.xml | |-- css | | `-- bootstrap-3.3.2.min.css | `-- js | |-- bootstrap-3.3.2.min.js | |-- greeting.js | `-- jquery-1.11.2.min.js
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
5 http://maven.apache.org/xsd/maven-4.0.0.xsd">
6 <modelVersion>4.0.0</modelVersion>
7 <groupId>org.allowed.bitarus</groupId>
8 <artifactId>testSpringMVCThymeleaf</artifactId>
9 <version>0.1.0</version>
10 <packaging>war</packaging>
11 <dependencies>
12 <dependency>
13 <groupId>org.springframework</groupId>
14 <artifactId>spring-core</artifactId>
15 <version>4.1.4.RELEASE</version>
16 </dependency>
17 <dependency>
18 <groupId>org.springframework</groupId>
19 <artifactId>spring-web</artifactId>
20 <version>4.1.4.RELEASE</version>
21 </dependency>
22 <dependency>
23 <groupId>org.springframework</groupId>
24 <artifactId>spring-webmvc</artifactId>
25 <version>4.1.4.RELEASE</version>
26 </dependency>
27 <dependency>
28 <groupId>org.thymeleaf</groupId>
29 <artifactId>thymeleaf-spring4</artifactId>
30 <version>2.1.4.RELEASE</version>
31 </dependency>
32 <dependency>
33 <groupId>org.slf4j</groupId>
34 <artifactId>slf4j-api</artifactId>
35 <version>1.7.10</version>
36 </dependency>
37 <dependency>
38 <groupId>org.slf4j</groupId>
39 <artifactId>slf4j-log4j12</artifactId>
40 <version>1.7.10</version>
41 </dependency>
42 </dependencies>
43 </project>
HelloController.java
1 package org.allowed.bitarus.hello;
2
3 import org.springframework.stereotype.Controller;
4 import org.springframework.ui.Model;
5 import org.springframework.web.bind.annotation.RequestMapping;
6 import org.springframework.web.bind.annotation.RequestParam;
7
8 @Controller
9 public class HelloController {
10
11 @RequestMapping("/hello")
12 public String hellox(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
13 model.addAttribute("name", name);
14 return "greeting";
15 }
16
17 }
mvc-dispatcher-servlet.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xsi:schemaLocation="
6 http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context-3.0.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12 <context:component-scan base-package="org.allowed.bitarus.hello" />
13 <!-- Enabling Spring MVC configuration through annotations -->
14 <mvc:annotation-driven />
15 <!-- Mapping Static Resources -->
16 <mvc:resources mapping="/js/**" location="/js/" />
17 <mvc:resources mapping="/css/**" location="/css/" />
18
19 <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
20 <property name="prefix" value="/WEB-INF/pages/" />
21 <property name="suffix" value=".html" />
22 <property name="templateMode" value="HTML5" />
23 <property name="cacheable" value="false" />
24 <property name="characterEncoding" value="UTF-8" />
25 </bean>
26 <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
27 <property name="templateResolver" ref="templateResolver" />
28 </bean>
29 <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
30 <property name="templateEngine" ref="templateEngine" />
31 <property name="order" value="1" />
32 <property name="characterEncoding" value="UTF-8" />
33 </bean>
34 </beans>
greeting.html
1 <!DOCTYPE HTML>
2 <html xmlns:th="http://www.thymeleaf.org">
3 <head>
4 <title>Getting Started: Serving Web Content</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6 <meta name="viewport" content="width=device-width, initial-scale=1"/>
7 <script th:src="@{/js/jquery-1.11.2.min.js}"></script>
8 <script th:src="@{/js/bootstrap-3.3.2.min.js}"></script>
9 <script th:src="@{/js/greeting.js}"></script>
10 <link rel="stylesheet" th:href="@{/css/bootstrap-3.3.2.min.css}"/>
11 </head>
12 <body>
13 <nav class="navbar navbar-default navbar-fixed-top">
14
15 <div class="container">
16 <ul class="nav navbar-nav" style="width: 100%;">
17 <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
18 <li><a href="#">Link</a></li>
19 <li class="dropdown">
20 <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
21 <ul class="dropdown-menu" role="menu">
22 <li><a href="#">Action</a></li>
23 <li><a href="#">Another action</a></li>
24 </ul>
25 </li>
26 </ul>
27 <h1>My First Bootstrap Page</h1>
28 <p>This part is inside a .container class.</p>
29 <p>The .container class provides a responsive fixed width container.</p>
30 <p th:text="'Hello, ' + ${name} + '!'" />
31 <div class="row">
32 <div class="col-sm-4">.col-sm-4</div>
33 <div class="col-sm-4">.col-sm-4</div>
34 <div class="col-sm-4">.col-sm-4</div>
35 </div>
36 <div class="row">
37 <div class="col-md-4">.col-md-4</div>
38 <div class="col-md-4">.col-md-4</div>
39 <div class="col-md-4">.col-md-4</div>
40 </div>
41
42 <ul class="nav nav-tabs">
43 <li role="presentation" class="tabHome"><a href="#">Home</a></li>
44 <li role="presentation" class="tabProfile"><a href="#">Profile</a></li>
45 <li role="presentation" class="tabMessages"><a href="#">Messages</a></li>
46 </ul>
47
48 <div class="panel panel-primary panelHome">
49 <div class="panel-heading">
50 <h3 class="panel-title">Panel home</h3>
51 </div>
52 <div class="panel-body">
53 This is a Basic panel home
54 <form role="form">
55 <div class="form-group">
56 <label for="email">Email address:</label>
57 <input type="email" class="form-control" id="email"/>
58 </div>
59 <div class="form-group">
60 <label for="pwd">Password:</label>
61 <input type="password" class="form-control" id="pwd"/>
62 </div>
63 <div class="checkbox">
64 <label><input type="checkbox"/> Remember me</label>
65 </div>
66 <button id="submitButton" type="submit" class="btn btn-default">Click to show modal</button>
67 </form>
68 </div>
69 </div>
70 <div class="panel panel-primary panelProfile">
71 <div class="panel-heading">
72 <h3 class="panel-title">Panel profile</h3>
73 </div>
74 <div class="panel-body">
75 </div>
76 </div>
77 <div class="panel panel-primary panelMessages">
78 <div class="panel-heading">
79 <h3 class="panel-title">Panel messages</h3>
80 </div>
81 <div class="panel-body">
82 </div>
83 </div>
84 </div>
85
86 <div id="myModal" class="modal fade">
87 <div class="modal-dialog">
88 <div class="modal-content">
89 <div class="modal-header">
90 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
91 <h4 class="modal-title">Confirmation</h4>
92 </div>
93 <div class="modal-body">
94 <p>Do you want to save changes you made to document before closing?</p>
95 <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
96 </div>
97 <div class="modal-footer">
98 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
99 <button type="button" class="btn btn-primary">Save changes</button>
100 </div>
101 </div>
102 </div>
103 </div>
104
105 </nav>
106 </body>
107 </html>
web.xml
1 <web-app id="WebApp_ID" version="2.4"
2 xmlns="http://java.sun.com/xml/ns/j2ee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
5 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
6 <display-name>Spring MVC Application + Thymeleaf</display-name>
7 <servlet>
8 <servlet-name>mvc-dispatcher</servlet-name>
9 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10 <load-on-startup>1</load-on-startup>
11 </servlet>
12 <servlet-mapping>
13 <servlet-name>mvc-dispatcher</servlet-name>
14 <url-pattern>/</url-pattern>
15 </servlet-mapping>
16 <context-param>
17 <param-name>contextConfigLocation</param-name>
18 <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
19 </context-param>
20 </web-app>
greeting.js
1 $(document).ready(greetingReady);
2
3 function greetingReady(){
4 console.log("greeting ready !!!!");
5 $('.tabHome').click(homeClicked);
6 $('.tabProfile').click(profileClicked);
7 $('.tabMessages').click(messagesClicked);
8
9 $('.tabHome').addClass('active');
10 $('.panelHome').show();
11 $('.panelProfile').hide();
12 $('.panelMessages').hide();
13
14 $('.panel-heading').click(headingClicked);
15 $('#submitButton').click(submitClicked);
16 }
17
18 function submitClicked(event){
19 $('#myModal').modal('show');
20 }
21
22 function headingClicked(){
23 $('.panel-body').toggle();
24 }
25
26 function homeClicked(event){
27 event.preventDefault();
28 event.stopPropagation();
29 $('.panelHome').show();
30 $('.panelProfile').hide();
31 $('.panelMessages').hide();
32 $('.tabHome').addClass('active');
33 $('.tabProfile').removeClass('active');
34 $('.tabMessages').removeClass('active');
35 }
36
37 function profileClicked(event){
38 event.preventDefault();
39 event.stopPropagation();
40 $('.panelHome').hide();
41 $('.panelProfile').show();
42 $('.panelMessages').hide();
43 $('.tabHome').removeClass('active');
44 $('.tabProfile').addClass('active');
45 $('.tabMessages').removeClass('active');
46 }
47
48 function messagesClicked(event){
49 event.preventDefault();
50 event.stopPropagation();
51 $('.panelHome').hide();
52 $('.panelProfile').hide();
53 $('.panelMessages').show();
54 $('.tabHome').removeClass('active');
55 $('.tabProfile').removeClass('active');
56 $('.tabMessages').addClass('active');
57 }
- mvn clean compile package
Deploy in Tomcat listening in 8081. Access in Tomcat http://localhost:8081/testSpringMVCThymeleaf-0.1.0/hello?name=agh
spring-mvc-html
Project structure:
. |-- pom.xml |-- src | `-- main | |-- java | | `-- org | | `-- allowed | | `-- bitarus | | `-- spring | | `-- mvc | | `-- html | | |-- ConfigX.java | | |-- ContextServletListener.java | | |-- HelloController.java | | |-- TestDAO.java | | `-- ThreadTimer.java | |-- resources | | |-- log4j.properties | | `-- test.sql | `-- webapp | `-- WEB-INF | |-- applicationContext.xml | |-- mvc-dispatcher-servlet.xml | |-- pages | | `-- greeting.jsp | `-- web.xml
Uses Spring 4, Tomcat 7.0.X, commons-dbcp, MariaDB, Gson and log4j.
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5 <groupId>org.allowed.bitarus</groupId>
6 <artifactId>spring-mvc-html</artifactId>
7 <version>0.1.0</version>
8 <packaging>war</packaging>
9 <dependencies>
10 <dependency>
11 <groupId>org.springframework</groupId>
12 <artifactId>spring-core</artifactId>
13 <version>4.1.4.RELEASE</version>
14 </dependency>
15 <dependency>
16 <groupId>org.springframework</groupId>
17 <artifactId>spring-web</artifactId>
18 <version>4.1.4.RELEASE</version>
19 </dependency>
20 <dependency>
21 <groupId>org.springframework</groupId>
22 <artifactId>spring-webmvc</artifactId>
23 <version>4.1.4.RELEASE</version>
24 </dependency>
25 <dependency>
26 <groupId>org.springframework</groupId>
27 <artifactId>spring-jdbc</artifactId>
28 <version>4.1.4.RELEASE</version>
29 </dependency>
30 <dependency>
31 <groupId>com.google.code.gson</groupId>
32 <artifactId>gson</artifactId>
33 <version>2.5</version>
34 </dependency>
35 <dependency>
36 <groupId>org.mariadb.jdbc</groupId>
37 <artifactId>mariadb-java-client</artifactId>
38 <version>1.4.4</version>
39 </dependency>
40 <dependency>
41 <groupId>log4j</groupId>
42 <artifactId>log4j</artifactId>
43 <version>1.2.17</version>
44 </dependency>
45 <dependency>
46 <groupId>javax.servlet</groupId>
47 <artifactId>javax.servlet-api</artifactId>
48 <version>3.1.0</version>
49 <scope>provided</scope>
50 </dependency>
51 <dependency>
52 <groupId>commons-dbcp</groupId>
53 <artifactId>commons-dbcp</artifactId>
54 <version>1.4</version>
55 </dependency>
56 </dependencies>
57 </project>
web.xml
1 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
2 <display-name>Spring MVC- HTML</display-name>
3 <servlet>
4 <servlet-name>mvc-dispatcher</servlet-name>
5 <servlet-class>
6 org.springframework.web.servlet.DispatcherServlet
7 </servlet-class>
8 <load-on-startup>1</load-on-startup>
9 </servlet>
10 <servlet-mapping>
11 <servlet-name>mvc-dispatcher</servlet-name>
12 <url-pattern>/</url-pattern>
13 </servlet-mapping>
14 <listener>
15 <listener-class>
16 org.springframework.web.context.ContextLoaderListener
17 </listener-class>
18 </listener>
19 </web-app>
applicationContext.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
5 </beans>
mvc-dispatcher-servlet.xml
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
5 <context:component-scan base-package="org.allowed.bitarus.spring.mvc.html" />
6 <bean
7 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
8 <property name="prefix">
9 <value>/WEB-INF/pages/</value>
10 </property>
11 <property name="suffix">
12 <value>.jsp</value>
13 </property>
14 </bean>
15 <!--
16 <bean id="testDatasource"
17 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
18 <property name="driverClassName" value="org.mariadb.jdbc.Driver" />
19 <property name="url"
20 value="jdbc:mariadb://localhost:3306/springmvchtml" />
21 <property name="username" value="usertest" />
22 <property name="password" value="????????" />
23 </bean>
24 -->
25 <bean id="testDatasource" class="org.apache.commons.dbcp.BasicDataSource"
26 destroy-method="close" >
27 <property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
28 <!--<property name="url" value="jdbc:mariadb://localhost:3306/springmvchtml"/>-->
29 <!--export JAVA_OPTS=-DspringJdbcUrl=jdbc:mariadb://localhost:3306/springmvchtml-->
30 <property name="url" value="#{systemProperties['springJdbcUrl']}"/>
31 <property name="username" value="usertest"/>
32 <property name="password" value="????????"/>
33 <property name="initialSize" value="3"/>
34 </bean>
35 <bean id="configx" class="org.allowed.bitarus.spring.mvc.html.ConfigX">
36 <property name="viewList">
37 <list>
38 <value>greeting</value>
39 </list>
40 </property>
41 </bean>
42 <bean id="threadTimer" class="org.allowed.bitarus.spring.mvc.html.ThreadTimer"
43 init-method="start" destroy-method="destroy">
44 <constructor-arg index="0" value="30000" />
45 </bean>
46 <bean id="testJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
47 <constructor-arg index="0" ref="testDatasource" />
48 </bean>
49 <bean id="testDAO" class="org.allowed.bitarus.spring.mvc.html.TestDAO"/>
50 </beans>
log4j.properties
log4j.rootLogger = ALL, rootLogger log4j.appender.rootLogger=org.apache.log4j.FileAppender log4j.appender.rootLogger.File=/tmp/testlog.out log4j.appender.rootLogger.layout=org.apache.log4j.PatternLayout log4j.appender.rootLogger.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.rootLogger.Threshold=ALL log4j.appender.rootLogger.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.HelloController=ALL,helloConsConsole log4j.appender.helloConsConsole=org.apache.log4j.ConsoleAppender log4j.appender.helloConsConsole.layout=org.apache.log4j.PatternLayout log4j.appender.helloConsConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.helloConsConsole.Threshold=DEBUG log4j.appender.helloConsConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.ThreadTimer=ALL,threadTimerConsole log4j.appender.threadTimerConsole=org.apache.log4j.ConsoleAppender log4j.appender.threadTimerConsole.layout=org.apache.log4j.PatternLayout log4j.appender.threadTimerConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.threadTimerConsole.Threshold=DEBUG log4j.appender.threadTimerConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.TestDAO=ALL,testDAOConsole log4j.appender.testDAOConsole=org.apache.log4j.ConsoleAppender log4j.appender.testDAOConsole.layout=org.apache.log4j.PatternLayout log4j.appender.testDAOConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.testDAOConsole.Threshold=DEBUG log4j.appender.testDAOConsole.Threshold=INFO log4j.logger.org.allowed.bitarus.spring.mvc.html.ConfigX=ALL,configXConsole log4j.appender.configXConsole=org.apache.log4j.ConsoleAppender log4j.appender.configXConsole.layout=org.apache.log4j.PatternLayout log4j.appender.configXConsole.layout.ConversionPattern=%d{ISO8601}|%p|%c|%t|%m%n #log4j.appender.configXConsole.Threshold=DEBUG log4j.appender.configXConsole.Threshold=INFO
test.sql
1 --JDBC URL: jdbc:mariadb://localhost:3306/springmvchtml
2 create database springmvchtml;
3 create user 'usertest'@'%' identified by '????????';
4 create user 'usertest'@'localhost' identified by '????????';
5 grant all on springmvchtml.* to 'usertest'@'%';
6 grant all on springmvchtml.* to 'usertest'@'localhost';
7 show grants for 'usertest'@'%';
8 show grants for 'usertest'@'localhost';
9 create table springmvchtml.dummy (name varchar(255) ) ;
10 insert into springmvchtml.dummy (name) values('aaaa');
11 insert into springmvchtml.dummy (name) values('bbbb');
12 commit;
TestDAO.java
1 package org.allowed.bitarus.spring.mvc.html;
2
3 import org.apache.log4j.Logger;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.beans.factory.annotation.Qualifier;
6 import org.springframework.jdbc.core.JdbcTemplate;
7
8 public class TestDAO {
9 @Autowired
10 @Qualifier("testJdbcTemplate")
11 private JdbcTemplate jdbcTemplate;
12 private Logger logger;
13
14 public TestDAO() {
15 this.logger = Logger.getLogger(TestDAO.class);
16 logger.info("Created " + this.getClass().getSimpleName());
17 }
18
19 public String getNameFromDummy() {
20 return this.jdbcTemplate.queryForObject("select name from dummy limit 1", String.class);
21 }
22
23 }
ThreadTimer.java
1 package org.allowed.bitarus.spring.mvc.html;
2
3 import java.text.MessageFormat;
4 import org.apache.log4j.Logger;
5 import org.springframework.beans.factory.annotation.Autowired;
6
7 public class ThreadTimer extends Thread {
8 private int delaySeconds;
9 private Logger logger;
10 private boolean running;
11
12 @Autowired
13 TestDAO testDAO;
14
15 public ThreadTimer(int delaySeconds) {
16 this.logger = Logger.getLogger(ThreadTimer.class);
17 logger.info("Created instance of " + this.getClass().getSimpleName());
18 this.running = true;
19 this.delaySeconds = delaySeconds;
20 this.setName(this.getClass().getSimpleName() + "_" + this.getName());
21 }
22
23 public void run() {
24 while (running) {
25 try {
26 Thread.sleep(this.delaySeconds);
27 logger.info("Delay " + this.getClass().getSimpleName());
28 if (testDAO != null) {
29 logger.info(MessageFormat.format("{0}", testDAO.getNameFromDummy()));
30 }
31 }
32 catch (InterruptedException e) {
33 logger.info("ThreadTimer interrupted exception:" + e.getMessage() );
34 }
35 catch (Exception e) {
36 logger.info("ThreadTimer exception:" + e.getMessage() );
37 stopRunning();
38 }
39 }
40 logger.info("Exited " + this.getClass().getSimpleName());
41 }
42
43 public void startRunning() {
44 this.running = true;
45 }
46
47 public void stopRunning() {
48 this.running = false;
49 }
50
51 public void destroy(){
52 logger.info("Called destroy");
53 this.stopRunning();
54 this.interrupt();
55 }
56 }
ConfigX.java
1 package org.allowed.bitarus.spring.mvc.html;
2
3 import java.util.List;
4 import org.apache.log4j.Logger;
5
6 public class ConfigX {
7 private Logger logger;
8 private List<String> viewList;
9
10 public ConfigX() {
11 this.logger = Logger.getLogger(ConfigX.class);
12 this.logger.info("Created instance of ConfigX");
13 }
14
15 public List<String> getViewList() {
16 return viewList;
17 }
18
19 public void setViewList(List<String> viewList) {
20 this.viewList = viewList;
21 }
22 }
ContextServletListener.java
1 package org.allowed.bitarus.spring.mvc.html;
2
3 import javax.servlet.ServletContextListener;
4 import javax.servlet.ServletContextEvent;
5 import javax.servlet.annotation.WebListener;
6 import java.sql.Driver;
7 import java.sql.DriverManager;
8
9 @WebListener
10 public class ContextServletListener implements ServletContextListener {
11 public void contextInitialized(ServletContextEvent sce){
12 System.out.println("ContextServletListener init");
13 }
14
15 public void contextDestroyed(ServletContextEvent sce) {
16 //export JAVA_OPTS=-DspringJdbcUrl=jdbc:mariadb://localhost:3306/springmvchtml
17 System.out.println("ContextServletListener destroyed");
18 try {
19 //Driver mySqlDriver = DriverManager.getDriver("jdbc:mariadb://localhost:3306/springmvchtml");
20 Driver mySqlDriver = DriverManager.getDriver( System.getProperty("springJdbcUrl") );
21 DriverManager.deregisterDriver(mySqlDriver);
22 }
23 catch(Exception ex){
24 System.out.println(ex.getMessage());
25 }
26 }
27 }
HelloController.java
1 package org.allowed.bitarus.spring.mvc.html;
2
3 import org.apache.log4j.Logger;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.beans.factory.annotation.Qualifier;
6 import org.springframework.stereotype.Controller;
7 import org.springframework.ui.Model;
8 import org.springframework.web.bind.annotation.PathVariable;
9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestParam;
11 import org.springframework.web.bind.annotation.ResponseBody;
12 import com.google.gson.Gson;
13
14 @Controller
15 public class HelloController {
16 protected class JsonObj {
17 private String fieldX;
18
19 public String getFieldX() {
20 return fieldX;
21 }
22
23 public void setFieldX(String fieldX) {
24 this.fieldX = fieldX;
25 }
26 }
27
28 @Autowired
29 @Qualifier("configx")
30 private ConfigX configx;
31 private Logger logger;
32
33 public HelloController() {
34 this.logger = Logger.getLogger(HelloController.class);
35 logger.info("Created " + this.getClass().getSimpleName());
36 }
37
38 @RequestMapping("/helloVal/{name}")
39 public String helloVal(@PathVariable(value = "name") String name, Model model) {
40 // http://localhost:8081/spring-mvc-html-0.1.0/helloVal/asd
41 logger.info("helloVal with " + name);
42 model.addAttribute("name", name); // set data in model
43 return configx.getViewList().get(0); // view JSP
44 }
45
46 @RequestMapping(value = "/hello", produces = "application/json")
47 @ResponseBody
48 public String hellox(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
49 // http://localhost:8081/spring-mvc-html-0.1.0/hello?name=asdkkk
50 logger.info("hellox with " + name);
51 JsonObj jo = new JsonObj();
52 jo.setFieldX(name);
53 return new Gson().toJson(jo);
54 }
55 }