본문 바로가기

Java/java 기초

Spring에서 Ajax활용하기

반응형

https://github.com/loy124/SpringStudy

 

loy124/SpringStudy

스프링 ajax 활용 및 Mybatis 예제. Contribute to loy124/SpringStudy development by creating an account on GitHub.

github.com

 

 

파일 시스템 구조

spring에서 ajax를 사용하려면

spring -> servlet-context(DispatcherServlet)에서 값을 추가해줘야한다.

 

	<!-- 사용자지정 -->
	<!-- java의 공통 패키지 -->
	<context:component-scan base-package="bit.com.a"/>
	
	<!-- Ajax 주석문 허가 -->
	<mvc:annotation-driven/>
	<!-- 스프링에서 처리할 수 없는 요청은 tomcat에 위임 -->
	<mvc:default-servlet-handler/>

 

추가시

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">

	<!-- Spring MVC annotation(주석문)을 사용하기 위한 설정 -->
	<context:annotation-config/>
	
	<!-- xml 객체 생성 -->
	<!-- ViewResolver 설정(사용자의 view의 위치, 확장자명)-->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property> <!-- 경로 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 사용자지정 -->
	<!-- java의 공통 패키지 -->
	<context:component-scan base-package="bit.com.a"/>
	
	<!-- Ajax 주석문 허가 -->
	<mvc:annotation-driven/>
	<!-- 스프링에서 처리할 수 없는 요청은 tomcat에 위임 -->
	<mvc:default-servlet-handler/>

</beans>

 

 

또한 Ajax 통신시 

컨트롤러 부분에서 무조건 @ResponseBody를 사용해야 한다 

hello.jsp와 HelloController.jsp 1 - 1, 2파트는 2 로 연결시켜놓았다.

 

hello.jsp

<%@page import="bit.com.a.model.MyClass"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>

	<!-- 1 -->
	<%
		MyClass cls = (MyClass) request.getAttribute("myCls");
	%>
	number:<%=cls.getNumber()%><br> name:<%=cls.getName()%><br>

	<!--2 -->
	<br>
	<br> number:${myCls.number}
	<br> name: ${myCls.name }

	<!-- 3 -->
	<form>
		아이디:<input type="text" id="checkid"><br> <br>
		<button type="button" id="_check" onclick="idcheck()">id 체크</button>
	</form>

	<script>
		function idcheck() {
			alert("idCheck");

			$.ajax({
				url : "./idCheck.do",
				type : "get",
				data : "id=" + $("#checkid").val(),
				success : function(data) {
					alert("되요ㅋ");
					alert(data);
				},
				error : function() {
					alert("에러나요");
				}
			})
		}
	</script>

	<!-- 4 -->
	<form method="post">
		이름: <input type="text" id="_name" value="홍길동"><br> 전화: <input
			type="text" id="_phone" value="123-4567-789"><br> 이메일: <input
			type="text" id="_email" value="http200@kakao.com"><br>
		생년월일: <input type="text" id="_birth" value="2001/11/23"><br>
		<button type="button" id="account">account</button>
	</form>

	<script type="text/javascript">
		$("#account").click(function() {
			//alert("click");

			var human = {
				name : $("#_name").val(),
				tel : $("#_phone").val(),
				email : $("#_email").val(),
				birth : $("#_birth").val()
			};
			console.log(human);
			$.ajax({
				url : "./account.do",
				data : human,
				type : "post",
				dataType : "json",
				async : true,
				success : function(resp) {
					alert("success");
					alert(resp.msg);
					alert(resp.name);

				},
				error : function() {
					alert("error")
				}
			});
		});
	</script>

	<br>
	<br>
	<br>
	<!-- 5 -->

	이름:
	<input type="text" id="_name1" value="정수동">
	<br> 전화:
	<input type="text" id="_phone1" value="123-4567-589">
	<br> 이메일:
	<input type="text" id="_email1" value="http200@kakao.com">
	<br> 생년월일:
	<input type="text" id="_birth1" value="2001-11-21">
	<button type="button" id="account1">account</button>
	<br>

	<script>
		/* Json -> Map */

		$("#account1").on("click", function() {
			//alert("account1")
			var data = {};

			data["name"] = $("#_name1").val();
			data["tel"] = $("#_phone1").val();
			data["email"] = $("#_email1").val();

			var birth = $("#_birth1").val();
			data["birth"] = birth.replace(/-/g, "");
			//alert(data["birth"]);

			$.ajax({
				contentType : 'application/json',
				dataType : 'json',
				url : "updateUser.do",
				type : 'post',
				data : JSON.stringify(data), // json -> string <-> parse
				success : function(resp) {
					alert("success")
				},
				error : function() {
					alert("error");
				}
			});
		});
	</script>

</body>
</html>









 

 

HelloController.java

 

package bit.com.a;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import bit.com.a.model.Human;
import bit.com.a.model.MyClass;


@Controller
public class HelloController {
	
	private static Logger logger = LoggerFactory.getLogger(HelloController.class);
	
//	1
	@RequestMapping("hello.do")
	public String hello(Model model) {
		logger.info("HelloController hello" + new Date());
		
		MyClass cls = new MyClass(101, "일지매");
		model.addAttribute("myCls", cls);
		
		return "hello";
	}
	/* 2 controller -> controller */
	@RequestMapping(value="move.do", method = RequestMethod.GET)
	public String move() {
		logger.info("HelloController move " + new Date());
		
		//sendRedirect(컨트롤러에서 컨트롤러로 보낸다)
		return "redirect:/hello.do"; 
//		return "forward:/hello.do"; 데이터를 가져갈때는 forward
	}
	
//	3번
//	Ajax 용 return값은 ajax에서 가져오는 데이터 (넘겨줘야할 데이터)
	//Ajax사용시 @ResponseBody를 사용해야한다
	@ResponseBody
	@RequestMapping(value="idCheck.do", produces = "application/String; charset=utf-8")
	//적어주기만 하면 무조건 session에 넘어간다 (의존성)
	public String idCheck(String id, HttpSession session) {
		logger.info("HelloController idCheck " + new Date());
		logger.info("id:" + id);
		
		String str = "오케이";
		return str;	
	}
	
	
	//4
	@ResponseBody
	@RequestMapping(value="account.do" ,method = RequestMethod.POST)
	public  Map<String, Object> account(Human my){
		logger.info("HelloController account " + new Date());
		logger.info(my.toString());
		
		//DB 접근
		Map<String, Object> rmap = new HashMap<String, Object>();
		rmap.put("msg", "메시지입니다");
		rmap.put("name", "정수동");
		
		return rmap;
		
	}
	
    //5
	@ResponseBody
	@RequestMapping(value="updateUser.do", method = {RequestMethod.GET, RequestMethod.POST})
	//@RequestBody를 적어야 Map으로 값을 받아올 수 있다.
	public Map<String, Object> updateUser(@RequestBody Map<String, Object> map){
		logger.info("HelloController updateUser " + new Date());
		logger.info( map.get("name") + "");
		logger.info( map.get("tel") + "");
		logger.info( map.get("email") + "");
		logger.info( map.get("birth") + "");
		
		Map<String, Object> rmap = new HashMap<String, Object>();
		rmap.put("name", "일지매");
		rmap.put("age", "24");
		
		return rmap;
	}
	
	
	
}




 

 

반응형

'Java > java 기초' 카테고리의 다른 글

Mybatis 시작하기  (0) 2020.02.25
Spring 셋팅 설정  (0) 2020.02.24
JSP, JSTL(el, core), Ajax로 각각 만든 고객 목록 관리 리스트(MVC2)  (0) 2020.01.24
jsp tag  (0) 2020.01.23
Core tag  (0) 2020.01.23