2016년 10월 6일 목요일

06day Spring

1.스프링 템플릿에서 데이터 보내고 처리된 데이터 뷰페이지로 보내기

폴더구조

web.xml ----매핑을 기본 탬플릿에서 *.do로 바꿈, 한글필터 적용함
<?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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- 한글 인코딩 -->
    <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>*.do</url-pattern>
    </filter-mapping>
  
    <!-- 모든 서블릿에서 활용가능한 공유자원 정의  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- 공유자원 컨테이너 생성 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 서블릿 -->
    <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>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern><!-- 매핑패턴 -->
    </servlet-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 http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://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/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    
    <context:component-scan base-package="com.exam.web01" />
    
    
    
</beans:beans>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

index.jsp
<!-- index(data) ▶ list.do ▶ConfigController(데이터 처리) ▶ view(데이터 받음) -->
<form action="./list3.do" method="post">
    데이터1 :<input type="text" name="data1">
    데이터2 :<input type="text" name="data2">
    <input type="submit" value="전송">
</form>
</body>
</html>

ConfigController.java
package com.exam.web01;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ConfigController {
 //첫번째 방법
 @RequestMapping("/list1.do")
 public String handleRequest1(
   @RequestParam("data1") String data1,
   @RequestParam("data2") String data2, Model model){
   
   System.out.println("data1 : "+data1);
   System.out.println("data2 : "+data2);
   
   model.addAttribute("data1",data1);
   model.addAttribute("data2",data2);
   
   return "listview";
 }
 
 //두번쨰 방법
 @RequestMapping("list2.do")
 public ModelAndView handleRequest2(
   @RequestParam("data1") String data1,
   @RequestParam("data2") String data2){
   
   ModelAndView modelAndView = new ModelAndView();
   modelAndView.setViewName("listview");
   modelAndView.addObject("data1", data1);
   modelAndView.addObject("data2", data2);
   
   return modelAndView;
 }
 
 //세번째 방법
 @RequestMapping("list3.do")
 public String handleRequest3(
   HttpServletResponse response,
   HttpServletRequest request,
   Model model){
  
  model.addAttribute("data1", request.getParameter("data1"));
  model.addAttribute("data2", request.getParameter("data2"));
  
  return "listview";
 }
   
}

listview.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    listview.jsp<br />
    
    data1 : <%= request.getAttribute("data1") %> <br />
    data2 : <%= request.getAttribute("data2") %> <br />
</body>
</html>


2.파일전송

먼저 파일전송을 위한 cos라이브러리를 다운받아야함.http://mvnrepository.com/artifact/com.servlets/cos/09May2002
maven사이트에서 라이브러리 검색을 하고, pom.xml에 붙어넣을 dependency 가져옴


라이브러리 가져오는 2번째 방법은 이클립스pom.xml dependencies탭에서 cos라이브러리 검색


폴더구조

web.xml --- 기본탬플릿에서 *.do로 매핑함
<?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 http://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>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

</web-app>

index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
index.jsp
<form action="./upload.do" method="post" enctype="multipart/form-data">
    파일 : <input type="file" name="upload" />
    <input type="submit" value="전송"/>
</form>
</body>
</html>

UploadController.java
package com.exam.web02;

import java.io.IOException;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

@Controller
public class UploadController {
 @RequestMapping(value="/upload.do", method=RequestMethod.POST)
 public String handleRequest(
   HttpServletResponse response,
   HttpServletRequest request){
  
  //업로드 조건 지정
  String uploadPath ="C:/spring/workspace/WEBEx02/src/main/webapp/upload";
  int maxFileSize = 1024*1024*2;
  String encoding = "utf-8";
  
  try {
   //파일이 업로드 됨
   MultipartRequest multi = new MultipartRequest(request, uploadPath, maxFileSize, encoding, new DefaultFileRenamePolicy());
   
  } catch (IOException e) {
   e.printStackTrace();
  }
  
  return "upload";
 }
}

upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    파일업로드 됨
</body>
</html>


댓글 없음:

댓글 쓰기