★ 스프링 MVC

: 스프링 MVC도 컨트롤러를 사용하여 클라이언트의 요청을 처리한다
  스프링에서 DispatcherServlet 이 MVC에서 C(Control) 부분을 처리한다.
  개발자가 처리할 부분은 클라이언트의 요청을 처리할 컨트롤러와 응답화면을 전송할 JSP나 Velocity 템플릿 등 뷰 코드이다
  DispatcherServlet, HandlerMapping, ViewResolver등은 스프링이 기본적으로 제공하는 구현 클래스를 사용한다.

: 스프링 MVC의 구성 요소
1. DispatcherServlet
클라이언트의 요청을 전달 받는다
컨트롤러에게 클라이언트의 요청을 전달하고 Controller가 리턴한 결과값을 View에 전달하여 응답을 생성하도록 한다.

2. HandlerMapping
클라이언트의 요청 URL을 어떤 Controller가 처리할지를 결정한다

3. Controller
클라이언트의 요청을 처리한 뒤 결과를 DispatcherServlet에 알려준다.
스트럿츠의 Action과 동일한 역활을 수행한다.

4. ModelAndView
컨트롤러가 처리한 결과 정보 및 뷰 선택에 필요한 정보를 담는다.

5. ViewResolver
컨트롤러의 처리 결과를 생성할 뷰를 결정한다.

6. View
컨트롤러의 처리 결과 화면을 생성한다.
JSP나 Velocity 템플릿 파일등을 뷰로 사용한다.

 

Project : Chapter06 (Dynamic Web Project) - *.jar
          project명에서 우클릭 - Spring Tools - Add Spring Project Nature

          Chapter06_DynamicSpringMaven (Dynamic Web Project) - pom.xml
          project명에서 우클릭 - Spring Tools - Add Spring Project Nature
          project명에서 우클릭 - Configure - Convert to Maven Project

          Chapter06_SpringWebMaven (Spring Project)


[실행]
http://localhost:8080/Chapter06/hello.do

Package : com.controller
Class   : HelloController.java

Folder  : WEB-INF
          web.xml
          dispatcher-servlet.xml

Folder  : view
          hello.jsp


★ web.xml
1. web.xml에 DispathcerServlet 설정을 통해 스프링 설정 파일을 지정합니다.
2. *.do로 들어오는 클라이언트의 요청을 DispatcherServlet이 처리하도록 했다
3. DispatcherServlet은 WEB-INF/서블릿이름-servlet.xml 파일로부터 스프링 설정 정보를 읽어온다.


<servlet>
 <servlet-name>dispatcher</servlet-name>
   <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
   </servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
 </servlet-mapping>

-------------------------------------------------------------
★ HelloController.java

1. 컨트롤러를 구현하려면 @Controller 어노테이션을 클래스에 적용한다.
2. @RequestMapping 어노테이션을 이용해서 클라이언트의 요청을 처리할 메소드를 지정한다.
3. ModelAndView.setViewName()메소드를 이용해서 컨트롤러의 처리 결과를 보여줄 뷰 이름을 지정한다.


package com.controller;

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

@Controller
public class HelloController {
 
 @RequestMapping("/hello.do")
 public ModelAndView hello(){
  ModelAndView mav = new ModelAndView();
  mav.setViewName("hello");
  mav.addObject("greeting","Hello Spring MVC");
  return mav;
 }

}

-------------------------------------------------------------
★ dispatcher-servlet.xml

1. DispatcherServlet은 스프링 컨테이너에서 컨트롤러 객체를 검색하기 때문에 스프링 설정파일에 컨트롤러를 빈으로 등록해주어야 한다
2. DispatcherServlet은 뷰이름과 매칭되는 뷰 구현체를 찾기 위해 ViewResolver를 사용한다.
3. 스프링 MVC는 JSP, Velocity, FreeMarker등의 뷰 구현 기술과의 연동을 지원하는데, JSP를 뷰 기술로 사용할 경우 InternalResourceViewResolver 구현체를 빈으로 등록해주면 된다.
4. ViewResolver가 /view/뷰이름.jsp를 뷰JSP로 사용한다는 의미이다


<bean id="helloController"
 class="com.controller.HelloController"/>

<bean id="viewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/view/" />
 <property name="suffix" value=".jsp" />
</bean>

-------------------------------------------------------------

★ /view/hello.jsp

<body>
인사말 : ${greeting }
</body>

-------------------------------------------------------------

[문제1]
Project : Chapter06_1
Package : com.controller
Class   : SumController

Package : com.bean
Class   : SumDTO

Foler   : sum
File    : input.jsp
          result.jsp

스프링 설정 파일
/WEB-INF/dispatcher-servlet.xml → /WEB-INF/dispatcher-config.xml

[실행결과]
http://localhost:8080/Chapter06_1/input.do

input.jsp    --------->  result.jsp

 X : ㅁ                  25 + 36 = xx
 Y : ㅁ

 계산(submit)
 result.do

-------------------------------------------------------------
[문제2]
Project : Chapter06_1
Package : com.controller
Class   : SungJukController

Package : com.bean
Class   : SungJukDTO

Foler   : sungJuk
File    : input.jsp
          result.jsp

스프링 설정 파일
/WEB-INF/mvc-config.xml

[실행결과]
http://localhost:8080/Chapter06_1/sungJuk/input.do

input.jsp    ------------     result.jsp

 이름 : ㅁ                   *** xxx 성적 ***
 국어 : ㅁ               총점 : xxx
 영어 : ㅁ                    평균 : xx.xxx
 수학 : ㅁ

 계산(submit)
 /sungJuk/result.do


** 스프링 설정 파일의 경로와 파일명을 바꿀 수 있고 여러개로 만들 수 있다

/WEB-INF/dispatcher-servlet.xml(스프링 설정 파일)의 이름도 바꾸고 2개로 나누어 본다

/WEB-INF/dispatcher-config.xml - SumController
       ↓
/WEB-INF/mvc-config.xml - SungjukController

 

 

 


 

[문제1]
Project : Chapter06_1
Package : com.controller
Class   : SumController

Package : com.bean
Class   : SumDTO

Foler   : sum
File    : input.jsp
          result.jsp

스프링 설정 파일
/WEB-INF/dispatcher-servlet.xml → /WEB-INF/dispatcher-config.xml

[실행결과]
http://localhost:8080/Chapter06_1/input.do

input.jsp    --------->  result.jsp

 X : ㅁ                  25 + 36 = xx
 Y : ㅁ

 계산(submit)
 result.do

-------------------------------------------------------------

 


프로젝트 생성
web.xml 생성
서블릿 작성
dispatcher-config.xml 만들기
콘트롤러 생성
주소확인
콘트롤러
sum폴더 생성
input.jsp 생성
result.jsp 생성

 

---------------------------------------------------------------------

>>> web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Chapter06_1</display-name>
 
 
  <servlet>
  <servlet-name>dispatcher</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
  <!--
    스프링 설정 파일 :
   /WEB-INF/dispatcher-servlet.xml
    WAC의 이름 또는 위치를 바꾸고 싶을때
   -->
  
   <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/dispatcher-config.xml</param-value>
   </init-param>
  
  </servlet>
 

  
  <servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.do</url-pattern>
  </servlet-mapping>
 
 
 
 
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

>>> dispatcher-config.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="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-4.3.xsd">

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="prefix" value="/view/"></property> // 많이 안씀 -->
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="SumController" class="com.controller.SumController"></bean>


</beans>

>>> controller(com.controller-SumController.java)

 

package com.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class SumController { //POJO형식 -> 순수한 자기만의 클래스 (extends implement 모두 안해줌)
 
 //http://localhost:9090/Chapter06_1/input.do
 @RequestMapping(value="/input.do", method = RequestMethod.GET)  // get방식
 public ModelAndView input() {
  ModelAndView mav = new ModelAndView();
  mav.setViewName("/sum/input");
  return mav;
 }
 
 
 @RequestMapping(value="/result.do", method = RequestMethod.GET)  // get방식
 public ModelAndView result() {
  ModelAndView mav = new ModelAndView();
  mav.setViewName("/sum/result");
  return mav;
 }

}

 

>>>>>> input.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>

<form action="result.do" method=get>
<!-- //<form action="http://localhost:9090/Chapter06_1/result.do" method=get> -->

<table border="1" align="center">
<tr>
<td> X<input type=text name="x" > </td>
</tr>
<tr>
<td> Y<input type=text name="y"> </td>
</tr>
<tr>
<td align="center"> <input type=submit value="result"> <input type=reset value="취소" > </td>
</tr>
</table>
</form>

</body>
</html>

 

 

>>>>> result.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>
${param.x } + ${param.y } = ${param.x + param.y}
</body>
</html>

 

>>>> 결과

http://localhost:9090/Chapter06_1/input.do

 

 

 

 

@RequestMapping("download.do")
public void download(HttpServletResponse response, @RequestParam("id")String id) throws Exception {
// id를 이용해 db에서 파일 fullPath 와 ofn 얻어오기
String ofn = service.getOfn(id);
String fullPath = service.getFilePath(id);
File target = new File(fullPath);
byte[] b = new byte[1024 * 1024 * 10];
DataOutputStream dos = new DataOutputStream(new FileOutputStream(target));

response.reset();
response.setContentType("application/octet-stream");

String fileName = new String(ofn.getBytes("utf8"), "8859_1");
response.setHeader("Content-Disposition", "attatchment; filename = " + fileName);
response.setHeader("Content-length", String.valueOf((int)target.length()));

FileInputStream fis = new FileInputStream(target);
ServletOutputStream sos = response.getOutputStream();

int num;
while((num = fis.read(b,0,b.length)) != -1) {
sos.write(b,0,num);
}
sos.flush();
sos.close();
fis.close();



}

 

<%@page import="java.sql.Timestamp"%>
<%@page import="java.sql.Date"%>
<%@page import="java.sql.Time"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
 pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
 <table border=1 align=center width=630>


  <tr>
   <th colspan=4>Message List
  </tr>

  <tr>
   <th>
   <th>Message
   <th>Name
   <th>Wdate
  </tr>
  <%

Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "web10";
String pw = "web10";
Connection con = DriverManager.getConnection(url, id, pw);

String sql = "select * from message";
PreparedStatement pstat = con.prepareStatement(sql);
ResultSet rs = pstat.executeQuery();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/mm/dd");


while(rs.next()) {
 
 Timestamp t = rs.getTimestamp("wdate");
 long messageTime = t.getTime();
 Date wdate = new Date(messageTime);
 String wdateString = sdf.format(wdate);
 
 // sdf.format(new Date(rs.getTimestamp("wdate")));
 %>

  <tr>
   <td><%=rs.getInt("seq")%>
   <td><%=rs.getString("message")%>
   <td><%=rs.getString("name")%>
   <td><%=wdateString%>
  </tr>

  <%
}

con.close();


%>


 </table>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Input</title>
</head>
<body>

<form action=recv.jsp method=get>
<table border=1>

<tr>
<th colspan=2> Input Message
</tr>

<tr>
<td> Name:
<td> <input type=text name=name placeholder="이름을 입력하세요.">
</tr>

<tr>
<td colspan=2>
<textarea placeholder="메시지을 입력하세요." name=text rows=5 cols=30></textarea>
</tr>

<tr>
<td colspan=2 align = center> <input type=submit id=ok value="OK">
</tr>

</table>
</form>

</body>
</html>

 

17.12.15 웹3일차

자바스크립트 이벤트 처리

이벤트란

====== 버튼 처리 문법

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<input type=button value=pop id=popBtn>


<script type="text/javascript">

document.getElementById("popBtn").onclick = function(){
 alert("pop");
}

</script>

</body>
</html>

====== 페이지 이동문법

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<input type=button value=pop id=popBtn>


<script type="text/javascript">

document.getElementById("popBtn").onclick = function(){
 location.href = "http://www.naver.com"; //페이지 이동문법
  
}

</script>

</body>
</html>


========= 버튼 클릭 후 페이지 팝업 사이즈 지정
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<input type=button value=pop id=popBtn>


<script type="text/javascript">

document.getElementById("popBtn").onclick = function(){

 window.open("http://www.naver.com","","width=500,heigt=500");
  
}

</script>

</body>
</html>

======

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript">

window.onload = function(){
 
 window.open("http://www.google.com","","width=500,height=500");
}

</script>
</body>
</html>

=====

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<script type="text/javascript">

window.onunload = function(){
 for(var i = 0;i<5;i++){
 
 
 window.open("http://www.google.com","","width=500,height=500");
}
}

</script>
</body>
</html>
=======

 

========================== jsp 시작


jsp

서블릿은 문서를 요청받으면 바로 만들어서 보냄

 


 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<p id=target>target</p>
<input type=button value=pop id=pop>


<script type="text/javascript">

document.getElementById("pop").onclick = function(){

 window.open("exam08.html","","width=300,height=200");
}

</script>
</body>
</html>

 

//////////////////////////////

 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<p id=target>target</p>
<input type=button value=pop id=pop>


<script type="text/javascript">

document.getElementById("pop").onclick = function(){

 window.open("exam08.html","","width=300,height=200");
}

</script>
</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

 <script type="text/javascript">
  function plus(num1, num2) {
   alert(num1 + num2);

  }
 </script>
 
 <a href="javascript:plus(10,20)">plus 함수이름 부르기(10,20 더하기)</a>


</body>
</html>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
 <table border=1>
  <tr>
   <td colspan=2 align=center>Plus Example
  </tr>

  <tr>
   <td>number1:
   <td><input type=text placeholder="input number1" id=num1>
  </tr>

  <tr>
   <td>number2:
   <td><input type=text placeholder="input number2" id=num2>
  </tr>

  <tr>
   <td colspan=2 align=center><input type=button value=plus id=plus>
  </tr>

  <tr>
   <td colspan=2 align=center><input type=text placeholder="result here" id=result>
  </tr>
  
</table>

<script type="text/javascript">

document.getElementById("plus").onclick = function(){
 var num1 = parseInt(document.getElementById("num1").value);
 var num2 = parseInt(document.getElementById("num2").value);
 document.getElementById("result").value = num1 + num2;
 
 
}

</script>
</body>
</html>

+ Recent posts