Develop/Spring MVC

0818 Spring

포페PostFace 2022. 8. 22. 17:43

0818

스프링 구동 순서
pom.xml에서 maven 중앙 저장소에서 필요한 파일을 읽고 구동함
-> web.xml에서 context-param 읽음 ->root-context.xml 읽음
-> web.xml에서 servlet-mapping 읽음 -> /요청=>DispatcherServlet 요청 처리
-> web.xml에서 filter(설정시 작동) 읽음(servlet 안에 init-param=서블릿에서만 사용하는 변수)
-> servlet-context.xml 읽음(/ 요청 했을때만 사용되는 것들이 정의되어있음) 
=> prefix,suffix 변수 설정, scan 해야할 패키지 설정(com.spring.ex @Controller).
->HomeController.java(MVC중 컨트롤러다) 읽음
->home() 메소드를 통해 home.jsp 실행

<!-- 
	class InternalResourceViewResolver{
		private String prefix;
		private String suffix;
		
		public void setPrefix(String prefix){
			this.prefix = prefix
		}
		public void setSuffix(String suffix){
			this.suffix = suffix;
		}
	}
	new InternalResourceViewResolver()
	setPrefix("/WEB-INF/views/")
	setSuffix(".jsp")
 -->
	<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>
	<!-- /WEB-INF/views/ 중간  .jsp -->




실행시 가장 먼저 나오는 주소
http://localhost:8080/ex/
ex = 05_MVC/com.spring.ex의 축약
마지막에 /를 요청한것.

HomeController.java에서
Model : view에 전달할 객체 정보를 담는다.
home.jsp를 바로 실행할 수 없는 이유 : 요청하는 정보들이 일련의 과정을 통해 생성되는데
그것들을 실행하지 못하고 바로 실행하게되면 정보가 없으므로.

webapp 밑에 jsp파일을 생성하면 직접실행이 되지만 WEB-INF폴더 밑에 생성된 파일은
실행되지 않는다.

method = RequestMethod.GET을 정의하지 않은 경우
get,post 둘 다 처리한다.

@RequestMapping(value="/member/view")
	public String view() {
		
		return "member/memberView";
	}


주소창에 /member/view 를 추가하면 주어진 위치로 이동한다.



@RequestMapping(value = "/member/result")
	public String result(Model model,HttpServletRequest request) {
		request.setAttribute("id","lim");
		model.addAttribute("id", "kim");
		return "member/memberResult";
	}



이동시 필요한 정보를 정의해놓고 사용할 수 있다.
${id}
<%=request.getAttribute("id")%>
${requestScope.id}

kim으로 출력된다(model 객체와 request 객체는 비슷한 성질을 띈다.). 
${param.id},<%=request.getParameter("id")%>는 쓸 수 없다.


@RequestMapping(value = "/member/list")
	public ModelAndView list() {
		ModelAndView mav=new ModelAndView();
		mav.addObject("name","태연");
		mav.addObject("age", 30);
		mav.setViewName("member/memberList");
		return mav;
	}


이런식으로 ModelAndView 객체를 통해 설정할 수도 있다.


@RequestMapping 주의사항 : 

아래와 같이 정의되어 있다고 가정할 때

@RequestMapping("test1/form")
public String form() {
	return "test1/test1Form";
}
// http://localhost:8080/ex/form 요청
//test1/test1Form.jsp , submit 클릭 test1/join1

// http://localhost:8080/ex/test1/join1?name=sss
@RequestMapping("test1/join1")
public String join1() {
	return "test1/result";
}



첫번째 매핑이 test1/form 이므로 폼을 통해 넘어올 경우
액션에 test1/join1이 아닌 join1만 써줘야한다.
안그럼 
http://localhost:8080/ex/test1/test1/join1?name=reqsa
과 같이 이동하므로 오류가 생긴다.


한글설정 하는법
src/main/webapp/WEB-INF/web.xml에 해당 코드를 추가한다.

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



request 요청을 통한 파라미터 객체생성 3가지
1. 직접 설정

@RequestMapping(value = "person/join1")
	public String view2(@RequestParam("id") String id,
			@RequestParam("pw") String pw,
			@RequestParam("name") String irum,
			@RequestParam("addr") String addr
			,Model model) {
		System.out.println(id);
		System.out.println(pw);
		System.out.println(irum);
		System.out.println(addr);
		
		PersonBean pb= new PersonBean();
		pb.setId(id);
		pb.setPw(pw);
		pb.setName(irum);
		pb.setAddr(addr);
		
		model.addAttribute("pb", pb);
		return "person/personView1";
	}


2. 자동 설정

@RequestMapping(value = "person/join2")
	public String view3(PersonBean pb) {
		//command 객체(자동으로 생성된 객체:setter까지 다 주입되어있다.)
		System.out.println(pb.getId());
		return "person/personView2";
	}


model.addAttribute("personBean", pb); 로 자동 설정되어 있다.
3. 자동 설정+별칭

@RequestMapping(value = "person/join3")
	public String view4(@ModelAttribute("pb") PersonBean pb) {
		//command 객체+별칭설정
		return "person/personView3";
	}


















'Develop > Spring MVC' 카테고리의 다른 글

0819 Spring Redirect AutoWired Valid  (0) 2022.08.22
0817 Spring Start  (0) 2022.08.22