# new Function 함수 

 

 - 런타임상에 문자열을 사용해 함수를 만들 수 있다는 장점.

 - 함수의 인자값을 서버로 부터 받아서 동적으로 함수를 생성할 때, 유용하게 사용 가능.

 - 단, new Function의 생성은 오직 전역 변수에만 접근 가능 

 

 

# newFunction 함수 문법

var function = new Function([arg1, arg2 ... argN] , functionBody);

# new Function 예시 

   

- sum 함수

 var sum = new Function('a' , 'b' , 'return a + b;');     
 var sum = new Function('a , b' , 'return a + b;');
 sum(1,2); //3 

  - alert 띄우기

var alertFunc  = new Function( 'v', 'alert(v)'));

   - 화살표 함수 생성하기 

function arrowFuncMake(str) {
  var splitted = str.split("=>");
  console.log(splitted);
  return new Function(splitted[0], "return (" + splitted[1] + ");");
}

arrowFuncMake('n => n * 10')(10);
// 100
arrowFuncMake('n => n * 10')(20);
// 200
arrowFuncMake('n => n * 10')(30);
// 300
arrowFuncMake('a ,b => a + b')(10,20);
// 30

 

 


# new Fucntion은 전역 변수만 접근 가능

   var value = "1111";     
   function getFunc() {         
   		var value = "test";         
        var func = new Function('alert(value)');         
        return func;
   }
   getFunc()(); 
   // alert시 1111이 띄워짐

 

블로그 이미지

미나미나미

,

[Spring] Spring에서 Thymeleaf 테이블 만들기 (index 사용)

- Spring MVC, boot 둘 동일하게 작동 가능(thymeleaf 설정의 차이는 있음)

 

 

 

1. Event.java : 이벤트 내용 정의

package com.example.demo;

import java.time.LocalDateTime;

public class Event {
    private String name;
    private int limitOfEnrollment;
    private LocalDateTime startDateTime;
    private LocalDateTime endDateTime;

    public static Event.EventBuilder builder() {
        return new Event.EventBuilder();
    }

    public String getName() {
        return this.name;
    }

    public int getLimitOfEnrollment() {
        return this.limitOfEnrollment;
    }

    public LocalDateTime getStartDateTime() {
        return this.startDateTime;
    }

    public LocalDateTime getEndDateTime() {
        return this.endDateTime;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setLimitOfEnrollment(final int limitOfEnrollment) {
        this.limitOfEnrollment = limitOfEnrollment;
    }

    public void setStartDateTime(final LocalDateTime startDateTime) {
        this.startDateTime = startDateTime;
    }

    public void setEndDateTime(final LocalDateTime endDateTime) {
        this.endDateTime = endDateTime;
    }

    public Event() {
    }

    public Event(final String name, final int limitOfEnrollment, final LocalDateTime startDateTime, final LocalDateTime endDateTime) {
        this.name = name;
        this.limitOfEnrollment = limitOfEnrollment;
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
    }

    public static class EventBuilder {
        private String name;
        private int limitOfEnrollment;
        private LocalDateTime startDateTime;
        private LocalDateTime endDateTime;

        EventBuilder() {
        }

        public Event.EventBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public Event.EventBuilder limitOfEnrollment(final int limitOfEnrollment) {
            this.limitOfEnrollment = limitOfEnrollment;
            return this;
        }

        public Event.EventBuilder startDateTime(final LocalDateTime startDateTime) {
            this.startDateTime = startDateTime;
            return this;
        }

        public Event.EventBuilder endDateTime(final LocalDateTime endDateTime) {
            this.endDateTime = endDateTime;
            return this;
        }

        public Event build() {
            return new Event(this.name, this.limitOfEnrollment, this.startDateTime, this.endDateTime);
        }

        public String toString() {
            return "Event.EventBuilder(name=" + this.name + ", limitOfEnrollment=" + this.limitOfEnrollment + ", startDateTime=" + this.startDateTime + ", endDateTime=" + this.endDateTime + ")";
        }
    }
}

2. EventService.java : 이벤트 객체 만들기

package com.example.demo;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class EventService {
    public List<Event> getEvents(){
        Event event = Event.builder()
                    .name("Spring")
                    .limitOfEnrollment(5)
                    .startDateTime(LocalDateTime.of(2019,1,10,10,10))
                    .endDateTime(LocalDateTime.of(2019,1,10,13,10,10))
                    .build();

        Event event2 = Event.builder()
            .name("Spring")
            .limitOfEnrollment(5)
            .startDateTime(LocalDateTime.of(2019,1,17,10,10))
            .endDateTime(LocalDateTime.of(2019,1,17,13,10,10))
            .build();

        return List.of(event,event);
    }
}

3. EventController.java : 이벤트 객체 페이지 전달

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class EventController {

    @Autowired
    EventService eventService;

    //@RequestMapping(value = "/events" ,method = RequestMethod.GET)
    @GetMapping("events")
    public String events(Model model){
        model.addAttribute("events" ,eventService.getEvents());
        return "events";
    }

}

 

 

4. Event.html : 이벤트 내용 표현

<!DOCTYPE html>
<html lang="en" xmlns:th="http://thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table {
            width: 100%;
            border: 1px solid #444444;
            text-align: center;
        }
        th, td {
            border: 1px solid #444444;
        }
    </style>
</head>
<body>
    <h1>이벤트 목록</h1>
    <table>
        <tr>
            <th>#</th>
            <th>이름</th>
            <th>참가 인원</th>
            <th>시작</th>
            <th>종료</th>
            <th>index 내용</th>
        </tr>
        <tr th:each="event , index: ${events}">
            <td th:text="${index.index}">#</td>
            <td th:text="${event.name}">이벤트 이름</td>
            <td th:text="${event.limitOfEnrollment}">100</td>
            <td th:text="${event.startDateTime}">2019년 1월 10일 오전 10시</td>
            <td th:text="${event.endDateTime}">2019년 1월 10일 오전 12시</td>
            <td th:text="${index}">index</td>
        </tr>
    </table>
</body>
</html>

5. 결과화면

블로그 이미지

미나미나미

,

# 스프링 JSP에서 HTML로 설정 변경하기 

 

 

1. web.xml의 추가 부분 ( 추가 부분을 확인하세요.)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- 추가 부분 시작 : HTML 설정 부분 -->
	<servlet>
		<servlet-name>htmlServlet</servlet-name>
		<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
		<load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>htmlServlet</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
	<!-- 추가 부분 끝 : HTML 설정 부분 -->


	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


	<!-- 한글설정 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>
			org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 한글설정 END -->


</web-app>

 

 

2. servlet-context.html의 suffix를 html로 변경

   <beans:property name="suffix" value=".jsp" />를

   <beans:property name="suffix" value=".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">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- 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/" />
		<!-- jsp을 html로 변경 -->
		<beans:property name="suffix" value=".html" />
		
	</beans:bean>
	
	<context:component-scan base-package="com.example.thymeleaf" />
	
	
	
</beans:beans>

 

 

3. eventList.html 파일 불러오기

 

- HTML 파일

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <title>Insert title here</title>
</head>

<body>
    <p>스프링에서 html 불러오기</p>
</body>

</html>

- EventController.java

package com.example.thymeleaf;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class EventController {

	@GetMapping("eventList")
	public String eventList(HttpServletRequest request, HttpServletResponse response) {
		return "eventList";
	}
	
}

4. 결과화면

 

블로그 이미지

미나미나미

,

Spring MVC 파일업로드 Multipart의 경우 몇가지 설정을 해야합니다.

 

1. pom.xml 파일업로드 관련 의존성 추가

<!--  파일업로드  -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
        <!--  파일업로드  -->

 

 


2. dispatcher-servlet.xml(이클립스 경우, servlet-context.xml)에 multipart 부분 설정 

 <!-- 파일업로드 관련 Mulitipart 설정 -->
    <beans:bean id="multipartResolver"
                class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 
        	setting maximum upload size
            최대 크기 설정
            <beans:property name="maxUploadSize" value="-1"/>
        -->
        <beans:property name="maxUploadSize" value="209715200"/> <!-- 20MB --> <!-- max size of file in memory (in bytes) -->
        <beans:property name="maxInMemorySize" value="1048576"/> <!-- 1MB -->
    </beans:bean>


3. web.xml에 multipart 부분 설정

 <!-- MultipartFilter 적용 -->
    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- MultipartFilter 적용 -->


 

 

4. tomcat 설정하기(본인 설치한 톰캣 설정 파일) - 톰캣 - conf - context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context allowCasualMultipartParsing="true">
	<!-- Context와 아래 Resource 부분 변경 해결 -->
	<Resources cachingAllowed="true" cacheMaxSize="100000"></Resources>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

5. tomcat 설정하기(본인 설치한 톰캣 설정 파일) - 톰캣 - conf - server.xml

 - body로 전송할 수 있는 사이즈 defalut 2mb를 최대 2gb으로 변경.

 - the configured maximum ...... 에러 발생시 처리할 부분..

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" 
			   maxPostSize="-1"/>
블로그 이미지

미나미나미

,
// 일반적인 즉시 함수 
(function (a) {
    console.log(100);
    // 100
})(100);

// 1. 즉시 실행 
!function (a) {
    console.log(a);
    // 100
}(100);

//
true && function (a) {
    console.log(a);
    // 100
}(100);

1 ? function (a) {
    console.log(a);
    // 100
}(100) : 0;

0, function (a) {
    console.log(a);
    // 100
}(100);

var b = function (a) {
    console.log(a);
    // 100
}(100);

function f2() { }
f2(function (a) {
    console.log(a);
    // 100
}(100))

var f3 = function c(a) {
    console.log(a);
    // 100
}(100);

new function(){
    console.log(100);
    // 100
};

블로그 이미지

미나미나미

,

1-1. 테스트

for(let j = 0; j < 10; j++){
    var arr = [];
    console.time("1-1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        arr[i] = i;
    }

    console.timeEnd('1-1.calculatingTime');

    //  -------------------------------------
    var arr = [];
    console.time("2-1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        arr.push(i);
    }
    console.timeEnd('2-1.calculatingTime');
}

   1-2. 결과 :

        익스의 경우 arr[i] = i가 성능상 빠름,

        크롬의 경우 arr[i]가 빠르다고 생각하여 테스트를 진행하였으나,

        엎치락뒤치락 하는 기록이 있음 (평균값. arr[i] = i : 20.79489746ms , arr.push(i) : 24.61420898)

     


 2-1. 테스트 

var j = 0;
for (j = 0; j < 10; j++) {
    var sum = 0;
    var arr = [];
    console.time("1.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        sum += i;
        arr[i] = sum;
    }

    console.timeEnd('1.calculatingTime');
}
//  -------------------------------------
var j = 0;
for (j = 0; j < 10; j++) {
    var sum = 0;
    var arr = [];
    console.time("2.calculatingTime")
    for (var i = 1; i <= 1000000; i++) {
        sum += i;
        arr.push(sum);
    }

    console.timeEnd('2.calculatingTime');
}

2-2 결과 

        익스의 경우 여전히 arr[i] = i가 성능상 빠름,

        크롬의 경우 엎치락뒤치락 하는 기록이 있음 (평균값. arr[i] = i : 75.38521ms , arr.push(i) : 78.85928)


 

블로그 이미지

미나미나미

,

_.partial 함수

 : 함수의 인자를 일부분 지정 후, 함수 호출 시 인자를 추가적으로 지정하는 함수.

 

 

예제. 인자값을 모두 더하는 함수

// 인자값을 모두 더하는 함수 
function add(){
    var result = 0;
    for(var i =0; i < arguments.length; i++){
		// 인자값 확인
		console.log('arg['+i+']' + ' =>' + arguments[i]); 
        result +=arguments[i];
    }
    return result;
}

// add 함수의 첫번째 인자를 비워두고, 2번째 인자에는 3으로 채운다
var addTest = _.partial(add, _ , 3);

console.log("result = > " + addTest(2)); 
// arg[0] =>2
// arg[1] =>3
// result = > 5

// 최종적으로 인자값이 2, 3, 10, 100 
console.log("result = > " + addTest(2 , 10 , 100)); 
VM1073:6 arg[0] =>2
VM1073:6 arg[1] =>3
VM1073:6 arg[2] =>10
VM1073:6 arg[3] =>100
VM1252:1 result = > 115


예제. 

var student = {
    studnetName : "abc", 
    studentNumber : "20201000",
    studentPrint : _.partial(function(a, b){
        return a + this.studentNumber  + ", " + b + this.studnetName;
    } , "학번 : " , "이름 :")
};
console.log("student = > " + student.studentPrint());

var callStu = student.studentPrint.call({studnetName : "kukkuku" , studentNumber : "20191000"});
console.log("callStu = > " + callStu);

// 새로운 함수를 return
var bindStu = student.studentPrint.bind({studnetName : "zerotototo" , studentNumber : "201999999"});
console.log("bindStu = > " + bindStu());
// VM2322:8 student = > 학번 : 20201000, 이름 :abc
// VM2322:10 callStu = > 학번 : 20191000, 이름 :kukkuku
// VM2322:12 bindStu = > 학번 : 201999999, 이름 :zerotototo

블로그 이미지

미나미나미

,

@GepMapping 테스트 해보기

 

1. 단순 컨트롤러 테스트 해보기 

  1-1. 컨트롤러 소스(SimpleMappingController.java)

// SimpleMappingController.java
// localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping1")
    public String SimpleMapping1(){
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

  1-2. 테스트 코드(SimpleMappingControllerTest.java)

// SimpleMappingControllerTest.java
@Test
    public void simpleMapping1() throws Exception{
        // 페이지 요청시 성공적으로 처리
        mockMvc.perform(get("/SimpleMapping1"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
                ;

        // 페이지 요청시 /123 부분으로 404 에러
        mockMvc.perform(get("/SimpleMapping1/123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isNotFound()) // 404 에러
        ;

        // 페이지 요청시 /zzzzz 부분으로 404 에러가 일어남으로 400번대 에러임을 확인 
        mockMvc.perform(get("/SimpleMapping1/zzzzzz"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().is4xxClientError()) // 400 번대 에러일 경우
        ;
    }

2. 컨트롤러의 path의 숫자 또는 영문 받기 

  2-1. 컨트롤러 소스 코드(SimpleMappingController.java)

// SimpleMappingController.java
   // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{number:[1-9]+}")
    public String SimpleMapping2Number(@PathVariable String number){
        System.out.println("number = > " + number);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{characters:[a-z]+}")
    public String SimpleMapping2String(@PathVariable String characters){
        System.out.println("characters = > " + characters);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

 2-2. 테스트 코드(SimpleMappingControllerTest.java)

@Test
    public void simpleMapping2() throws Exception{
        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping2"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isNotFound()) // 404
        ;

        // 페이지 요청시 number
        mockMvc.perform(get("/SimpleMapping2/123123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
        ;

        // 페이지 요청시 characters
        mockMvc.perform(get("/SimpleMapping2/asdasda"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
        ;
    }

3. 컨트롤러의 여러 패스를 받는 경우 / 하나의 패스를 받는 경우  

  3-1. 컨트롤러 소스 코드(SimpleMappingController.java)

   // "SimpleMapping3/"만 맞는 다면, 모든 다 받는다(ex: "test/123" , "test" , "test/1111/1123123")
    @GetMapping("/SimpleMapping3/**")
    @ResponseBody
    public String SimpleMapping3Multi(HttpServletRequest request){
        System.out.println("SimpleMapping3Multi");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Multi " + request.getRequestURI();
    }

    // "SimpleMapping3/" 아래의 한 패스만 받는다, (ex: "test" , "zzzzz" , "1123123")
    @GetMapping("/SimpleMapping3/*")
    @ResponseBody
    public String SimpleMapping3Simple(HttpServletRequest request){
        System.out.println("SimpleMapping3Simple");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Simple " + request.getRequestURI();
    }

3-2. 테스트 코드(SimpleMappingControllerTest.java)

@Test
    public void simpleMapping3() throws Exception{
        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Multi " + "/SimpleMapping3"))
        ;

        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3/123/zzzzaaa"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Multi " + "/SimpleMapping3/123/zzzzaaa"))
        ;

        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3/zzaseqwe123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Simple " + "/SimpleMapping3/zzaseqwe123"))
        ;
    }

4. 결과 화면 


5. 소스 코드

  컨트롤러 코드  

더보기

//  컨트롤러 소스 코드(SimpleMappingController.java)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class SimpleMappingController {

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping1")
    public String SimpleMapping1(){
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{number:[1-9]+}")
    public String SimpleMapping2Number(@PathVariable String number){
        System.out.println("number = > " + number);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

    // localhost:8080/SimpleMapping1 으로 페이지 불러오기
    @GetMapping("/SimpleMapping2/{characters:[a-z]+}")
    public String SimpleMapping2String(@PathVariable String characters){
        System.out.println("characters = > " + characters);
        // views/SimpleMapping/SimpleMapping1.jsp 페이지
        return "SimpleMapping/SimpleMapping1";
    }

    // "SimpleMapping3/"만 맞는 다면, 모든 다 받는다(ex: "test/123" , "test" , "test/1111/1123123")
    @GetMapping("/SimpleMapping3/**")
    @ResponseBody
    public String SimpleMapping3Multi(HttpServletRequest request){
        System.out.println("SimpleMapping3Multi");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Multi " + request.getRequestURI();
    }

    // "SimpleMapping3/" 아래의 한 패스만 받는다, (ex: "test" , "zzzzz" , "1123123")
    @GetMapping("/SimpleMapping3/*")
    @ResponseBody
    public String SimpleMapping3Simple(HttpServletRequest request){
        System.out.println("SimpleMapping3Simple");
        System.out.println("request.getRequestURI() = > " + request.getRequestURI());
        return "SimpleMapping3Simple " + request.getRequestURI();
    }

}


테스트 코드 

더보기

// 테스트 코드(SimpleMappingControllerTest.java)
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

public class SimpleMappingControllerTest {

    @InjectMocks
    private SimpleMappingController simpleMappingController;

    private MockMvc mockMvc;

    // @Test 메소드 실행전 셋업 메소드
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(this.simpleMappingController).build();
    }

    @Test
    public void simpleMapping1() throws Exception{
        // 페이지 요청시 성공적으로 처리
        mockMvc.perform(get("/SimpleMapping1"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
                ;

        // 페이지 요청시 /123 부분으로 404 에러
        mockMvc.perform(get("/SimpleMapping1/123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isNotFound()) // 404 에러
        ;

        // 페이지 요청시 /zzzzz 부분으로 404 에러가 일어남으로 400번대 에러임을 확인
        mockMvc.perform(get("/SimpleMapping1/zzzzzz"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().is4xxClientError()) // 400 번대 에러일 경우
        ;
    }

    @Test
    public void simpleMapping2() throws Exception{
        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping2"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isNotFound()) // 404
        ;

        // 페이지 요청시 number
        mockMvc.perform(get("/SimpleMapping2/123123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
        ;

        // 페이지 요청시 characters
        mockMvc.perform(get("/SimpleMapping2/asdasda"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(forwardedUrl("SimpleMapping/SimpleMapping1")) //
        ;
    }

    @Test
    public void simpleMapping3() throws Exception{
        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Multi " + "/SimpleMapping3"))
        ;

        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3/123/zzzzaaa"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Multi " + "/SimpleMapping3/123/zzzzaaa"))
        ;

        // 페이지 요청시 number 또는 characters 없음으로 404 에러
        mockMvc.perform(get("/SimpleMapping3/zzaseqwe123"))
                .andDo(print()) // 처리 내용을 출력
                .andExpect(status().isOk()) // 200
                .andExpect(content().string("SimpleMapping3Simple " + "/SimpleMapping3/zzaseqwe123"))
        ;
    }
}

블로그 이미지

미나미나미

,