Category Archives: Spring

spring4 transaction 설정

spring4 transaction 설정

http://roqkffhwk.tistory.com/112

http://addio3305.tistory.com/86

http://ande226.tistory.com/105

Advertisements

[Spring] Kind of Controller

Spring kind of controller

Purpose Class(Interface) Description
Simple Process Controller
AbstractController
you do to implement required feature
parameter mapping AbstractCommandController Save request parameter to object and validate it
Process input form SimpleFormController Print form and process input data
Process multi page input form AbstractWizardFormController input data through multi page
Controll input form’s flow and process input data
Mapping static view ParameterizableViewController

UrlFilenameViewController

Not process any function in controller, simply
pass client’s request to view
Multi action MultiActionController process relation function or logic in one controller

[Spring MVC] example

Spring MVC Example

download

Ref: http://snoopy81.tistory.com/241

c.f. rename attached file extention to 7z

We show Spring MVC example. From this, you will know how to make spring mvc code.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>myHome</display-name>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
<servlet-name>myHome01</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>myHome01</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

</web-app>

Description

8: define listener for web application

13~14: you can define context configuration file like them.

19~21: define servlet for myHome01. ‘load-on-startup’ tag means loading at startup time not request time. Nomally this does when the servlet is heavy, so response fastly at requesting.

24~27: defne servlet mapping. *.html url request go to myHome01 servelet. and myHome1 servlet process this request.

myHome01-servlet.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.xsd">

	<!-- HandlerMapping-->
	<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/board.html">indexController</prop>
				<prop key="/detail.html">detailController</prop>
			</props>
		</property>
	</bean>

	<!-- ViewResolver-->
	<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

	<!-- bean -->
	<bean id="indexController" class="controller.IndexController">
		<property name="board" ref="board"></property>
	</bean>

	<bean id="detailController" class="controller.DetailController">
		<property name="board" ref="board"></property>
	</bean>

	<bean id="board" class="logic.BoardImpl">
		<property name="boardDao" ref="boardDao"></property>
	</bean>

	<bean id="boardDao" class="dao.BoardDaoImpl">
		<property name="sqlMapClient" ref="sqlMapClient"></property>
	</bean>

</beans>

*SimpleUrlHanderMapping Class
-mapping request url to controller

*InternalResourceViewResolver Class
-Set viewClass, prefix, suffix properties
-viewClass: Define class that implement view interface
==>JstlView class: support JSP page using JSTL

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
	<settings useStatementNamespaces="true"/>
<sqlMap resource="../classes/sql/oracle/board.xml"/>
</sqlMapConfig>

* for using iBatis

board.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="board">

	<select id="getBoardList" resultClass="vo.BoardVO">
		SELECT 	BOARD_IDX 						AS BOARDIDX,
				BOARD_SEQ 						AS BOARDSEQ,
				BOARD_TYPE 						AS BOARDTYPE,
				STEP							AS STEP,
				TITLE							AS TITLE,
				CONTENT							AS CONTENT,
				TO_CHAR(REGI_DT, 'YYYY-MM-DD') 	AS REGIDT,
				REGI_USER 						AS REGIUSER,
				TO_CHAR(MODI_DT, 'YYYY-MM-DD') 	AS MODIDT,
				MODI_USER 						AS MODIUSER
		FROM 	BOARD
		ORDER BY BOARD_IDX DESC, BOARD_SEQ DESC
	</select>

		<select id="getBoardDetail" parameterClass="int" resultClass="vo.BoardVO">
		SELECT 	BOARD_IDX 						AS BOARDIDX,
				BOARD_SEQ 						AS BOARDSEQ,
				BOARD_TYPE 						AS BOARDTYPE,
				STEP							AS STEP,
				TITLE							AS TITLE,
				CONTENT							AS CONTENT,
				TO_CHAR(REGI_DT, 'YYYY-MM-DD') 	AS REGIDT,
				REGI_USER 						AS REGIUSER,
				TO_CHAR(MODI_DT, 'YYYY-MM-DD') 	AS MODIDT,
				MODI_USER 						AS MODIUSER
		FROM 	BOARD
		WHERE 	BOARD_IDX = #value#
	</select>

</sqlMap>

 

board.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>BOARD LIST</title>

<script type="text/javascript">
	function goDetail(board_idx){
		var doc = document.boardForm;
		doc.boardIdx.value = board_idx;
		//alert(board_idx);
		doc.action = "./detail.html";
		doc.submit();
	}
</script>

</head>
<body>
<form name="boardForm">
	<input type="hidden" name="boardIdx" value=""/>
	<table border="1">
		<tr>
			<th width="50">No.</th>
			<th width="400">제목</th>
			<th width="100">등록일</th>
			<th width="100">등록자</th>
		</tr>
	<c:forEach items="${boardList}" var="board">
		<tr>
			<td align="center"> <c:out value="${board.boardIdx}"></c:out> </td>
			<td align="left" onclick="goDetail('<c:out value="${board.boardIdx}"></c:out>')"> <c:out value="${board.title}"></c:out> </td>
			<td align="center"> <c:out value="${board.regiDt}"></c:out> </td>
			<td align="center"> <c:out value="${board.regiUser}"></c:out> </td>
		</tr>
	</c:forEach>
	</table>
</form>
</body>
</html>

detail.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>BOARD LIST</title>
</head>
<body>

	<table border="1">
		<tr>
			<th width="50">No.</th>
			<th width="400">제목</th>
			<th width="100">등록일</th>
			<th width="100">등록자</th>
		</tr>

		<tr>
			<td align="center"> <c:out value="${boardDetail.boardIdx}"></c:out> </td>
			<td align="left"> <c:out value="${boardDetail.title}"></c:out> </td>
			<td align="center"> <c:out value="${boardDetail.regiDt}"></c:out> </td>
			<td align="center"> <c:out value="${boardDetail.regiUser}"></c:out> </td>
		</tr>

	</table>

	<input type="button" value=" list " onclick="window.location='board.html'" />

</body>
</html>

[Spring] RestTemplate

Spring 3.0부터는 REST client를 쉽게 구현케 할 수 있는 RestTemplate이 도입되었다.

Main Method

HTTP method RestTemplate methods
DELETE delete(java.lang.String, java.lang.Object...)
GET getForObject(java.lang.String, java.lang.Class, java.lang.Object...)
getForEntity(java.lang.String, java.lang.Class, java.lang.Object...)
HEAD headForHeaders(java.lang.String, java.lang.Object...)
OPTIONS optionsForAllow(java.lang.String, java.lang.Object...)
POST postForLocation(java.lang.String, java.lang.Object, java.lang.Object...)
postForObject(java.lang.String, java.lang.Object, java.lang.Class, java.lang.Object...)
PUT put(java.lang.String, java.lang.Object, java.lang.Object...)
any exchange(java.lang.String, org.springframework.http.HttpMethod, org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object...)
execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor, java.lang.Object...)

Get Method

String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", 
String.class,"42", "21");

Post Method

String postUrl = url + “/login”;
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add(“username”, user);
map.add(“password”, password);
String result = restTemplate.postForObject(postUrl, map, String.class);

Post Method – how to  modify header and body

String reqUrl = Url + “/search”;

HttpHeaders headers = new HttpHeaders();
headers.add(“Authorization”, sessionKey);

MultiValueMap<String, String> postParams = new LinkedMultiValueMap<String, String>();
postParams.add(“search”, searchKey);  //body 조작

HttpEntity<MultiValueMap<String, String>> requestEntity
= new HttpEntity<MultiValueMap<String, String>>(postParams, headers);

result = restTemplate.exchange(reqUrl , HttpMethod.POST, requestEntity,    String.class).getBody();

Async Post

using execute – implement third parameter- RequestCallback, 4th – ResponseExtractor

then, called ResponseExtractor’s extractData method asynclonously.

//RequestCallback – doWithRequest  implemementation

static class RestRequestCallBack implements RequestCallback {

private String sessionKey;
private String searchKey;

private RestRequestCallBack(String sessionKey, String searchKey){
this.sessionKey = sessionKey;
this.searchKey = searchKey;

}
public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
HttpHeaders request = clientHttpRequest.getHeaders();

request.add(“Authorization”, sessionKey);

request.add( “Accept”, “application/json” );

String search = “search=”+ searchKey;
byte searchbyte[] = search.getBytes();
clientHttpRequest.getBody().write(searchbyte, 0, searchbyte.length);
}
}
//ResponseExtractor -extractData  implemementation
private static class FileResponseExtractor implements ResponseExtractor<Object>
{
private final File file;
private       File file () { return this.file; }

private FileResponseExtractor ( File file )
{
this.file = file;
}

@Override
public Object extractData ( ClientHttpResponse response ) throws IOException
{
InputStream  is = response.getBody();
OutputStream os = new BufferedOutputStream( new FileOutputStream( file()));

IOUtils.copyLarge( is, os );
IOUtils.closeQuietly( is );
IOUtils.closeQuietly( os );

return null;
}
}

public String searchAsync(String sessionKey, String searchKey) {

Object result = null;

String reqUrl = Url + “/search”;

String downloadDir = “D:\\”;
String fileName = “mysearch.log”;
try {
result = restTemplate.execute(reqUrl,
HttpMethod.POST,
new RestRequestCallBack(sessionKey, searchKey),
new FileResponseExtractor( new File( downloadDir, fileName )));

} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();

}

return null;
}

—— execute test code async code——-
searchKey = “http 80”;
sessionKey = client.getSession(user, password);
client.searchAsync(sessionKey, searchKey);

HTTP method RestTemplate methods
DELETE delete(java.lang.String, java.lang.Object...)
GET getForObject(java.lang.String, java.lang.Class, java.lang.Object...)
getForEntity(java.lang.String, java.lang.Class, java.lang.Object...)
HEAD headForHeaders(java.lang.String, java.lang.Object...)
OPTIONS optionsForAllow(java.lang.String, java.lang.Object...)
POST postForLocation(java.lang.String, java.lang.Object, java.lang.Object...)
postForObject(java.lang.String, java.lang.Object, java.lang.Class, java.lang.Object...)
PUT put(java.lang.String, java.lang.Object, java.lang.Object...)
any exchange(java.lang.String, org.springframework.http.HttpMethod, org.springframework.http.HttpEntity, java.lang.Class, java.lang.Object...)
execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor, java.lang.Object...)

 

[Spring] Start Spring

class작성, bean 작성 법에 대해 친절히 나와 있다.

아래 사이트를 참고한다.

http://wiki.dev.daewoobrenic.co.kr/mediawiki/index.php/EDU_USER_DEV

 

개발 화면

사용자 등록 사용자 수정 사용자 상세보기 사용자 목록보기

[편집] 개발 순서

[편집] MODEL

  • MODEL 클래스 작성, JavaBeans 스펙에 맞게 getter/setter 작성.

[편집] SQL(SQLMAP XML)

  • SQL 문이 담긴 XML 파일 작성하고, SQL CONFIG XML(sqlmap-config.xml) 파일에 정의

[편집] DAO

  • XML에 있는 statement 호출하는 DAO 클래스 작성
  • JCF의 BaseSqlMapClientDao 상속받도록 작성.
  • executeQueryForObject / executeQueryForList / executeUpdate
  • Spring Context XML에 DAO 모듈 정의.(SqlMapClient를 프라퍼티로 가지도록 함.)

[편집] SERVICE

  • Service 클래스 작성하여 비즈니스 로직 구현
  • 호출하는 DAO 모듈을 맴버 프라퍼티로 두고 setter 메소드 구현.
  • Spring Context XML에 작성된 SERVICE 모듈 정의.(DAO 모듈을 프라퍼티로 가지도록 함.)

[편집] ACTION

  • Action 클래스 작성
  • 호출하는 SERVICE 모듈을 맴버 프라퍼티로 두고 setter 메소드 구현.
  • STRUTS XML(struts.xml) 파일에 액션 정의.

[편집] JSP

  • 화면 작성.(< s:property>, < s:iterator>, < s:textfield>, < s:select>)

 

[편집] 테이블 스키마

  • 사용자 아이디와 이름, 주소 값을 가지는 테이블 작성(오라클 기준, HSQLDB는 VARCHAR2를 VARCHAR로 변경.)
CREATE TABLE USERS(
	ID VARCHAR2(20) PRIMARY KEY,
	NAME VARCHAR2(20),
	ADDRESS VARCHAR2(50)
)

[편집] 모델의 작성

  • 모델 클래스를 만들고 attribute 선언(attribute는 private 변수 선언)
  • getter/setter 메소드를 구현(JavaBeans 스펙 기준)
public class User {
	private String id;
	private String name;
	private String address;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

[편집] SQL작성(SQL MAP XML)

  • User.XML 파일 생성하고 ibatis의 statement를 작성.
  • < typeAlias /> 를 사용하여 모델클래스의 별칭으로 사용(선택사항).
  • < resultMap /> 을 사용하여 DB 컬럼과 모델클래스 프라퍼티간의 이름 및 타입 매핑(선택사항).
  • QUERY의 파라미터로 전달된 값은 #를 사용하여 참조(예 : #name# ).
<sqlMap namespace="user">			
	<typeAlias alias="user" type="sample.user.model.User"/>

	<resultMap id="user-resultMap" class="user" >
		<result property="id" column="id"/>
		<result property="name" column="name"/>
    		<result property="address" column="address"/>	
	</resultMap>	

	<statement id="createUser" parameterClass="user" >
		INSERT INTO USERS( id, name, address) VALUES(#id#, #name#, #address#)
	</statement>

	<statement id="findUser" parameterClass="string" resultMap="user-resultMap" >
		SELECT id, name, address FROM USERS WHERE id = #id#
	</statement>

	<statement id="findUsers" resultMap="user-resultMap" >
		SELECT  id, name, address FROM USERS
	</statement>	

	<statement id="updateUser" parameterClass="user">
		UPDATE USERS SET name = #name#, address =#address# WHERE id = #id#
	</statement>

	<statement id="deleteUser" parameterClass="string">
		DELETE FROM USERS WHERE id = #id#
	</statement>		
</sqlMap>
  • 작성된 SQLMAP XML 파일은 SQLMAP CONFIG XML 파일에 정의해준다.
<sqlMapConfig>
	<settings cacheModelsEnabled="true" />

	<sqlMap resource="sample/user/dao/sqlmap/User.xml" />
</sqlMapConfig>

[편집] DAO 작성

  • jcf.dao.ibatis.BaseSqlMapClientDAO 상속(인터페이스 구현은 선택).
  • executeUpdate(String statementId, Object param)
    • INSERT/UPDATE/DELETE 등 DML 문 QUERY에 사용
    • statementId는 SQLMAP에 작성된 statment의 ID를 지칭하며, 실행항 QUERY를 지정.
    • param은 생행할 QUERY에서 사용할 파라미터(없는 경우 null을 넘겨준다).
  • executeQueryForObject(String statementId, Object param)
    • SELECT 문 실행시 사용하며, 한건의 결과만 가져올 때 사용.
  • executeQueryForObject(String statementId, Object param)
    • SELECT 문 실행시 사용하며, 한건 이상의 결과를 가져올 때 사용.
public class UserDaoImpl extends BaseSqlMapClientDAO implements UserDao {

	public void createUser(User user) {
		executeUpdate("createUser", user);
	}

	public User findUser(String id) {
		User user = (User) executeQueryForObject("findUser", id);
		return user;
	}

	public List findUsers() {
		List usecaseList = executeQueryForList("findUsers", null);
		return usecaseList;
	}

	public void updateUser(User user) {
		executeUpdate("updateUser", user);
	}

	public void deleteUser(String id) {
		executeUpdate("deleteUser", id);
	}

	public List findUsers(HashMap searchCondition) {
		List list = executeQueryForList("findUsers", null);
		return list;
	}
}
  • 작성된 DAO 클래스는 Spring 프레임워크에 빈정의를 해둔다.(applicationContext-user.xml)
  • 이때 SQLMAP CLIENT(sqlMapClient)를 프라퍼티로 가지도록 설정한다.
<beans ..>
	<bean id="userDao" class="sample.user.dao.UserDaoImpl">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>
</beans>

[편집] SERVICE 개발

  • 서비스 클래스를 만들고, 비즈니스 메소드를 구현한다.
  • 호출할 USER DAO를 맴버 프라퍼티로 선언하고 setter 메소드를 구현한다.
public class UserServiceImpl implements UserService {

	private UserDao userDao;

	public void setUserDao(UserDao dao) { this.userDao = dao; }

	public void createUser(User user) {
		userDao.createUser(user);
	}

	public List findUsers() {
		return userDao.findUsers();
	}

	public User findUser(String userId) {
		User user = userDao.findUser(userId);
		return user;
	}

	public void deleteUser(String userId) {
		userDao.deleteUser(userId);
	}

	public void updateUser(User user) {
		userDao.updateUser(user);
	}
}
  • 작성된 SERVICE 클래스는 Spring 프레임워크에 빈정의를 추가한다.(applicationContext-user.xml)
  • 이때 DI(Dependency Injection)할 dao(UserDao)를 프라퍼티로 가지도록 설정한다.
  • < property 태그의 name 속성은 SERVICE 클래스의 맴버 변수이름이고, ref는 참조할 dao 클래스 빈 정의의 id(혹은 name)이다.
<beans ..>
	<bean id="userService" class="sample.user.service.UserServiceImpl">
		<property name="userDao" ref="userDao" />
	</bean>

	<bean id="userDao" class="sample.user.dao.UserDaoImpl">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>
</beans>

[편집] ACTION 작성

  • jcf.web.struts2.action.BaseAction을 상속한다.
  • UI로 부터 파라미터로 받거나, UI로 전달할 객체들을 맴버 프라퍼티로 선언하고 getter/setter를 만든다.
  • 호출할 SERVICE 클래스들을 맴버 프라퍼티로 선언하고 setter 메소드를 만든다.
public class UserAction extends BaseAction {
	/* ******************************** PROPERTIES ******************************* */
	private User user;
	private List userList;

	private UserService userService;

	/* ******************************** ACTION METHODS ******************************* */
	public String addUser() {
		return SUCCESS;
	}

	public String saveUser() {
		User checkUser = userService.findUser(user.getId());
		if (checkUser == null)
			userService.createUser(user);
		else
			userService.updateUser(user);

		return SUCCESS;
	}

	public String findUser() {
		user = userService.findUser(user.getId());
		return SUCCESS;
	}

	public String findUsers() {
		userList = userService.findUsers();
		return SUCCESS;
	}

	public String deleteUser() {
		userService.deleteUser(user.getId());
		return SUCCESS;
	}

	/* ******************************** GETTER & SETTER ******************************* */
	public User getUser() {return user;}

	public void setUser(User user) {this.user = user;}

	public List getUserList() {return userList;}

	public void setUserList(List userList) {this.userList = userList;}

	public UserService getUserService() {return userService;}

	public void setUserService(UserService userService) {this.userService = userService;}
  • 작성된 액션 클래스의 액션 메소드에 대한 STRUTS XML 파일을 작성한다.(struts-user.xml)
  • 패키지의 이름/상속/네임스페이스를 조심해서 작성한다.
    • 패키지 명은 유일해야 한다.
    • 기본적으로 srtust-default를 상속하도록 한다.
    • 네임스페이스는 유일할 필요는 없지만, 액션 호출 URL에 영향을 미치므로 기본적으로 패키지 명과 동일하게 준다.
<struts>
	<package name="user" extends="struts-default" namespace="/user">
		<action name="addUser" class="sample.user.action.UserAction" method="addUser">
			<result>/public/user/editUser.jsp</result>
		</action>

		<action name="saveUser" class="sample.user.action.UserAction" method="saveUser">
			<result type="chain">findUsers</result>
		</action>

		<action name="findUser" class="sample.user.action.UserAction" method="findUser">
			<result>/public/user/findUser.jsp</result>
		</action>

		<action name="editUser" class="sample.user.action.UserAction" method="findUser">
			<result>/public/user/editUser.jsp</result>
		</action>

		<action name="findUsers" class="sample.user.action.UserAction" method="findUsers">
			<result>/public/user/findUsers.jsp</result>
		</action>

		<action name="deleteUser" class="sample.user.action.UserAction" method="deleteUser">
			<result type="redirect">/user/findUsers.action</result>
		</action>
	</package>

</struts>

[편집] JSP 작성

[편집] 작성/편집 화면(editUser.jsp)

  • 스트럿츠 2 태그를 사용하기 위해서 taglib 작성한다.
  • < s:property value=“변수”/> : 변수는 액션 클래스에서 맴버 프라퍼티로 가지고 있는 객체이다.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<link rel='stylesheet' href='<%= request.getContextPath() %>/css/style.css'>
<s:head theme='simple' />
<SCRIPT language='JavaScript' type='text/javascript'>
	function submit()
	{
		document.userForm.submit();
		return; 
	}
	</SCRIPT>
</head>
<body>
<h1>사용자 생성/수정</h1>
<s:form name='userForm' action='saveUser' theme='simple'>
	<table cellpadding='3' cellspacing='0' border='1'>
		<tr>
			<td width='100' align='left'>아이디</td>
			<td width='200'><s:textfield name='user.id' /></td>
		</tr>
		<tr>
			<td width='100' align='left'>이름</td>
			<td width='200'><s:textfield name='user.name' /></td>
		</tr>
		<tr>
			<td width='100' align='left'>주소</td>
			<td width='200'><select name="user.address">
				<option value="seoul">SEOUL</option>
				<option value="inchen">INCHEN</option>
				<option value="pusan">PUSAN</option>
			</select></td>
		</tr>
	</table>
</s:form>
<a href='javascript:submit()'>저장</a>
<a href='<%= request.getContextPath() %>/user/findUsers.action'>목록</a>
</body>
</html>

[편집] 리스트 화면(findUsers.jsp)

  • 스트럿츠 2 태그를 사용하기 위해서 taglib 작성한다.
  • < s:iterator value=“리스트형 변수”/> : 리스트의 개수만큼 반복 처리.
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@taglib uri="/WEB-INF/tld/app.tld" prefix="app" %>
<html>
<head>
<link rel='stylesheet' href='<%= request.getContextPath() %>/css/style.css'>
</head>

<body>
<h1>사용자 조회</h1>
<table cellpadding="3" cellspacing="0" border="1" width="250">
    <tr>
        <td align="center">아이디</td>
        <td align="center">이름</td>
        <td align="center">주소</td>    
    </tr>

    <s:iterator value="userList">
        <tr>
            <td>
                <a href="<s:url action="findUser"><s:param name="user.id" value="id"/></s:url>">
                      <s:property value="id"/>
                </a>
            </td>
            <td><s:property value="name"/></td>  
       <td><s:property value="address"/></td>

        </tr>
    </s:iterator>
</table>
<br/>
<a href="<%= request.getContextPath() %>/user/addUser.action">등록</a>
</body>
</html>

[편집] 상세 조회 화면(findUser.jsp)

  • 스트럿츠 2 태그를 사용하기 위해서 taglib 작성한다.
  • < s:textfield name=“parameter 변수명”/>
    • 변수값이 있으면 자동으로 값을 뿌려주고 없는 경우 공란으로 처리
    • 이 값은 submit 되는 순간 해당 모델의 attribute에 동일 이름에 값을 set 하게 된다.
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head><link rel='stylesheet' href='<%= request.getContextPath() %>/css/style.css'></head>

<body>
<h1>사용자 정보</h1>
<table cellpadding="3" cellspacing="0" border="1">
		<tr>
			<td width=100 align="left">아이디</td>
			<td width=200><s:property value="user.id"/></td>
		</tr>
		<tr>
			<td width=100 align="left">이름</td>
			<td width=200><s:property value="user.name"/></td>
		</tr>		  
		<tr>
			<td width=100 align="left">주소</td>
			<td width=200><s:property value="user.address"/></td>
		</tr>		
</table>
<br/>

<a href="<%= request.getContextPath() %>/user/editUser.action?user.id=${user.id}">
수정</a>&nbsp;&nbsp;&nbsp;
<a href="<%= request.getContextPath() %>/user/findUsers.action">목록</a>&nbsp;&nbsp;&nbsp;
<a href="<%= request.getContextPath() %>/user/deleteUser.action?user.id=${user.id}">삭제</a>
</body>
</html>