jspblog : ajax test

This commit is contained in:
kim
2021-01-20 16:42:37 +09:00
parent 8b3ff7935d
commit 163bedea4d
4 changed files with 99 additions and 0 deletions

View File

@@ -49,6 +49,11 @@
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
<build>

View File

@@ -0,0 +1,33 @@
package com.example.jspblog.test;
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 java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/ajax1")
public class Ajax1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String jsonData = "{\"username\":\"kim\", \"password\":\"1234\"}";
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print(jsonData);
out.flush();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
out.print("ok");
out.flush();
}
}

View File

@@ -0,0 +1,30 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
</head>
<body>
<button onclick="getAjax()">클릭</button>
<script>
function getAjax() {
$.ajax({
type: "GET", // 요청 메소드
url: "http://localhost:8080/jspblog/ajax1?username=kim&password=1234", // 전송할 url
// get은 data, contentType 필요 X
dataType: "text" // 응답의 data type
})
.done(function (result){
})
.fail(function (error) {
});
}
</script>
</body>
</html>

View File

@@ -0,0 +1,31 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
</head>
<body>
<button onclick="postAjax()">클릭</button>
<script>
function postAjax() {
$.ajax({
type: "POST",
url: "http://localhost:8080/jspblog/ajax1",
data:"username=kim&password=1234",
contentType:"application/x-www-form-urlencoded",
// dataType: "json"
})
.done(function (result){
console.log(result);
})
.fail(function (error) {
});
}
</script>
</body>
</html>