handler, response, json

2024. 2. 16. 17:51Daily Codig Reminder

URLMapping

 

@Controller
public class TestController {
	@RequestMapping(value = "/", method = RequestMethod.GET )//get, post 둘다 처리
	public String main() {//servlet과 동일
		return "main";//응답요청을 할 jsp 파일이름 test.jsp
	}
	@RequestMapping(value="/aaa", method=RequestMethod.GET)
	public String aaa() {
		System.out.println("aaa 호출");
		return "main";
	}
	// aaa2, aaa3 둘다 같은 페이지 호출
	@RequestMapping(value= {"/aaa2", "/aaa3"}, method=RequestMethod.GET)
	public String aaa2() {
		System.out.println("aaa2 호출");
		return "main";
	}
	// 앞에 bbb만 맞으면 호출
	@RequestMapping(value= "/bbb*", method=RequestMethod.GET)
	public String aaa3() {
		System.out.println("aaa3 호출");
		return "main";
	}
	//4. * 은 라나의 문자열임  ccc/bbb 가능  ccc/bbb/xxx 안됨
	@RequestMapping(value= "/ccc/*", method=RequestMethod.GET)
	public String aaa4() {
		System.out.println("aaa4 호출");
		return "main";
	}
	//5.  ** 는 여러경로 가능 ddd/zzz, ddd/zzz/aaa 가능
	@RequestMapping(value= "/ddd/**", method=RequestMethod.GET)
	public String aaa5() {
		System.out.println("aaa5 호출");
		return "main";
	}
	//6. ** 는 여려경로가능 eee/kk/bbb/aaa
	@RequestMapping(value= "/eee/**/aaa", method=RequestMethod.GET)
	public String aaa6() {
		System.out.println("aaa6 호출");
		return "main";
	}
	//7. 중요!!!!!!!!!! hhh/abcd/xxx/1234 http://8077/app/hhh/tester/xxx/1234
	//특정주소를 데이터로 뽑아서 사용 가능
	@RequestMapping(value= "/hhh/{userid}/xxx/{passwd}", method=RequestMethod.GET)
	public String aaa7(@PathVariable("userid") String userid, 
			@PathVariable("passwd") String passwd) {
		System.out.println("aaa7 호출=====");
		System.out.println(userid+"\t"+passwd);
		//http://localhost:8015/userapp/hhh/abcd/xxx/1111
		//aaa7 호출=====
		//abcd	1111
		return "main";
	}
	@RequestMapping(value= "/ggg", method=RequestMethod.GET)
	public String ggg(@RequestParam String id) {
		System.out.println("ggg 호출=====");
		System.out.println(id);
		return "main";
}
	@RequestMapping(value= "/ggg2", method=RequestMethod.GET)
	public String ggg2( String id) {// 필수 아님 ?id=
		System.out.println("ggg 호출=====");
		System.out.println(id);
		//ggg 호출=====
		//1111
		
		return "main";
}
}

 

 

Redirect_forward

@Controller
public class TestController {
//	@RequestMapping(value="/main", method=RequestMethod.GET)
//	public String main(Model m) {
//		System.out.println("main====");
//		m.addAttribute("userid","홍길동");
//		m.addAttribute("passwd", "1234");
//		return "main";
//	}
	@RequestMapping(value="/main", method=RequestMethod.GET)
	public String main() {
		System.out.println("main====");
		return "main";
	}
	//1. redirect시 request.getParameter("userid") 파라미터로 데이터 전송됨 setattribute 사용안됨
	@RequestMapping(value="/redirect", method=RequestMethod.GET)
	public String redirect(Model m , HttpServletRequest request) {
		System.out.println("redirect====");
		m.addAttribute("userid","홍길동");//redirect 시 주소에 parameter 로 전달 model 만
		m.addAttribute("passwd","1234");//redirect 시 주소에 parameter 로 전달 model 만
		request.setAttribute("passwd", "1234");//전달되지않음
	//	return "redirect:main";//main으로 redirect
		return "redirect:main?userid=aaa";
		//request.getParameter 로 뽑힘
	}
	//2. forward
		@RequestMapping(value="/forward", method=RequestMethod.GET)
		public String forward(Model m , HttpServletRequest request) {
			System.out.println("forward====");
			m.addAttribute("userid","홍길동");//redirect 시 주소에 parameter 로 전달 model 만
			request.setAttribute("passwd", "1234");//전달되지않음
			return "forward:main";
			// request.getAttribute 로 뽑힘
		}
}

 

 

1. : ${userid }<br>
1. request.getAttribute : <%= request.getAttribute("userid") %><br>
2. <%= request.getAttribute("passwd") %><br>
3. request.getParameter : <%= request.getParameter("userid") %><br>
3. request.getParameter : <%= request.getParameter("passwd") %><br>

 

http://localhost:8015/userapp/main?userid=aaa&userid=홍길동&passwd=1234

//redirect

 

//forward

 

@RequestMapping(value="/main", method=RequestMethod.GET)
	public String main() {
		System.out.println("main====");
		return "main";
	}
	//1. redirect-flash<mvc:annotation-driven/> 필요함
	@RequestMapping(value="/flash", method=RequestMethod.GET)
	public String redirect(RedirectAttributes m) {
		System.out.println("redirectflash====");
		m.addAttribute("userid","홍길동");//redirect 시 주소에 parameter 로 전달 model 만
		m.addAttribute("passwd","1234");//redirect 시 주소에 parameter 로 전달 model 만
		return "redirect:main?userid=aaa";
	}
	//2. forward
		@RequestMapping(value="/forward", method=RequestMethod.GET)
		public String forward(Model m , HttpServletRequest request) {
			System.out.println("forward====");
			m.addAttribute("userid","홍길동");//redirect 시 주소에 parameter 로 전달 model 만
			request.setAttribute("passwd", "1234");//전달되지않음
			return "forward:main";
			// request.getAttribute 로 뽑힘
		}

 

 

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

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven /> <!-- RedirectAttributets 사용 시 필수! -->

    <!-- Handles HTTP GET requests for /resources/ by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.controller" />



</beans:beans>

 

 

HandlerInterceptorAdapter

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	throws Exception{
		System.out.println("prehandler===");
		return true; //true 계속 진행
		//return false; 진행금지
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler, ModelAndView modelAndView)
	throws Exception{
		System.out.println("posthandler===");
	}

 

 

xml

<beans:bean class="com.intercpetor.MyHandlerInterceptor" id="myInterceptor"></beans:bean>
	<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
	<beans:property name="interceptors">
	<beans:list>
	<beans:ref bean="myInterceptor"/>
	</beans:list>
	</beans:property>
	</beans:bean>

true→

prehandler===

main====

posthandler===

 

false→

prehandler===

loginForm 에 저장안됐을 시에 loginForm 으로 감

session에 저장이 되면 main과 home 에 login정보가 저장이 되고

logined 에 출력이 됨

 

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	// home: session 로그인 정보 있으면 main.jsp
	// 로그인 정보가 없는 경우 loginForm.jsp
	@RequestMapping(value="/home" , method= RequestMethod.GET)
	public String home() {//인터셉터 처리
		System.out.println("Homecontroller.main호출");
		return "main";
	}
	@RequestMapping(value="/home/user1" , method= RequestMethod.GET)
	public String user1() {//인터셉터 처리
		System.out.println("Homecontroller.main user1호출");
		return "main";
	}
	@RequestMapping(value="/home/user2" , method= RequestMethod.GET)
	public String user2() {//인터셉터 처리
		System.out.println("Homecontroller.main user2호출");
		return "main";
	}
}

 

 

@Controller
public class TestController {
	@RequestMapping(value="/main" , method= RequestMethod.GET)
	public String main() {//인터셉터 처리
		System.out.println("Testcontroller.main호출");
		return "main";
	}
	@RequestMapping(value="/loginForm" , method= RequestMethod.GET)
	public String loginForm() {//인터셉터 처리
		System.out.println("Testcontroller.loginForm호출");
		return "loginForm";
	}
	@RequestMapping(value="/login" , method= RequestMethod.POST)
	public ModelAndView login(String userid, String passwd, HttpSession session) {//인터셉터 처리
		System.out.println("Testcontroller.loginForm호출");
		session.setAttribute("login", userid);
		ModelAndView mav = new ModelAndView();
		mav.addObject("userid", userid);
		mav.addObject("passwd", passwd);
		mav.setViewName("logined");

		return mav;
	}
}

 

 

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	throws Exception{
		System.out.println("prehandler==="+handler);
		HttpSession session = request.getSession();
		if (session.getAttribute("login")==null) {
			System.out.println("interceptor session 정보 없음===");
			response.sendRedirect("/app/loginForm");//servlet-context.xml ㅇ서 /main /home 만 처리하도록 설정
		}
		return true; //true 계속 진행
		//return false; //진행금지
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler, ModelAndView modelAndView)
	throws Exception{
		System.out.println("posthandler===");
	}
	
	
}

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean class="com.controller.TestController" id="xxx"></beans:bean>
	<beans:bean class="com.user.app.HomeController" id="yyy"></beans:bean>
	<beans:bean class="com.intercpetor.MyHandlerInterceptor" id="myInterceptor"></beans:bean>
	
	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	  <interceptors>
	<interceptor>
	<mapping path="/main/**"/>
	<beans:ref bean ="myInterceptor"/>
	</interceptor>
	<interceptor>
	<mapping path="/home/**"/>
	<beans:ref bean="myInterceptor"/>
	</interceptor>
	</interceptors>
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
<!--  	<context:component-scan base-package="com.user.app" />
	-->
	
</beans:beans>

 

 

interceptor session 정보 없음===
Homecontroller.main호출
posthandler===
Testcontroller.loginForm호출
prehandler===public java.lang.String cohttp://m.user.app.HomeController.home()
interceptor session 정보 없음===
Homecontroller.main호출
posthandler===
Testcontroller.loginForm호출
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/app/home/uesr1] in DispatcherServlet with name 'appServlet'
prehandler===public java.lang.String cohttp://m.user.app.HomeController.user1()
interceptor session 정보 없음===
Homecontroller.main user1호출
posthandler===
Testcontroller.loginForm호출

 

 

 

 

namespace_resouce

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
//@RequestMapping("/main")
//public String main1() {
//	return "main";
//	//controller에서 주소처리가 아닌 servlet-context.xml 주소 처리 등록 /main=> main.jsp 응답
//}
@RequestMapping("/")
public String ttt() {
	return "home";
	//controller에서 주소처리가 아닌 servlet-context.xml 주소 처리 등록 /main=> main.jsp 응답
}
}

 

 

xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean class="com.controller.TestController" id="xxx"></beans:bean>
	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
<view-controller  path="/main" view-name="test"/>
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/image/**" location="/WEB-INF/image/" />
	<resources mapping="/img/**" location="/WEB-INF/img/" />
	<resources mapping="/css/**" location="/WEB-INF/css/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.user.app" />

</beans:beans>

 

 

<%@ 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>
<link rel = "stylesheet" href="css/test.css" type="text/css">
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<h1>main</h1>
<h2>css 속성테스트</h2>
<img alt="" src="image/a.jpg" width="100" height="100"><br>
<img alt="" src="../image/a.jpg" width="100" height="100">
</body>
</html>

다른방법

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<beans:bean class="com.controller.TestController" id="xxx"></beans:bean>
	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
<view-controller  path="/main" view-name="test"/>
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<!-- <resources mapping="/image/**" location="/WEB-INF/image/" />
	<resources mapping="/img/**" location="/WEB-INF/img/" />
	<resources mapping="/css/**" location="/WEB-INF/css/" />
 -->
 <resources mapping="/resources/**" location="/resources/img/" />
 <resources mapping="/resources/**" location="/resources/css/" />
 <resources mapping="/resources/**" location="/resources/js/" />
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.user.app" />

</beans:beans>

 

 

 

JSON -비동기처리

<!-- JSON/Ajax start -->
    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.8</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.8.8</version>
</dependency>
        <!-- JSON/Ajax end -->

@RequestMapping("/eee")
	public String eee(LoginDTO dto) {
		System.out.println("eee===="+dto.getUserid()+"\t"+dto.getPasswd());
		
		return "hello";
	}

eee====홍길동 1234

 

@RequestMapping("/ccc")
	public String ccc(String userid, String passwd) {
		System.out.println("eee===="+userid+"\t"+passwd);
		
		return "hello";
	}

ccc====홍길동 1234

 

@RequestMapping("/ddd")
	public String ddd(String userid) {
		System.out.println("ddd===="+userid);
		
		return "hello";
	}

ddd====홍길동

 

@RequestMapping("/aaa")
	public String aaa(@RequestBody LoginDTO login) {
	//body 에 숨겨온 json ㄷ이터
		System.out.println("aaa===="+login);
		
		return "hello";
	}

aaa====LoginDTO [userid=홍길동, passwd=1234]

 

@RequestMapping("/bbb")
	public String bbb(@RequestBody ArrayList<LoginDTO> list) {
	//body 에 숨겨온 json ㄷ이터
		System.out.println("bbb===="+list);
		
		return "hello";
	}

bbb====[LoginDTO [userid=홍길동, passwd=null], LoginDTO [userid=null, passwd=1234]]

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>main</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#ddd").on("click", function() {
        // AJAX 요청
        $.ajax({
            type: "post",
            url: "ddd", // 서버의 엔드포인트 URL로 변경해야 합니다.
           dataType: "text",
            data: {userid:"홍길동"},
            success: function(data, status, xhr) {
                console.log(data);                
            },
            error: function(xhr, status, error) {
            	console.log(error);
            }
        });
    });
    
    $("#eee").on("click", function() {
        // AJAX 요청
        $.ajax({
            type: "post",
            url: "eee", // 서버의 엔드포인트 URL로 변경해야 합니다.
           dataType: "text",
            data: {userid:"홍길동", passwd:"1234"},
            success: function(data, status, xhr) {
                console.log(data);    //success            
            },
            error: function(xhr, status, error) {
            	console.log(error);
            }
        });
    });
    $("#ccc").on("click", function() {
        // AJAX 요청
        $.ajax({
            type: "post",
            url: "ccc", // 서버의 엔드포인트 URL로 변경해야 합니다.
           dataType: "text",
            data: {userid:"홍길동", passwd:"1234"},
            success: function(data, status, xhr) {
                console.log(data);    //success            
            },
            error: function(xhr, status, error) {
            	console.log(error);
            }
        });
    });
    $("#aaa").on("click", function() {
        // AJAX 요청
        $.ajax({
            type: "post",
            url: "aaa", // 서버의 엔드포인트 URL로 변경해야 합니다.
           dataType: "text",
           headers: {
        	   "Content-Type":"application/json"
           },
            data: JSON.stringify({userid:"홍길동", passwd:"1234"}),
            success: function(data, status, xhr) {
                console.log(data);    //success            
            },
            error: function(xhr, status, error) {
            	console.log(error);
            }
        });
    });
    $("#bbb").on("click", function() {
        // AJAX 요청
        $.ajax({
            type: "post",
            url: "bbb", // 서버의 엔드포인트 URL로 변경해야 합니다.
           dataType: "text",
           headers: {
        	   "Content-Type":"application/json"
           },
            data: JSON.stringify(
            		[
            	{userid:"홍길동"}, 
            	{passwd:"1234"}
            	]
            ),
            success: function(data, status, xhr) {
                console.log(data);    //success            
            },
            error: function(xhr, status, error) {
            	console.log(error);
            }
        });
    });
});

</script>

</head>
<body>
<h1>main</h1>
<button id="aaa">aaa호출</button><br>
<button id="bbb">bbb호출</button><br>
<button id="ccc">ccc호출</button><br>
<button id="ddd">ddd호출</button><br>
<button id="eee">eee호출</button><br>
<div id="result"></div>

</body>
</html>

'Daily Codig Reminder' 카테고리의 다른 글

myBatis2  (0) 2024.02.16
@Reponsebody ,mybatis  (0) 2024.02.16
parameter, session  (0) 2024.02.16
parameter  (1) 2024.02.12
mybatis  (1) 2024.02.12