Last Modified 2017.10.22

Simple Ajax Example on Spring MVC

Source : https://github.com/kimjonghoon/simpleAjaxExampleOnSpringMVC

Create webapp archetype

C:\ Command Prompt
mvn archetype:generate -Dfilter=maven-archetype-webapp
C:\ Command Prompt
Define value for property 'groupId': : net.java_school
Define value for property 'artifactId': : simpleAjaxExampleOnSpringMVC
Define value for property 'version':  1.0-SNAPSHOT: : 
Define value for property 'package':  net.java_school: : net.java_school.simpleAjaxExampleOnSpringMVC

Edit pom.xml as follows.

pom.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/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>net.java_school</groupId>
	<artifactId>simpleAjaxExampleOnSpringMVC</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>simpleAjaxExampleOnSpringMVC</name>
	<url>http://maven.apache.org</url>

	<properties>
		<jdk.version>1.8</jdk.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Servlet JSP JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.9.9</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.9</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.8.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.1.8.RELEASE</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>simpleAjaxExampleOnSpringMVC</finalName>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>2.6</version>
					<configuration>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.6.2</version>
					<configuration>
						<source>${jdk.version}</source>
						<target>${jdk.version}</target>
						<encoding>UTF-8</encoding>
					</configuration>
				</plugin>
				<plugin>
					<groupId>org.eclipse.jetty</groupId>
					<artifactId>jetty-maven-plugin</artifactId>
					<version>9.4.7.v20170914</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>

</project>

Create Model

Post.java
package net.java_school.blog;

public class Post {
    private String title;
    private String keywords;
    private String description;
    private String content;
    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getKeywords() {
        return keywords;
    }
    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

Create Controller

BlogController.java
package net.java_school.blog;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BlogController {

	@RequestMapping(method=RequestMethod.GET)
	public String home() {
		return "index";
	}
	
	@RequestMapping(value="java", method=RequestMethod.GET)
	public String javaIndex() {
		return "java/index";
	}

	@RequestMapping(value="java/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Post getPost(@PathVariable String id) {
		Post post = new Post();

		switch (id) {
		case "jdk-install":
			post.setTitle("Java Install");
			post.setKeywords("JDK,Java 8");
			post.setDescription("This article covers Install Java 8");
			post.setContent("visit http://www.oracle.com...");
			break;
		default:
			post.setTitle("No such document.");
			post.setKeywords("No such document.");
			post.setDescription("No such document.");
			post.setContent("No such document.");
		}

		return post;
	}

}

Create JSP

/WEB-INF/views/index.jsp
<html>
<body>
<h2>Hello World!</h2>
<a href="/java">Go to Java Tutorial</a>
</body>
</html>
/WEB-INF/views/java/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="Keywords" content="keywords" />
<meta name="Description" content="description" />
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<script type="text/javascript">
$(document).ready(function() {
    $('#jdk-install a').click(function() {
        var url = '/java/jdk-install';
        $.getJSON(url, function(data) {
            $('title').empty();
            $('title').append(data.title);
            $("meta[name='Keywords']").attr("content", data.keywords);
            $("meta[name='Description']").attr("content", data.description);
            $('article').empty();
            $('article').append(data.content);
            console.log(data);            
            console.log($("meta[name='Keywords']").attr("content"));
            console.log($("meta[name='Description']").attr("content"));
        });
        return false;
    });
});
</script>
</head>
<body>

<ul>
	<li id="home"><a href="/">Home</a></li>
    <li id="jdk-install"><a href="#">JDK Install</a></li>
</ul>

<article>
content
</article>

</body></html>

Edit web.xml as follows.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">
  
  <display-name>Simple Ajax Example On Spring MVC</display-name>
    
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
      <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
        
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
    
  <servlet>
    <servlet-name>ajaxexample</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
    
  <servlet-mapping>
    <servlet-name>ajaxexample</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 
</web-app>

Create ajaxexample-servlet.xml as follows.

ajaxexample-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
		 http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
	<mvc:annotation-driven />
        
	<context:component-scan base-package="net.java_school.blog" />
            
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>/WEB-INF/views/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
    
</beans>

Test

Go to the root directory and run mvn jetty:run and visit http://localhost:8080.

Home
Java Index
JDK Install