๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์Šคํ”„๋ง Spring/๐Ÿงถ ์Šคํ”„๋ง ํ”„๋ ˆ์ž„์›Œํฌ Spring

ajax์™€ @ResponseBody

by Meteora_ 2021. 6. 22.
728x90

์ข‹์•„์š” ajax

 

<form id="like_form" >
											
       	<%-- <col width="50px"><col width="20px"> --%>


        <img style=" width: 50px; height: 50px; " alt = "" src = "./images/like.png" onclick="return like()">


        <div id="like_result" style="font-size: 15px;">${dto.like}๋ช…์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค.</div>

        <input type="hidden" name="seq" value="${dto.seq}">

											
											</form>

 

ajax ->

 

<script type="text/javascript">
      function like(){
      $.ajax({
      url: "likeController",
      type: "POST",
      cache: false,
      dataType: "json",
      data: $('#like_form').serialize(), //์•„์ด๋””๊ฐ€ like_form์ธ ๊ณณ์˜ ๋ชจ๋“  ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์™€ ํŒŒ๋ผ๋ฏธํ„ฐ ์ „์†ก ํ˜•ํƒœ(ํ‘œ์ค€ ์ฟผ๋ฆฌํ˜•ํƒœ)๋กœ ๋งŒ๋“ค์–ด์คŒ
      success:
      function(data){ //ajaxํ†ต์‹  ์„ฑ๊ณต์‹œ ๋„˜์–ด์˜ค๋Š” ๋ฐ์ดํ„ฐ ํ†ต์งธ ์ด๋ฆ„ =data
      // data์ค‘ putํ•œ ๊ฒƒ์˜ ์ด๋ฆ„ like
      $("#like_result").html(data.like +"๋ช…์ด ์ข‹์•„ํ•ฉ๋‹ˆ๋‹ค."); //id๊ฐ’์ด like_result์ธ html์„ ์ฐพ์•„์„œ data.like๊ฐ’์œผ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.
      },
      error:
      function (request, status, error){
      alert("ajax์‹คํŒจ")
      }
      });
      }

 

 

package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.MustEatDao;


import net.sf.json.JSONObject;

@WebServlet("/likeController")
public class LikeController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doProcess(req, resp);
	}
	
	protected void doProcess(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int seq = Integer.parseInt(req.getParameter("seq"));
		
		MustEatDao dao = MustEatDao.getInstance();
		dao.updatelike(seq);
		
		int like = dao.selectlike(seq);
		System.out.println("์ข‹์•„์š” ๊ฐœ์ˆ˜ = " + like);
		
		JSONObject obj = new JSONObject();
		obj.put("like", like);
		
		resp.setContentType("application/x-json; charset=UTF-8");
		resp.getWriter().print(obj);
		
	}

project // sample5ajax

 

pom.xml

 

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sample5ajax</groupId>
  <artifactId>sample5ajax</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>15</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
  
  <dependencies>
			<dependency>
			    <groupId>org.springframework</groupId>
			    <artifactId>spring-webmvc</artifactId>
			    <version>5.3.3</version>
			</dependency>
			<dependency>
			    <groupId>log4j</groupId>
			    <artifactId>log4j</artifactId>
			    <version>1.2.17</version>
			</dependency>
			
			<dependency>
			    <groupId>org.slf4j</groupId>
			    <artifactId>slf4j-simple</artifactId>
			    <version>1.7.25</version>
			    
			</dependency>
			
					<!-- Java์šฉ json ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ(XML/YAM/CSV) data-processing ํˆด -->
		  	<dependency>
			    <groupId>com.fasterxml.jackson.core</groupId>
			    <artifactId>jackson-core</artifactId>
			    <version>2.10.1</version>
			</dependency>
			
			<dependency>
			    <groupId>com.fasterxml.jackson.core</groupId>
			    <artifactId>jackson-databind</artifactId>
			    <version>2.10.1</version>
			</dependency>
				
			
</dependencies>  
  
  
</project>

 

servlet-context.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"
	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/>
	
	<!-- viewResolver ์„ค์ •(์‚ฌ์šฉ์ž์˜ view์˜ ์œ„์น˜, ํ™•์žฅ์ž๋ช…) -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>	<!-- views์˜ ๊ฒฝ๋กœ -->
		<property name="suffix" value=".jsp"></property>			<!-- ํ™•์žฅ์ž ๋ช… -->	
	</bean>

	<!-- 
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.prefix = "/WEB-INF/views/";
		viewResolver.suffix = ".jsp";
	 -->
	 
	 <!-- java ๊ณตํ†ต ํŒจํ‚ค์ง€ -->
	 <context:component-scan base-package="bit.com.a"/>
	 
	 <!-- Ajax ์ฃผ์„๋ฌธ์„ ์‚ฌ์šฉํ—ˆ๊ฐ€ -->
	 <mvc:annotation-driven/>
	 
	 <!-- spring์—์„œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์—†๋Š” ์š”์ฒญ์€ tomcat์— ์œ„์ž„ -->
	 <mvc:default-servlet-handler/>

</beans>

bit.com.a -> HelloController

 

package bit.com.a;

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

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

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

@Controller
public class HelloController {
	private static Logger logger = LoggerFactory.getLogger(HelloController.class);
	
	
	//1๋ฒˆ
	@RequestMapping(value="hello.do", method = RequestMethod.GET)
	public String hello(Model model) {
		
		logger.info("HelloController hello()" + new Date());
		
		MyClass cls = new MyClass(1234, "์ฃผ์ง€ํ›ˆ");
		
		model.addAttribute("mycls", cls);//์ง์‹ธ
		
		
		return "hello";
	
	
	
	}
	//2๋ฒˆ ๋ทฐ์—์„œ ์ปจํŠธ๋กค๋Ÿฌ ์ „์†ก๋ฐ›์Œ
	@RequestMapping(value="move.do", method = { RequestMethod.GET,RequestMethod.POST})
	public String move(Model model, MyClass mycls) {
		
		logger.info("HelloController move()" + new Date());
		
		
		model.addAttribute("mycls", mycls);
		System.out.println(mycls.toString());
		
		return "hello";
		
	}
	
	//3๋ฒˆ ajax
	@ResponseBody  //ajax ์‚ฌ์šฉ์‹œ ๋ฐ˜๋“œ์‹œ ์‚ฌ์šฉ
	@RequestMapping(value="idcheck.do", method = { RequestMethod.GET,RequestMethod.POST},
					produces = "application/String; charset=utf-8")
	//ํ•œ๊ตญ๋ง๋‚˜์˜ค๋ ค๋ฉด ํ”„๋กœ๋•์Šค
	
	public String idcheck(String id) {
		logger.info("HelloController idcheck()" + new Date());
		
		System.out.println("id="+id);
		
		String str = "์˜ค์ผ€์ด";
		
		return str;
		
	}
	
	
	//4๋ฒˆ JSON
	@ResponseBody
	@RequestMapping(value="account.do", method = { RequestMethod.GET,RequestMethod.POST})
	public Map<String, Object> account(Human h){
	//Map<String, Object> attributeํ˜•ํƒœ๋ผ๊ณ  ์ƒ๊ฐ
	
		logger.info("HelloController account()" + new Date());
	
	
		System.out.println(h.toString());
		//DB์ ‘๊ทผ
		
		//๋‚ ๋ ค์ค„๊ฑฐ ์ค€๋น„
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("message", "๋‚ด๊ฐ€๋ณด๋‚ธ ๋ฉ”์„ธ์ง€์ž…๋‹ˆ๋‹ค");
		map.put("name", "์†ก์ค‘๊ธฐ");
		
		return map;
	
	}
	
	//5๋ฒˆ JSON ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ›๊ธฐ
		@ResponseBody
		@RequestMapping(value="read.do", method = { RequestMethod.GET,RequestMethod.POST})
		public List<MyClass> list(){
		//Map<String, Object> attributeํ˜•ํƒœ๋ผ๊ณ  ์ƒ๊ฐ
		
			logger.info("HelloController list()" + new Date());
		
			System.out.println("list");
			
			//DB์ ‘๊ทผ
			
			//๋‚ ๋ ค์ค„๊ฑฐ ์ค€๋น„
			List<MyClass> list = new ArrayList<MyClass>();
			list.add(new MyClass(456, "์›๋นˆ"));
			list.add(new MyClass(456, "๊ฐ•๋™์›"));
			
			return list;
		
		}
	
	
	
}//class end

views / hello.jsp

 

<%@page import="bit.com.a.dto.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://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>


<!-- 1 ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ๋ทฐ๋กœ ์งํ’€๊ธฐ-->
<%
	MyClass cls = (MyClass)request.getAttribute("mycls");

%>

๋ฒˆํ˜ธ:<%=cls.getNumber() %>
์ด๋ฆ„:<%=cls.getName() %>

<br>
number:${mycls.number }<br>
name:${mycls.name }<br>
<br>

<!--2 ๋ทฐ์—์„œ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ์ด๋™ํ•  ๊ฒฝ์šฐ  -->
<form action="move.do" method="post">
๋ฒˆํ˜ธ:<input type="text" name = "number" size="20">
์ด๋ฆ„:<input type="text" name = "name" size="20">
<input type="submit" value="์ด๋™">


</form>
<br><br>
<!--3 ajax id ์ „์†ก -->

<h3>3. ajax</h3>


์•„์ด๋””:<input type="text" id="checkid">
<br><br>
<button type="button" onclick="idcheck()">์•„์ด๋””์ฒดํฌ</button>

<script type="text/javascript">

function idcheck() {
	$.ajax({
		
		url:"idcheck.do",
		type:"get",
		//data:"id="+$("#checkid").val(),
		
		//JSON ํ˜•์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด๋‚ธ๋‹ค
		data:{id:$("#checkid").val()},
		
		success:function(data){
			//alert("success");
			alert(data);
			
		},
		error:function(){
			alert("error");
		}
	});
}




</script>



<br><br>
<!--4 
 json - > object(controller)
 map(controller) -> json(web)

-->
<h3>4. json</h3>

์ด๋ฆ„:<input type="text" id="name" value="์†ก์ค‘๊ธฐ"><br>
์ „ํ™”:<input type="text" id="phone" value="010-456"><br>
์ด๋ฉ”์ผ:<input type="text" id="email" value="vivi@na"><br>
์ƒ๋…„์›”์ผ:<input type="text" id="birth" value="1997/11/14"><br>

<button type="button" id="account">ํšŒ์›๊ฐ€์ž…</button>


<script type="text/javascript">

$("#account").click(function(){
	
	alert("click");
	//JSONํ˜•์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด๋‚ธ๋‹ค
	var human={
			name:$("#name").val(),
			phone:$("#phone").val(),
			email:$("#email").val(),
			birth:$("#birth").val()
			
	};
	
	
		$.ajax({
				
				url:"account.do",
				type:"post",
				dataType:"json",
				data:human,
				async:true,//๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์ด๋‹ค
				
				success:function(data){
					//alert("success");
					alert(data.message);
					alert(data.name);
					alert(data);//๊ทธ๋ƒฅ์ฐ์œผ๋ฉด ์˜ค๋ธŒ์ ํŠธ๋กœ ๋„˜์–ด์˜จ๋‹ค
					
					alert(JSON.stringify(data)); //json-> String // string -> json : JSON.parse()
					
					
				},
				error:function(){
					alert("error");
				}
			});
	
	
	
});





</script>

<h3>5. data read(list)</h3>
<div id="datas">
</div>

<button type="button" onclick="read()">๋ฆฌ์ŠคํŠธ์ถœ๋ ฅ</button>
<script type="text/javascript">
function read(){
	
	alert("read");
	$.ajax({
			
			url:"read.do",
			type:"post",
			async:true,//๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ์ด๋‹ค
			
			success:function(data){
				alert("success");
				
				
				var str = '';
				$.each(data, function(i, item){
					str += item.number;
					str += item.name + "<br>";
					
					
				});
				
				$("#datas").html(str);
				
				
			},
			error:function(){
				alert("error");
			}
		});
	
}

</script>

<h3>Hello.jsp</h3>

</body>
</html>

๋Œ“๊ธ€