23.05.30 : Spring Mvc (xml / Annotation)

이준영·2023년 5월 30일
0
p. 250 : 스프링 mvc 핵심 구성 요소 참조, (~p 253)

Spring MVC 만들기   <=== Spring DI /AOP

1. Java Project -> Maven Project + Spring Framework + 기타 설정

2. STS(Spring Tool Suite)
		기존 버전(x)
        새로운 버전( => Spring Boot)


Spring Boot  --> 유니콘
전자정부프레임워크 --> legacy spring mvc(기존의 쓰던 스프링 방식 사용)



Spring Mvc

<servlet class> 부분

DispatcherServlet

컨트롤러 역할을 한다 (xml / annotation 가지고 올 수 있음)

<url-pattern>에 해당하는 것만 가져옴



응용 : spring mvc : 우편번호 검색기

프로젝트 구성 기본

dao / to

zipcode.daum			model2.ZipcodeAction		zipcode.jsp
zipcode_ok.daum			model2.ZipcodeOkAction		zipcode_ok.jsp

작업순서 : web.xml --> jsp부분 / action부분 --> servlet.context.xml



dao / to 만든 후

1. web.xml 쓰던 거 가져와서 url-pattern 변경, zipcode.jsp 디자인



2. Action 작업 -> zipcode_ok.jsp에서 정보 가져오기

ZipcodeAction.java

package model2;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ZipcodeAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		System.out.println("ZipcodeAction 호출");
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "zipcode" );
		
		
		return modelAndView;
	}

}

ZipcodeOkAction.java

package model2;

import java.util.ArrayList;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.ZipcodeDAO;
import model1.ZipcodeTO;

public class ZipcodeOkAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		System.out.println( "zipcodeokaction 호출 " );
		
		// form.jsp의 dong으로 받는다는 말
		String strDong = request.getParameter("dong");
		
		System.out.println(strDong);
		
		//
		ZipcodeDAO dao = new ZipcodeDAO();
		
		ArrayList<ZipcodeTO> lists = dao.zipcodeList(strDong);
		
		System.out.println(lists.size());
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "zipcode_ok" );
		// 여러개 써도 상관 x
		modelAndView.addObject( "lists", lists );
		
		return modelAndView;
	}

}

zipcode.ok_jsp

<%@page import="model1.ZipcodeTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
zipcode_ok.jsp
<br><br>
<%
	ArrayList<ZipcodeTO> lists = (ArrayList)request.getAttribute("lists");

	StringBuilder sbHtml = new StringBuilder();
	
	sbHtml.append("<table>");
	for(ZipcodeTO to : lists) {   <--- 간단하게 동까지만
		sbHtml.append("<tr>");
		sbHtml.append("<td>" + to.getZipcode() + "</td>");
		sbHtml.append("<td>" + to.getSido() + "</td>");
		sbHtml.append("<td>" + to.getGugun() + "</td>");
		sbHtml.append("<td>" + to.getDong() + "</td>");
		
		sbHtml.append("</tr>");
	}
	sbHtml.append("</table>");
%>
</body>
<%=sbHtml %>
</html>


3. servlet.context.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	
	
	<bean name="zipcode.do" class="model2.ZipcodeAction" />
	<bean name="zipcode_ok.do" class="model2.ZipcodeOkAction" /> 

	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>


4. index 실행

<%@ 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>
</head>
<body>

<a href="zipcode.daum">zipcode.daum</a><br>
<a href="zipcode_ok.daum">zipcode_ok.daum</a><br>

</body>
</html>




응용 : spring mvc : 게시판 만들기

기존에 만든 model2에서 수정만 해주면 된다.

controller를 만들던 기존과 달리 controller 구현만 해주면 돼서 훨씬 간편

dao / to 설정 후

기존과 다르게 controller를 구현받고 ModelAndView 생성하여 데이터를 저장

ListAction.java

package model2;

import java.util.ArrayList;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.BoardDAO;
import model1.BoardTO;

public class ListAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		System.out.println( "ListAction 호출" );
		
		BoardDAO dao = new BoardDAO();
		ArrayList<BoardTO> datas = dao.boardList();

		request.setAttribute( "datas", datas );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_list1");
		
		modelAndView.addObject("datas", datas);
		
		
		return modelAndView;
	}

}

WriteAction.java

package model2;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.BoardDAO;
import model1.BoardTO;

public class WriteOkAction implements Controller {

	@Override
	public  ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		System.out.println( "WriteOkAction 호출" );
		
		BoardTO to = new BoardTO();
		to.setSubject( request.getParameter( "subject" ) );
		to.setWriter( request.getParameter( "writer" ) );
		to.setMail( "" ) ;
		if( !request.getParameter("mail1").equals("") 
				&& !request.getParameter("mail2").equals("") ) {
			to.setMail( request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" ) );	
		}
		
		to.setPassword( request.getParameter( "password" ) );
		to.setContent( request.getParameter( "content" ) );
		
		to.setWip( request.getRemoteAddr() );
		
		BoardDAO dao = new BoardDAO();
		int flag = dao.boardWriteOk( to );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_write1_ok" );
		// 여러개 써도 상관 x
		modelAndView.addObject( "flag", flag );
		
		return modelAndView;
		
				
		
	}

}


viewAction

viewAction으로 접근하기 위해선 일단 board_list1의 view로 가는 경로를 변경해야한다(list.do seq~~ 로)

package model2;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.BoardDAO;
import model1.BoardTO;

public class ViewAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		System.out.println( "ViewAction 호출" );
		
		
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_view1" );

		
		return modelAndView;
	}

}

modify_ok / delete_ok

flag 인자로 하여 데이터 저장 / 가져옴

modify_ok

package model2;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.BoardDAO;
import model1.BoardTO;

public class ModifyOkAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		System.out.println( "ModifyOkAction 호출" );
		

		BoardTO to = new BoardTO();
		to.setSeq( request.getParameter( "seq" ) );
		to.setSubject( request.getParameter( "subject" ) );
		to.setMail( "" );
		if( !request.getParameter( "mail1" ).equals( "" ) && !request.getParameter( "mail2" ).equals( "" ) ) {
			to.setMail( request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" ) );
		}
		to.setPassword( request.getParameter( "password" ) );
		to.setContent( request.getParameter( "content" ) );
		
		BoardDAO dao = new BoardDAO();
		
		int flag = dao.boardModifyOk( to );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_modify1_ok" );
		modelAndView.addObject("flag", flag);
		
		return modelAndView;
	}

}

delete_ok

package model2;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import model1.BoardDAO;
import model1.BoardTO;

public class DeleteOkAction implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		System.out.println( "DeleteOkAction 호출" );
		

		BoardTO to = new BoardTO();
		to.setSeq( request.getParameter( "seq" ) );
		to.setPassword( request.getParameter( "password" ) );
		
		BoardDAO dao = new BoardDAO();
		int flag = dao.boardDeleteOk( to );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_delete1_ok" );
		modelAndView.addObject("flag", flag);
		
		return modelAndView;
	}

}






Annotation : Controller

컨트롤러 또한 annotation으로 제공된다.

ConfigController1.java (ConfigController1같은 건 여러개로 분할해서 사용도 가능)

controller와 RequestMapping 사용

쓰는 방법


@Controller
//중복 구문 위에다 쓰기
@RequestMapping("/board")
1. 기본
public class ConfigController3 {
	
	@RequestMapping("/list1.do")
	public String handleRequest1() {
		System.out.println("handleRequest1() 호출");
			
		
		
		return "listview1";
	}
    
    
2. ModelAndView 사용
@RequestMapping("/list2.do")
public ModelAndView handleRequest2() {
		System.out.println("handleRequest2() 호출");
			
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("listview2");
		
		
		return modeladAndView;
	}    
 }


이렇게 중복된 것 한꺼번에 처리 가능


servlet.context.xml에서 위의 코드를 등록


index에서 해당 코드 실행





Annotation : 요청 / 응답

action을 따로 만들지 않고 configcontroller안에서 만들고 dao도 한 번에 받기 가능

get / post 분리

get / post 분리하여 사용할 수 있다. (보안상)

// get 시리즈
	@GetMapping("/form_ok.do")
	//@RequestMapping(value="/form_ok.do", method=RequestMethod.GET)   <-- 둘다 동일한 효과
	public ModelAndView form_get_ok() {
		
		System.out.println("form_get_ok() 호출");
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}
	
	// post 시리즈
    @PostMapping("/form_ok.do")
	@RequestMapping(value="/form_ok.do", method=RequestMethod.POST)  <-- " "
	public ModelAndView form_post_ok() {
		
		System.out.println("form_post_ok() 호출");
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}
    
    
    
    //통합(기존 사용)
    	@RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok() {
		
		System.out.println("form_ok() 호출");
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}



데이터 받고 콘솔 출력

	@RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok(HttpServletRequest request, HttpServletResponse response) { 
    <-- 인자들은 필요 없으면 빼도 됨( 여기선 response안쓰니까 뺴도 무방 )
		
		System.out.println("form_ok() 호출" + request.getParameter("data"));
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}
    
    
    //이렇게 작성해도 나온다.
    @RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok(String data) {
		
		System.out.println("form_ok() 호출 : " + data);
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}
    
    //데이터 2개 받기
    @RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok(String data1, String data2) {
		
		System.out.println("form_ok() 호출 : " + data1);
		System.out.println("form_ok() 호출 : " + data2);
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}


//외부에서 받는 변수 이름과 내부에서 쓰는 변수 이름을 다르게 하고 싶을 때
	@RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok(@RequestParam("data1") String pdata1) {
		
		//System.out.println("form_ok() 호출 : " + data1);
		System.out.println("form_ok() 호출 : " + pdata1);
		
		ModelAndView modeladAndView = new ModelAndView();
		modeladAndView.setViewName("form_ok");
		
		return modeladAndView;
	}

응답

	1. 전통 방법
	@RequestMapping(value="/form_ok.do")
	public String form_ok(HttpServletRequest request) {
		
		request.setAttribute("data1", request.getParameter("data1"));
		
		return "form_ok";
	}
    
    2. ModelAndView
    @RequestMapping(value="/form_ok.do")
	public ModelAndView form_ok(HttpServletRequest request) {
		
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("form_ok");
		modelAndView.addObject("data1", request.getAttribute("data1"))
		
		return modelAndView;
	}
    
    
    3. Model 사용
    @RequestMapping(value="/form_ok.do")
	public String form_ok(HttpServletRequest request, Model model) {
		
	
		model.addAttribute("data1", request.getParameter("data1"));

		return "form_ok";
	}
    
    

form_ok.jsp

<body>
form_ok.jsp<br>
<%=(String)request.getAttribute("data1") %>
</body>



응용 : Spring Mvc 게시판 : Annotation으로 바꾸기

변경점

  1. servlet.context.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-4.3.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<!--
	<bean class="config.ConfigController1" />
	<bean class="config.ConfigController2" />
		 -->
		 
	<!-- 패키지 지정하여 그 패키지 안 검색 -->	 
	<context:component-scan base-package="config" />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

model2패키지 -> config 패키지, 안에 Action -> ConfigController 하나로 변경

package config;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

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

import model1.BoardDAO;
import model1.BoardTO;

@Controller
public class ConfigController {
	
	@RequestMapping("/list.do")
	public ModelAndView boardList(HttpServletRequest request) {
		
		BoardDAO dao = new BoardDAO();
		
		ArrayList<BoardTO> lists = dao.boardList();
		
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_list1");
		modelAndView.addObject("lists", lists);
		
		return modelAndView;
		
	}
	
	@RequestMapping("/write.do")
	public ModelAndView boardWrite(HttpServletRequest request) {
	
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_write1");

		return modelAndView;
		
	}
	
	
	@RequestMapping("/write_ok.do")
	public ModelAndView boardWriteOk(HttpServletRequest request) {
		
		BoardTO to = new BoardTO();
		
		to.setSubject( request.getParameter( "subject" ) );
		to.setWriter( request.getParameter( "writer" ) );
		to.setMail( "" ) ;
		if( !request.getParameter("mail1").equals("") 
				&& !request.getParameter("mail2").equals("") ) {
			to.setMail( request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" ) );	
		}
		
		to.setPassword( request.getParameter( "password" ) );
		to.setContent( request.getParameter( "content" ) );
		
		to.setWip( request.getRemoteAddr() );
		
		BoardDAO dao = new BoardDAO();
		
		int flag = dao.boardWriteOk(to);
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_write1_ok");
		modelAndView.addObject("flag", flag);
		
		return modelAndView;
		
	}
	
	@RequestMapping("/view.do")
	public ModelAndView boardView(HttpServletRequest request) {

		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_view1");

		return modelAndView;
		
	}
	
	@RequestMapping("/modify.do")
	public ModelAndView boardModify(HttpServletRequest request) {

		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_modify1");

		return modelAndView;
		
	}
	
	@RequestMapping("/modify_ok.do")
	public ModelAndView boardModifyOk(HttpServletRequest request) {

		
		BoardTO to = new BoardTO();
		to.setSeq( request.getParameter( "seq" ) );
		to.setSubject( request.getParameter( "subject" ) );
		to.setMail( "" );
		if( !request.getParameter( "mail1" ).equals( "" ) && !request.getParameter( "mail2" ).equals( "" ) ) {
			to.setMail( request.getParameter( "mail1" ) + "@" + request.getParameter( "mail2" ) );
		}
		to.setPassword( request.getParameter( "password" ) );
		to.setContent( request.getParameter( "content" ) );
		
		BoardDAO dao = new BoardDAO();
		
		int flag = dao.boardModifyOk( to );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_modify1_ok" );
		modelAndView.addObject("flag", flag);
		return modelAndView;
		
	}
	
	
	@RequestMapping("/delete.do")
	public ModelAndView boardDelete(HttpServletRequest request) {

		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("board_delete1");

		return modelAndView;
		
	}
	
	@RequestMapping("/delete_ok.do")
	public ModelAndView boardDeleteOk(HttpServletRequest request) {

		
		BoardTO to = new BoardTO();
		to.setSeq( request.getParameter( "seq" ) );
		to.setPassword( request.getParameter( "password" ) );
		
		BoardDAO dao = new BoardDAO();
		
		int flag = dao.boardDeleteOk( to );
		
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName( "board_delete1_ok" );
		modelAndView.addObject("flag", flag);
		return modelAndView;
		
	}
}

나머지 view 폴더 안의 jsp나 index는 동일 ( 결과도 동일 )

profile
끄적끄적

0개의 댓글