parameter.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>1013 파라미터 전송</title>
</head>
<body>
<a href="getlink?name=yn&job=singer">
링크를 이용한 파라미터 전송</a><br/>
<h3>Get 방식의 Form전송</h3>
<form action="getform">
이름:<input type="text" name="name"/><br/>
비번:<input type="password" name="password"> <br/>
<input type="submit" value="전송"/>
</form>
<br/>
<h3>post 방식의 Form전송</h3>
<form action="postform" method="post">
이름:<input type="text" name="name"/><br/>
비번:<input type="password" name="password"> <br/>
<input type="submit" value="전송"/>
</form>
<br/>
<h3>post 방식의 Form전송</h3>
<form action="postform" method="post">
이름:<input type="text" name="name"/><br/>
비번:<input type="password" name="password"> <br/>
<input type="submit" value="전송"/>
</form>
<br/>
<h3>File 업로드</h3>
<form action="fileupload" method="post" enctype="multipart/form-data">
이름:<input type="text" name="name"/><br/>
파일:<input type="file" name="file"/><br/>
<input type="submit" value="전송"/>
</form>
</body>
</html>
PageController.java
package com.ynsoft.item.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ynsoft.item.domain.MemberDTO;
import com.ynsoft.item.domain.ReportDTO;
import lombok.extern.log4j.Log4j;
//Controller를 만들기위한 어노테이션
@Controller
//로그 출력을 위한 인서튼서를 생성하기 위한 어노테이션
@Log4j
public class PageController {
//처리할 URL과 전송 방식
//model:view에게 데이터를 넘기기 위한 객체
@RequestMapping(value = "blog/{num}",method = RequestMethod.GET)
public String blog(@PathVariable int num, Model model) {
model.addAttribute("num",num);
//출력할 뷰 이름 설정
return "blog";
}
@RequestMapping(value="parameter",method = RequestMethod.GET)
public String parameter(Model model) {
return "parameter";
}
//파라미터를 HttpServletRequest를 이용해서 읽기
@RequestMapping(value="getlink",method = RequestMethod.GET)
public void getlink(
HttpServletRequest request,Model model) {
String name= request.getParameter("name");
String job= request.getParameter("job");
System.out.println(name+job);
}
//@RequestParam이용
@RequestMapping(value="getform",method = RequestMethod.GET)
public void getlink(
@RequestParam("name") String name,
@RequestParam("password") String password,
Model model) {
System.out.println(name+password);
}
//파라미터 command사용해서 출력
@RequestMapping(value="postform",method = RequestMethod.POST)
public void postform(
MemberDTO dto,
Model model) {
System.out.println(dto);
}
@RequestMapping(value="fileupload",method = RequestMethod.POST)
public void fileupload(ReportDTO dto,HttpServletRequest request) {
if(dto.getFile().isEmpty()) {
System.out.println("업로드 파일이 없습니다.");
}
else {
//프로젝트 내 upload 디렉토리 절대경로 생성
//로컬에서는 이 절대경로에 들어가지만, cafe24에 올리면 이 프로젝트 안에 upload폴더에 들어감
String filepath=request.getServletContext().getRealPath("/upload");
System.out.println(filepath);
//UUID.randomUUID():랜덤 코드 생성
filepath= filepath + "/" +UUID.randomUUID() + dto.getFile().getOriginalFilename();
File file=new File(filepath);
try {
dto.getFile().transferTo(file);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
}
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">
<!-- 웹 애플리케이션이 시작될 때 작업을 수행하는 리스너 클래스
여기서는 스프링의 클래스를 등록했는데 여기까지 설정하면 webapp디렉토리의
applicationContext.xml 파일이 동작 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- applicationContext.xml 파일 경로 수정 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Dispatcher-Servlet 설정
Dispatcher-Servlet 역할을 수행 할 설정 파일의 경로 설정 -->
<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>
<!-- Dispatcher-Servlet과 URL이 /로 되어있음매핑 -->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
servlet-context.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">
<!-- Spring MVC에서 제공하는 어노테이션을 사용하겠다는 설정 지우면 안 됨 -->
<annotation-driven />
<!-- 컴파일되지 않는 파일(정적 파일)의 위치를 설정
resources/로 시작하는 파일 경로는 src/main/resources 디렉토리에서 찾고
이 자원들은 캐싱을 함 캐싱:자주사용하면 메모리에 올려두는 것-->
<resources mapping="/resources/**" location="/resources/" />
<!--Controller에서 View이름을 리턴하는 경우 View이름과 조합해 실제 출력할 파일을 설정
redirect 되는 경우는 이 설정을 적용하지 않음
<beans:property name="prefix" value="/" /> 로 만들면 webapp에서 실행 -->
<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>
<!-- @어노테이션이 붙은 클래스의 bean을 자동 생성해주는 패키지 경로 -->
<context:component-scan
base-package="com.ynsoft.item" />
<!-- 파일업로드 설정 -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</beans:bean>
</beans:beans>
728x90
'Spring > Spring 실습' 카테고리의 다른 글
MyBatis의 SQL을 인터페이스에서 작성해서 수행하도록 프로젝트 변경 (0) | 2022.10.14 |
---|---|
MySQL + Spring 연동 (0) | 2022.10.14 |
Spring MVC Project 생성 #2 (0) | 2022.10.13 |
Spring MVC Project 생성 (0) | 2022.10.13 |
spring / jsonparser 영화순위 api 배열 데이터 출력하기 (0) | 2022.09.16 |
댓글