Grandle 의 기본 언어는 Groovy
LiveKit | The all-in-one Voice AI platform
Build, deploy, and scale realtime agents. Open source. Enterprise grade.
livekit.io
package com.koreait.servlet;
import java.io.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
// 서블릿이 최초 로딩될 때, 단 1회만 실행되는 초기화 메서드
// 이곳에는 db연동, 서버 등을 일회성메서드를 주로 넣음
public void init() {
message = "Hello World!";
}
// url 호출 --> client의 GET 요청을 처리하는 구간
// HttpServletRequest: 클라이언트 요청 정보를 담은 객체
// HttpServletResponse : 서버에서 클라이언트로 전달될 응답 정보를 담은 객체
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// response.setContentType("text/html");
// 한글 깨짐 방지 --> html의 charset=UTF-8
response.setContentType("text/html; charset=UTF-8");
// 실제 클래스 안에서 쓰이는 한글 깨짐 방지
response.setCharacterEncoding("UTF-8");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
// 서블릿이 폼캣 종료 또는 언로드시 호출
// 리소스 해제, 커넥션 풀 반환
public void destroy() {
}
}
*webapp 파일에서 controller 패키지 생성
** main / java / com.koreait.servlet / controller / MyController
package com.koreait.servlet.controller;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
// value --> "*.korea" : 이름에 관계 없이 .korea로 끝난는 모든 URL 매핑
// http://localhost:8080/servlet/controller/join.korea (get, post)
@WebServlet("*.korea")
public class MyController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyController() {}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
// get post 어느걸로 불리던 여기로 이동
protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
String command = uri.substring(contextPath.length());
// 전체주소
System.out.println(uri);
// root 파일을 알려줌
System.out.println(contextPath);
// 실제 내 리소스를 알려줌 --> routing해주면 됨
System.out.println(command);
if(command.equals("/controller/join.korea")){
System.out.println("✅ 회원가입 작업");
}else if(command.equals("/controller/login.korea")){
System.out.println("✅ 로그인 작업");
}else if(command.equals("/controller/info.korea")){
System.out.println("✅ 회원정보 작업");
}else if(command.equals("/controller/modify.korea")){
System.out.println("✅ 회원정보 수정작업");
}
}
}
* .ajax
http://localhost:8080/servlet/controller/*.ajax
ex) get / post 동일하게 진행
- regist.ajax
- userid, password ,age , gender 전달
- {"userid" : "전달한 값", "msg" : "가입되었습니다."}
-
- userid, password 전달
- {"userid" : "전달한 값", "msg" : "로그인되었습니다."}
- response.setContentType("application/json; charset=UTF8;");
- response.getWriter().write("{\"key\":\"Value\}");login.ajax
package com.koreait.servlet.controller;
/*
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("*.ajax")
public class AjaxController extends HttpServlet {
private static final long serialVersionUID = 1L;
public AjaxController() {}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
// get post 어느걸로 불리던 여기로 이동
protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("application/json; charset=UTF8;");
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
String command = uri.substring(contextPath.length());
String action = command.substring(command.lastIndexOf('/') + 1);
// 전체주소
System.out.println(uri);
// root 파일을 알려줌
System.out.println(contextPath);
// 실제 내 리소스를 알려줌 --> routing 해주면 됨
System.out.println(command);
System.out.println(action);
PrintWriter out = resp.getWriter();
String userid = req.getParameter("userid");
switch (action) {
case "regist.ajax":
String password = req.getParameter("password");
String age = req.getParameter("age");
String gender = req.getParameter("gender");
out.write(String.format(
"{\"userid\":\"%s\",\"msg\":\"가입되었습니다.\"}",
userid
));
break;
case "login.ajax":
String userpw = req.getParameter("password");
out.write(String.format(
"{\"userid\":\"%s\",\"msg\":\"로그인되었습니다.\"}",
userid
));
break;
}
out.flush();
}
}
*/
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("*.ajax")
public class AjaxController extends HttpServlet {
private static final long serialVersionUID = 1L;
public AjaxController() {}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doAction(req, resp);
}
protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
String command = uri.substring(contextPath.length());
System.out.println(req.getParameter("userid"));
System.out.println(req.getParameter("password"));
String userid = req.getParameter("userid");
String password = req.getParameter("password");
String age = req.getParameter("age");
String gender = req.getParameter("gender");
if(command.equals("/controller/regist.ajax")) {
resp.setContentType("application/json; charset=UTF8;");
resp.getWriter().write("{\"userid\":\"" + userid +"\", \"msg\":\"가입되었습니다.\"}");
}else if(command.equals("/controller/login.ajax")) {
resp.setContentType("application/json; charset=UTF8;");
resp.getWriter().write("{\"userid\":\"" + userid +"\", \"msg\":\"로그인되었습니다.\"}");
}
}
}
<%--
ajax.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax</title>
<script>
function ajaxRegist(){
const userid = document.querySelector("input[name='userid']").value
const password = document.querySelector("input[name='password']").value
const age = document.querySelector("input[name='age']").value
const gender = document.querySelector("input[name='gender']:checked")?.value
fetch("regist.ajax", {
method: "POST",
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
body: "userid=" + userid + "&password=" + password + "&age=" + age + "&gender=" + gender
}).then(function(response){
return response.json()
}).then(function(data){
console.log((data))
}).catch(function(err){
console.log(err);
})
}
function ajaxLogin(){
const userid = document.querySelector("input[name='userid']").value
const password = document.querySelector("input[name='password']").value
fetch("login.ajax", {
method: "POST",
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
body: "userid=" + userid + "&password=" + password
}).then(function(response){
return response.json()
}).then(function(data){
console.log((data))
}).catch(function(err){
console.log(err);
})
}
</script>
</head>
<body>
<p>아이디: <input type="text" name="userid"></p>
<p>비밀번호: <input type="password" name="password"></p>
<p>나이: <input type="text" name="age"></p>
<p>성별: 남:<input type="radio" name="gender" value="남자"> 여:<input type="radio" name="gender" value="여자"></p>
<p><button type="button" onclick="ajaxRegist()">AJAX 회원가입</button></p>
<p><button type="button" onclick="ajaxLogin()">AJAX 로그인</button></p>
</body>
</html>
'Backend > Servlet' 카테고리의 다른 글
MVC2 (0) | 2025.06.12 |
---|---|
Tomcat9 (0) | 2025.06.10 |
Session & Servlet api (0) | 2025.06.05 |
Maven 프로젝트 (0) | 2025.06.04 |
Servlet _ Apache Tomcat _ Install (0) | 2025.06.02 |