JAVA

(java)Spring Frame Work MVC project

김만식이 2020. 10. 25. 18:29

스프링 MVC

 

구성요소

설명

DispatcharServlet

클라이언트 요형을 전달받는다. 컨트롤러에게 클라이언트의 요청을 전달하고 컨트롤러가 리턴할 결과값을 view에 전달하여 알맞은 응답을 생성하도록한다.

HandlerMapping

클라이언트의 요청 URL을 어떤 컨트롤러가 처리할지를 결정한다.

handlerAdapter

DispatcherServlet의 처리요청을 변환해서 컨트롤러에게 전달하고 컨트롤러의 응답 결과를

DispatcherServlet이 요구하는 형식으로 변환한다. 웹브라우저의 캐시등의 설정도 담당한다.

Controller

클라이언트의 요청을 처리한 뒤 결과를 리턴한다 응답 결과에서 보여줄 데이터를 모델에 담아 전달한다

ModelAndView

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

viewResolver

컨트롤러의 처리결과를 보여줄 뷰를 결정한다

View(jsp)

컨트롤러의 처리결과 화면을 생성한다. Jsp velocity 탬플릿 파일 등을 이용해서 클라이언트에 응답 결과를 전송한다.

순서는

Resquest -> dispatcherServlet -> HandlerMapping -> HandlerAdapter -> controller ->HandlerMapping (model and view로 변환하여 리턴)-> ->dispatcharServlet ->viewResolver

->view(jsp)

 

실질적인 처리는 dispatcharServlet 에서 처리해줌

 

mvc 프로젝트생성은 new에서 legacy project
mvc project 로 설정해주면 생성
위부분은 groupId 와 artifactId 를설정하는곳 

기본 홈화면설정

 

위와같이 /가 매핑되어있음 이부분이 실행시 홈이될 화면을맵핑해줌

일단 한글처리를 위해 

 <!-- 한글처리 -->
  <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>

을 web.xml에 추가해주고 저장해준다

 

여기로 이동하면
홈으로 이동하는 mapping이 있다 필자는 수정하여 개인정보를 출력하도록하겠다.(기본리턴은 home으로되어있다)이제 info을 보여줄view를 생성해주겠다

 

잠깐!!

위 servlet-context
여기서 매핑할 view 의 경로와 .jsp를 자동으로 잡아주기때문에 우리는 view(jsp)의 이름만 적어서 리턴하면 되는것이다  
view는 view 폴더에서 생성하면됨(필자는 하위폴더를 생성하여 만들었다)

 

 

<%@ 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>
<style>
h1{
text-align: center
}
div.position{
margin: 30px 400px
}
img{
border: 2px solid black;
border-radius: 30px 30px 30px 30px;
}
</style>
<body>
<h1 >Main Info</h1>
<div class="position">
<P>  The time on the server is ${serverTime}. </P>
<ul>
<li>이름:김민섭</li>
<li>나이:25</li>
<li>직업:개발자</li>
</ul>
<P><img src="./resources/img/KakaoTalk_20201023_134240792.jpg"></P>
</div>
</body>
</html>

info.jsp

 

 

사진을 넣는경로를 webapp/resources/img

프로젝트 실행시 메인출력이 해당과 같이 출력되는것을 확인할수 있다

 

다음은 Model , Model and View를 사용하여 데이터를 넘기는것을 하도록하겠다

	// model
	@RequestMapping("content")
    //메개로 model을불러와addAttribute로데이터를넘김
	public String content(Model model) {

		model.addAttribute("id", 30);

		return "list/reply";
	}

	// model and view
	@RequestMapping("reply")
	public ModelAndView reply() {
		//ModelAndView 객체호출하여 넘기는방식
        ModelAndView mv = new ModelAndView();

		mv.addObject("id", 30);
		mv.setViewName("list/reply");

		return mv;
	}

 

<%@ 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>
	<p>reply.jsp입니다</p>
	id:${id} 
	id :<%=request.getAttribute("id")%>
	
</body>
</html>

reply.jsp

 

model
model and view

이제 위를 이용하여 회원가입정보를 입력받아 출력하는것을 해보자

	@RequestMapping("join")
	public String join(Model model) {
		
		
		
		return "list/join";
	}

join page 매핑

 

<style>
a{
display: block;
font-weight: 900;
background-color: black;
width:10%;
height:40px;
color: white;
margin: 10px 130px; 
padding: 10px 150px;
}
</style>
<a href="./join">회원가입</a>

info에 join 이동링크추가

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>회원가입 페이지</title>
</head>
<form action="./msinfo3" method="post">
	
	<table border="1" style="border-collapse: collapse">
		<tr>
			<th colspan="2" bgcolor="skyblue">회원 기본 정보</th>
		</tr>
		<tr>
			<th>아이디:</th>
			<td><input type="text"  size="20" minlength="4" maxlength="12" name="userid"> 4~12자의 영문 대소문자와 숫자로만 입력</td>
		</tr>
		<tr>
			<th>비밀 번호:</th>
			<td><input type="password" id="pw" size="20" minlength="4" maxlength="12" name="userpass"> 4~12자의 영문 대소문자와 숫자로만 입력</td>
		</tr>
		<tr>
			<th>비밀 번호 확인:</th>
			<td><input type="password" id="pwchk" size="20" minlength="4" maxlength="12" name="passcheck"></td>
		</tr>
		<tr>
			<th>메일 주소:</th>
			<td><input type="email" id="mail" size="25" name="useremail"> 예)YoonEui@domain.com</td>
		</tr>
		<tr>
			<th>이름:</th>
			<td><input type="text" size="25"name="username"></td>
		</tr>
		<tr>
			<th colspan="2" bgcolor="skyblue">개인 신상 정보</th>
		</tr>
		<tr>
			<th>우편번호</th>
			<td>
				<input type="text"  placeholder="우편번호" name="address1">
				<input type="text"  placeholder="주소"  name="address2"><br>
				<input type="text"  placeholder="상세주소"  name="address3">
				<input type="text"  placeholder="참고항목"  name="address4">
			</td>
		</tr>
		<tr>
			<th>주민등록번호:</th>
			<td><input type="text" id="number1" size="10" name="number1"> - <input type="password" id="number2" size="10" name="number2"> 예) 123456 - 1234567
			</td>
		</tr>
		<tr>
			<th>생일:</th>
			<td><input type="text" id="year" size="10" name="year">년 <input type="text" id="month" size="5" name="month">월 <input type="text" id="day" size="5" name="day">일
			</td>
		</tr>
		<tr>
			<th>관심 분야:</th>
			<td>
				<input type="checkbox" name="chk" value="computer">컴퓨터
				<input type="checkbox" name="chk" value="internet">인터넷 
				<input type="checkbox" name="chk" value="play">여행 
				<input type="checkbox" name="chk" value="movie">영화감상 
				<input type="checkbox" name="chk" value="music">음악감상</td>
		</tr>
		<tr>
			<th>자기 소개:</th>
			<td><textarea id="my_intro" cols="60" rows="10" name="my_intro"></textarea></td>
		</tr>
	</table>
<pre>
				<input type="submit"  value="회원 가입" > <input type="reset" value="다시 입력">
</pre>
</form>
</head>
</html>

join.jsp

 

	@RequestMapping("msinfo1")
	public String TestInfo1(JoinMember joinMember) {
		
		return "list/msinfo";
	}
	
	@RequestMapping("msinfo2")
	public String TestInfo2(
			@RequestParam("userid") String userid,
			@RequestParam("userpass") String userpass,
			@RequestParam("passcheck") String passcheck,
			@RequestParam("useremail") String useremail,
			@RequestParam("username") String username,
			@RequestParam("address1") String address1, 
			@RequestParam("address2") String address2,
			@RequestParam("address3") String address3, 
			@RequestParam("number1") String number1,
			@RequestParam("number2") String number2, 
			@RequestParam("year") String year,
			@RequestParam("month") String month, 
			@RequestParam("day") String day, 
			@RequestParam("chk") String chk,
			@RequestParam("my_intro") String my_intro,
			Model model) {
		
		JoinMember join =new JoinMember() ;
		
		join.setUserid(userid);
		join.setUserpass(userpass);
		join.setPasscheck(passcheck);
		join.setUseremail(useremail);
		join.setUsername(username);
		join.setAddress1(address1);
		join.setAddress2(address2);
		join.setAddress3(address3);
		join.setNumber1(number1);
		join.setNumber2(number2);
		join.setAddress1(address1);
		join.setAddress2(address2);
		join.setAddress3(address3);
		join.setYear(year);
		join.setMonth(month);
		join.setDay(day);
		join.setChk(chk);
		join.setMy_intro(my_intro);
		model.addAttribute(join);
		
		return "list/msinfo";
	}
	@RequestMapping("msinfo3")
	public String msinfo3(
			HttpServletRequest request,
		    Model model) {
	request.getParameter("year");
	request.getParameter("month");
	request.getParameter("day");
	request.getParameter("chk");
	request.getParameter("my_intro");
	
	JoinMember join =new JoinMember() ;
	
	join.setUserid(request.getParameter("userid"));
	join.setUserpass(request.getParameter("userpass"));
	join.setPasscheck(request.getParameter("passcheck"));
	join.setUseremail(request.getParameter("useremail"));
	join.setUsername(request.getParameter("username"));
	join.setAddress1(request.getParameter("address1"));
	join.setAddress2(request.getParameter("address2"));
	join.setAddress3(request.getParameter("address3"));
	join.setNumber1(request.getParameter("number1"));
	join.setNumber2(request.getParameter("number2"));
	join.setYear(request.getParameter("year"));
	join.setMonth(request.getParameter("month"));
	join.setDay(request.getParameter("day"));
	join.setChk(request.getParameter("chk"));
	join.setMy_intro(request.getParameter("my_intro"));
	model.addAttribute(join);
	
	return "list/msinfo";
	}

package com.javax.ex.member;


public class JoinMember {
	private String userid;
	private String userpass;
	private String passcheck;
	private String useremail;
	private String username;
	private String address1;
	private String address2;
	private String address3;
	private String number1; // 주민 앞자리
	private String number2; // 주민 뒷자리
	private String year;
	private String month;
	private String day;
	private String chk;
	private String my_intro;

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getUserpass() {
		return userpass;
	}

	public void setUserpass(String userpass) {
		this.userpass = userpass;
	}

	public String getPasscheck() {
		return passcheck;
	}

	public void setPasscheck(String passcheck) {
		this.passcheck = passcheck;
	}

	public String getUseremail() {
		return useremail;
	}

	public void setUseremail(String useremail) {
		this.useremail = useremail;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getAddress1() {
		return address1;
	}

	public void setAddress1(String address1) {
		this.address1 = address1;
	}

	public String getAddress2() {
		return address2;
	}

	public void setAddress2(String address2) {
		this.address2 = address2;
	}

	public String getAddress3() {
		return address3;
	}

	public void setAddress3(String address3) {
		this.address3 = address3;
	}

	public String getNumber1() {
		return number1;
	}

	public void setNumber1(String number1) {
		this.number1 = number1;
	}

	public String getNumber2() {
		return number2;
	}

	public void setNumber2(String number2) {
		this.number2 = number2;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public String getDay() {
		return day;
	}

	public void setDay(String day) {
		this.day = day;
	}

	public String getChk() {
		return chk;
	}

	public void setChk(String chk) {
		this.chk = chk;
	}

	public String getMy_intro() {
		return my_intro;
	}

	public void setMy_intro(String my_intro) {
		this.my_intro = my_intro;
	}



}

  getter , setter

<%@ 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>
	<div>
	<ul>
	<li>아이디 : ${joinMember.userid}</li>
  	<li>비밀번호 : ${joinMember.userpass}</li>
	<li>비밀번호확인 : ${joinMember.passcheck}</li>
	<li>메일주소 : ${joinMember.useremail}</li>
	<li>이름 : ${joinMember.username}</li>
	<li>우편번호 : ${joinMember.address1} ${joinMember.address2} ${joinMember.address3} </li>
	<li>주민등록번호 : ${member.number1} - ${joinMember.number2}</li>
	<li>생일 : ${joinMember.year}년 ${joinMember.month}월 ${joinMember.day}일</li>
	<li>관심분야 : ${joinMember.chk}</li>
	<li>자기소개 : ${joinMember.my_intro}</li>  
	</ul>
	</div>
	
</body>
</html>

출력부

 

 

 

 

 

msinfo3

 

 

msinfo2

 

msinfo1