Last Modified 2024.3.3
스프링 MVC에서 동작하는 간단한 에이잭스 예제
예제 소스 : https://github.com/kimjonghoon/simpleAjaxExampleOnSpringMVC
아키타입 생성 과정과 소스 설명
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
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> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>simpleAjaxExampleOnSpringMVC Maven Webapp</name> <url>http://www.java_school.net</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <spring.version>5.3.33</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- Servlet JSP JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</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.16.1</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.16.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies> <build> <finalName>simpleAjaxExampleOnSpringMVC</finalName> <pluginManagement> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> <configuration> <failOnMissionWebXml>false</failOnMissionWebXml> </configuration> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>10.0.20</version> </plugin> </plugins> </pluginManagement> </build> </project>
모델
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; } }
컨트롤러
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("자바 설치"); post.setKeywords("JDK,Java 8"); post.setDescription("자바 8 설치에 대해 설명합니다."); post.setContent("http://www.oracle.com을 방문합니다. .."); break; default: post.setTitle("해당 문서가 없습니다."); post.setKeywords("해당 문서가 없습니다."); post.setDescription("해당 문서가 없습니다."); post.setContent("해당 문서가 없습니다."); } return post; } }
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> <head> <meta charset="UTF-8" /> <meta name="Keywords" content="keywords" /> <meta name="Description" content="description" /> <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="/">홈</a></li> <li id="jdk-install"><a href="#">JDK 설치</a></li> </ul> <article> 본문 </article> </body></html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <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>
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>
테스트
pom.xml이 있는 디렉터리에서 mvn jetty:run을 실행한 후, http://localhost:8080을 방문한다.