1.게시판에 사용될 테이블 만들기



_M#]



2.게시판 프로젝트 시작하기



3.게시판 리스트를 위한 프로그래밍



4.게시물 쓰기


5.게시물 상세보기


06.게시물 수정하기


07.게시물 삭제하기



08.예외 처리 페이지







action/ListAtion.java

package action; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import model.User; import conn.Ibatis; public class ListAction { List<User> list; public String execute(){ Ibatis ibatis=new Ibatis(); try { //db에서 모든 글을 가져오기 list=ibatis.sqlMapper.queryForList("selectAllUsers"); //select하기 ? Map<String, String> map=new HashMap<String, String>(); map.put("USER_ID", "^^"); //list=ibatis.sqlMapper.queryForList("select", map); // 지우기 ibatis.sqlMapper.delete("delete", map); } catch (SQLException e) { System.out.println(e.getMessage()); } return "success"; } public List<User> getList() { return list; // <s:iterater value="list">로 호출할 것이 } }



conn/Ibatis.java
package conn;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.User;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class Ibatis {
	public static SqlMapClient sqlMapper;	
	static {
		try {
			//sqlMapConfig.xml 파일의 설정내용을 가져온다.
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			//sqlMapConfig.xml의 내용을 적용한 sqlMapper 객체 생성.
			sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close(); 
		} catch (IOException e) {
			throw new RuntimeException(
					"SqlMapClient 인스턴스 생성시 예외발생." + e, e);
		}
	}   
}

model/User.java
package model;

public class User {
	private String userId;  
	private String userPW;
	private String userName;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserPW() {
		return userPW;
	}
	public void setUserPW(String userPW) {
		this.userPW = userPW;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	@Override
	public String toString() {
		String result;
		result=String.format("[User:ID=%s,Password=%s,Name=%s]", 
				userId, userPW, userName);
		return result;
	}
}


test/UserTest.java
package test;

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import model.User;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class UserTest {
	private static SqlMapClient sqlMapper;
	static List<User> list;
	static {
		try {
			//sqlMapConfig.xml 파일의 설정내용을 가져온다.
			Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			//sqlMapConfig.xml의 내용을 적용한 sqlMapper 객체 생성.
			sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
			reader.close(); 
		} catch (IOException e) {
			throw new RuntimeException(
					"SqlMapClient 인스턴스 생성시 예외발생." + e, e);
		}
	}   

	public static List<User> getList() {
		return list;   //${list}  <s:property value="list"> <s:iterator 로 화면에 출력
	}
}


13-1.sql
create table if not exists user(
  USER_ID varchar(20) primary key,
  USER_PW varchar(20),
  USER_NAME varchar(20)
);
insert into user value('^^', 'pppp1111', 'Hong');
insert into user value('-_-', '1111pppp', 'Min');
commit;
insert into user (USER_ID, USER_PW, USER_NAME )
 values ('pinksubean', 'pppp1111', 'park');
insert into user (USER_ID, USER_PW, USER_NAME )
 values ('pinkonejee', '1111pppp', 'kim');
SqlMapConfig.xml
<?xml version="1.0" encoding="euc-kr" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" 
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>

  <properties resource="dbconnect.properties" />

  <settings 
    useStatementNamespaces="false"
    cacheModelsEnabled="true" 
    enhancementEnabled="true"
    lazyLoadingEnabled="true" 
    maxRequests="32" 
    maxSessions="10" 
    maxTransactions="5" 
    />

  <transactionManager type="JDBC">
    <dataSource type="DBCP">
      <property name="JDBC.Driver" value="${driver}" />
      <property name="JDBC.ConnectionURL" value="${url}" />
      <property name="JDBC.Username" value="${username}" />
      <property name="JDBC.Password" value="${password}" />
      <property name="JDBC.DefaultAutoCommit" value="false" />
    </dataSource>
  </transactionManager>

   <sqlMap resource="User.xml" />
</sqlMapConfig> 
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <constant name="struts.i18n.encoding" value="UTF-8" />
  <constant name="struts.devMode" value="true" />
  
  <package name="ch12"  extends="struts-default">

	
	<action name="List" class="action.ListAction">
		<result>list.jsp</result>
	</action>

   </package>    
</struts>

User.xml
<?xml version="1.0" encoding="euc-kr" ?>

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

<sqlMap namespace="User">
  <!--  전화번호부 테이블 DATA0=(user_name) DATA1 DATA2 -->
  <!-- 리절트 맵 정의 -->
  <resultMap id="UserResult" class="model.User">
    <result property="userId" column="USER_ID"/>
    <result property="userPW" column="USER_PW"/>
    <result property="userName" column="USER_NAME"/>
  </resultMap>
  
  <!-- select 쿼리문 정의 -->
  <select id="selectAllUsers" resultMap="UserResult">
    select * from USER
  </select>
   <!-- 상세 내용 보기 -->
     <select id="select" parameterClass="java.util.Map"
             resultMap="UserResult">
             select * from USER where USER_ID=#USER_ID#
     </select>
  
    <!--  글 지우기  -->
  	<delete id="delete" parameterClass="java.util.Map">
  		delete  from USER where USER_ID=#USER_ID#
  	</delete>
  	
  	<!--  글 수정하기 -->
  	<update id="update" parameterClass="java.util.Map">
  		update USER (USER_PW, USER_NAME  ) 
  		set ( #USER_PW#, #USER_NAME#  ) where USER_ID=#USER_ID#
  	</update>
</sqlMap>

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>아이바티스 공부</display-name>
 
    
  <filter>
  <filter-name>struts2</filter-name>
  <filter-class>
  org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>
   <init-param> 
     <param-name>struts.i18n.encoding</param-name>
     <param-value>euc-kr</param-value>
  </init-param> 
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-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>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!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>
	게시글 목록 <br/>
	<s:iterator value="list">
		<s:property value="userId"/> / 
		<s:property value="userPW"/> /
		<s:property value="userName" />		<hr/>  
	</s:iterator> <br/> 
	private String userId;  
	private String userPW;
	private String userName;
</body>
</html>




스프링 라이브러리 다운 받기

http://www.springsource.org/download






action/UserRegAction4.java
package action;

import model.User;
import dao.UserDao;
import com.opensymphony.xwork2.ActionSupport;

public class UserRegAction4 extends ActionSupport {
	private User user=new User();	
	private UserDao userDao;
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}		
	
	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	@Override
	public String execute() throws Exception {
		//userDao=new UserDao();
		// 객체 생성을 spring 이 해주었다. 
		userDao.create(user);
		return SUCCESS;
	}
}


dao/UserDao.java
package dao;

import model.User;

public class UserDao {
	public void create(User user){
		System.out.println("사용자를 추가했습니다.");
		System.out.println("추가된 사용자의 정보");
		System.out.println(user);
	}
}

model/User.java
package model;

public class User {
	private String userId;  
	private String userPW;
	private String userName;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getUserPW() {
		return userPW;
	}
	public void setUserPW(String userPW) {
		this.userPW = userPW;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	@Override
	public String toString() {
		String result;
		result=String.format("[User:ID=%s,Password=%s,Name=%s]", 
				userId, userPW, userName);
		return result;
	}
}

struts.properties
struts.i18n.reload=true
struts.devMode=true
struts.configuration.xml.reload=true
struts.objectFactory=org.apache.struts2.spring.StrutsSpringObjectFactory
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
  <constant name="struts.i18n.encoding" value="UTF-8" />
  <constant name="struts.devMode" value="true" />
  
  <package name="ch12"  extends="struts-default">

    <action name="userRegForm">
      <result>/jsp/userRegForm4.jsp</result>
    </action>  
    
    <!--  spring 적용된 userRegAction4  -->
    <action name="userRegAction" class="userRegAction4"> 
      <result name="input">/jsp/userRegForm4.jsp</result>  
      <result name="success">/jsp/userRegSuccess4.jsp</result>
    </action>
   </package>    
</struts>

jsp/useRegForm4.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>회원 가입</title>
</head>
<body>
<center>
<h2>회원 가입</h2><p>
<s:form action="userRegAction"  validate="true">
    <s:textfield label="아이디" name="user.userId" value="%{user.userId}" />  
    보는는 쪽 : 객체.setUser().setUserId()  /  받는쪽 : 객체.getUser().getUserId();  
    <s:password label="비밀번호" name="user.userPW"  value="%{user.userPW}" />
    <s:textfield label="이름" name="user.userName"  value="%{user.userName}" />
    <s:submit/>
</s:form>
</center>
</body>
</html>
jsp/useRegSuccess4.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>회원 가입 완료</title>
</head>
<center>
<body>
<b><font color="red">회원 가입이 완료되었다.</font></b><p>
 아 이 디 : <s:property value="user.userId"/>  <p>
 비밀번호 : <s:property value="user.userPW"/>  <p>
 이 름  : <s:property value="user.userName"/> <p>
</body>
</center>
</html>
appliactionContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-autowire="byName">
<bean id="userDao" class="dao.UserDao" />
<!--  userDao = new UserDao(); 객체를 생성해 둡니다. 
	   db와 연동시켜주는 객체는 싱글톤을 사용하거나 
	   userDao.getInstance(); - 싱글톤 객체 얻는 명령.. 
	   userDao.insert  userDao.selectAll.. 등등
	   
 -->
<bean id="userRegAction4" class="action.UserRegAction4" />
<!--  action.UserRegAction4 클래스를 userRegAction4로
	   불러 사용할 수 있습니다. 
	   + action.UserRegAction4 클래스의 객체를 생성해둡니다.
	   new UserRegAction4(); 
  -->

</beans>
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>Chapter14</display-name>
    <context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>
	    	/WEB-INF/applicationContext.xml
	    </param-value>
	</context-param>
	
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
  <filter>
  <filter-name>struts2</filter-name>
  <filter-class>
  org.apache.struts2.dispatcher.FilterDispatcher
  </filter-class>
   <init-param> 
     <param-name>struts.i18n.encoding</param-name>
     <param-value>UTF-8</param-value>
  </init-param> 
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-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>



MyException.java
package Service;

public class MyException {
	String name;
	String message;
	
	public String execute() throws Exception{
		message="실행중입니다";
		System.out.println("MyException-execute");
		// 일부러 예외를 만들어 보자
		
		int len = name.length(); 
		//java.lang.NullPointerException 발생
		
		message="에러 없이 실행 완료";
		return "success";		
	}

	public String getMessage() {
		return message;
	}
	
}

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.devMode" value="true" />
	
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
	<!--  예외 발생하면 기본적으로  Exception.jsp 띄우기 -->
	<global-results>
		<result name="error">/Exception.jsp</result>
	</global-results>	
	<global-exception-mappings>
		<exception-mapping result="error" 
		exception="java.lang.Exception"/>
	</global-exception-mappings>
		
	<!--   <result name="error">/Exception.jsp</result>
		   <exception-mapping result="error" 
	     	exception="java.lang.NullPointerException"/>
	-->
	
    
    <action name="Exception"  class="Service.MyException">
    	<result name="error">/Exception.jsp</result>
    	<result>/Exception.jsp</result>
    	<exception-mapping result="error" 
    	exception="java.lang.NullPointerException" />
    </action>
	</package>
</struts>
pageError.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page isErrorPage="true"%>
<html>
<body>
<h1>에러 페이지</h1>
${exception}
</body>
</html>

Exception.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>
	${message }
</body>
</html>





로깅

http://logging.apache.org 

log4j-1.2.15.jar


log4j.properties
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
#   1. DEBUG (the least serious)
#   2. INFO
#   3. WARN
#   4. ERROR
#   5. FATAL (the most serious)

# Set root logger level to WARN and append to stdout
log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n

# OpenSymphony Stuff
log4j.logger.com.opensymphony=INFO
log4j.logger.org.apache.struts2=DEBUG

log4j.logger.com.opensymphony.xwork2.util.profiling.UtilTimerStack=INFO





프로파일링


s06.FileIO.zip





스트럿츠 2는 서버에 파일 업로드하기 위해서는 이 기능을 지원하는 IO 컴퍼넌트 ,

FileUpload 컴퍼넌트의 2가지 라이브러리가 필요하다.

commons-fileupload-1.2.1.jar

commons-io-1.4.jar


※Struts 2의 기본 설정 파일에서는 업로드 파일 크기를 2MB로 제한하고 있다.


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.devMode" value="true" />
	
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
	
	<action name="FileUploadForm" class="file.FileUploadAction">
      <result>/jsp/fileUpload.jsp</result>
    </action>
    <action name="FileUploadAction" class="file.FileUploadAction">
      <result name="input">/jsp/fileUpload.jsp</result>
      <result>/jsp/fileUploadOK.jsp</result>
    </action>
    
      
    
	<action name="FileList" class="file.FileListAction">
	    <result>/jsp/fileDownload.jsp</result>
	</action>		
    <action name="FileDownload" class="file.FileDownloadAction">
            <result type="stream">
                <param name="contentType">binary/octet-stream</param>
                <param name="contentLength">${contentLength}</param>
                <param name="contentDisposition">${contentDisposition}</param>
                <param name="inputName">inputStream</param>
                <param name="bufferSize">4096</param>
            </result>
    </action>  
    
 
	</package>
</struts>

struts.properties
struts.i18n.encoding=UTF-8
struts.multipart.maxSize=2097152
struts.devMode = true

jsp/fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>파일 업로드 입력 폼</h2>
  <s:form action="FileUploadAction" method="POST" enctype="multipart/form-data">
  <s:file name="upload" label="File"  size="50"/>
  <s:submit />
  </s:form>
</body>
</html>

jsp/fileUploadOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>파일 업로드 입력 완료</h2>

  <p>
    <ul>
    <li>ContentType: <s:property value="uploadContentType" /> / ${uploadContentType}</li>
    <li>FileName: <s:property value="uploadFileName" /></li>
    <li>File: <s:property value="upload" /></li>
    </ul>
  </p>

</body>
</html>
jsp/fileDownload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 다운 로드</title>
</head>

<body>
<h4>다운로드 목록</h4><hr>
다운로드 디렉토리 : <s:property value="BasePath"/> 
   
<ul>

<s:iterator value="listFile" status="stat">
	<s:url id="download" action="FileDownload">
		<s:param name="basePath" value="basePath" />
		<s:param name="fileName"><s:property value="listFile[#stat.index].name" /></s:param>
	</s:url>
	<li><s:a href="%{download}"><s:property value="listFile[#stat.index].name" /></s:a><br/></li>
</s:iterator>
</ul>
<br/>
* 파일 이름을 클릭하면 파일이 다운로드됩니다. 
</body>
</html>

FileListAction.java
package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class FileListAction extends ActionSupport {
	
	private static final String BasePath = "C:/upload/";
	
	private List<File> listFile = new ArrayList<File>();
	private String basePath;
    
	public String execute() throws Exception {
		basePath = BasePath;
		File dir = new File(basePath);
		File[] files = dir.listFiles();
		
		if (null != files) {
			for (File f: files) {
				if (f.isFile()) {
					listFile.add(f);
				}
			}
		}		
		
		return SUCCESS;
	}

	public List getListFile() {
		return listFile;
	}
	public void setListFile(List<File> listFile) {
		this.listFile = listFile;
	}
	public String getBasePath() {
		return basePath;
	}
	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}
}

FileUpload.java
package file;

import java.io.File;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.profiling.UtilTimerStack;

public class FileUploadAction extends ActionSupport {
	
	  private static final String UploadPath = "C:/upload/";

	  // 스트럿츠2 파일 업로드의 특징 : intercepter가 파일 객체의 3가지 정보를 셋팅합니다. 
	  private File upload; // <s:file name="upload" 파라미터
	  private String uploadContentType;
	  private String uploadFileName;
	  
	  File saveFile;
	  
	  @Override
	  public String execute() throws Exception {
		  //프로파일링 셋팅하자
		  UtilTimerStack.setActive(true);
		  
		    if(upload != null && upload.exists()){
		    	saveFile=new File(UploadPath+uploadFileName);
		    	FileUtils.copyFile(upload, saveFile); //왼쪽 것을 오른쪽으로 복사한다. 
		    }
		    return SUCCESS;
	  }

	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	
}

FileDownloadAction.java
package file;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import com.opensymphony.xwork2.ActionSupport;

public class FileDownloadAction extends ActionSupport {	
		
	private String basePath;
	private String fileName;              //파일의 이름
	private String contentType;          //스트림 타입
	private String contentDisposition;	 //스트림의 원래 이름
	private InputStream inputStream;  //스트림 데이터
	private long contentLength;          //스트림의 크기	

	public String execute() throws Exception {
	    	//inputPath
	    	String inputPath = basePath + "/" + fileName;

	    	//contentLength
	    	File f = new File(inputPath);
	    	setContentLength(f.length());
	    	
	    	//contentDisposition
	    	setContentDisposition("attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

	    	//inputStream    	
	    	setInputStream(new FileInputStream(inputPath));
	    	
	        return SUCCESS;
	    }

		public String getBasePath() {
			return basePath;
		}
		public void setBasePath(String basePath) {
			this.basePath = basePath;
		}
		public String getContentDisposition() {
			return contentDisposition;
		}
		public void setContentDisposition(String contentDisposition) {
			this.contentDisposition = contentDisposition;
		}
		public long getContentLength() {
			return contentLength;
		}
		public void setContentLength(long contentLength) {
			this.contentLength = contentLength;
		}
		public String getContentType() {
			return contentType;
		}
		public void setContentType(String contentType) {
			this.contentType = contentType;
		}
		public String getFileName() {
			return fileName;
		}
		public void setFileName(String fileName) {
			this.fileName = fileName;
		}
		public InputStream getInputStream() {
			return inputStream;
		}
		public void setInputStream(InputStream inputStream) {
			this.inputStream = inputStream;
		}
}









다중 파일 업로드


MultiUploadListAction.java
package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class MultiUploadListAction extends ActionSupport {
	
	  private static final String UploadPath = "C:/upload/";

	  private List<File> uploads = new ArrayList<File>();
	  private List<String> uploadsFileName = new ArrayList<String>();
	  private List<String> uploadsContentType = new ArrayList<String>();
	  
	  File saveFile;
	  
	  @Override
	  public String execute() throws Exception {
		  for (int i = 0; i < uploads.size(); i++) {
		        File destFile = new File(UploadPath
		            + getUploadsFileName().get(i));
		        
		        FileUtils.copyFile(getUploads().get(i), destFile);
		  }
		  return SUCCESS;
	  }

	public List<File> getUploads() {
		return uploads;
	}

	public void setUploads(List<File> uploads) {
		this.uploads = uploads;
	}

	public List<String> getUploadsFileName() {
		return uploadsFileName;
	}

	public void setUploadsFileName(List<String> uploadsFileName) {
		this.uploadsFileName = uploadsFileName;
	}

	public List<String> getUploadsContentType() {
		return uploadsContentType;
	}

	public void setUploadsContentType(List<String> uploadsContentType) {
		this.uploadsContentType = uploadsContentType;
	}

	public File getSaveFile() {
		return saveFile;
	}

	public void setSaveFile(File saveFile) {
		this.saveFile = saveFile;
	}

	public static String getUploadPath() {
		return UploadPath;
	}	
}

struts.xml
<action name="MultiUploadListForm">
      <result>/jsp/multiUploadList.jsp</result>
    </action>
    <action name="MultiUploadListAction" class="file.MultiUploadListAction">
      <result>/jsp/multiUploadListOK.jsp</result>
    </action> 
multiUploadList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2>다중파일 업로드 입력 폼 (리스트)</h2>
  <s:form action="MultiUploadListAction" method="POST" 
      enctype="multipart/form-data">
    <s:file label="File (1)" name="uploads" size="50"/>
    <s:file label="File (2)" name="uploads" size="50"/>
    <s:file label="FIle (3)" name="uploads" size="50"/>
    <s:submit />
  </s:form>
</body>
</html>

multiUploadListOK.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>파일 업로드</title>
</head>

<body>
  <h2> 리스트를 이용한 다중 파일 업로드 입력 완료 화면 </h2>
  <s:iterator value="uploads" status="stat">
  File ( <s:property value="%{#stat.index + 1}" /> ) <br/>
   컨텐츠 타입 : 
   <s:property value="%{uploadsContentType[#stat.index]}" /> <br/>
   파일 이름 : 
   <s:property value="%{uploadsFileName[#stat.index]}" /> <br/>
   임시 파일 이름 :    
   <s:property value="%{uploads[#stat.index]}" /> <br/>
   <hr/>
 </s:iterator>
</body>
</html>



Mysql.java
package dao;

public class Mysql {
	
	public void insert(String id){
		System.out.println("커넥션 연결됨");
		System.out.println(id+" 회원 가입 처리되었습니다");
	}
	
}

LoginAction.java
package Service;

public class LoginAction {
	
	public String execute(){
		System.out.println("로그인 처리중");
		System.out.println("id 비번 모두 일치함 통과");
		return "success";
	}
}

RegMember.java
package Service;

import dao.Mysql;

public class RegMember {
	String id;
	
	public String getId() { //jsp에서 ${id}
		return "id :"+ id+"";
	}
	
	public void setId(String id) {
		System.out.println("RegMember-setId="+id);
		this.id = id;
	}
	
	public String execute(){
		System.out.println("RegMember-execute");
		new Mysql().insert(id); //db에 회원가입 요청 
		
		return "success";
	}
}

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<constant name="struts.i18n.encoding" value="UTF-8" />
	<constant name="struts.devMode" value="true" />
	
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
		<action name="RegMember" class="Service.RegMember" >
		<interceptor-ref name="params" />
		<result type="chain">
			<param name="actionName">LoginAction</param>
			<param name="namespace">/</param>
		</result>
	</action>
	
	<action name="LoginAction" class="Service.LoginAction" >
		<interceptor-ref name="chain"></interceptor-ref>
		<interceptor-ref name="params"></interceptor-ref>
		<result>/Success.jsp</result>
	</action>
	</package>
</struts>
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>04.validate</display-name>
  <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>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
	  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
Form.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="RegMember.action"  >
		<input text="text" name="id" size="8">
		<input type="submit" value="보내기">
	</form>
</body>
</html>
Success.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>
	회원가입 성공 ${id}
</body>
</html>





DBHelper.java
package DAO;

import java.util.ArrayList;
import java.util.List;

import model.Article;

public class DBHelper {
	
	
	public List<Article> selectAll(){
		System.out.println("db에서 글 모두 가져온다");
		List<Article> list=new ArrayList<Article>();
		Article article1=new Article(1, "첫", "안녕1");
		Article article2=new Article(2, "첫~", "안녕2");
		Article article3=new Article(3, "첫~~", "안녕3");
		Article article4=new Article(4, "첫~~~", "안녕4");
		Article article5=new Article(5, "첫@@@", "안녕5");
		list.add(article1);
		list.add(article2);
		list.add(article3);
		list.add(article4);
		list.add(article5);
		return list;
	}
}

Article.java
package model;

//게시글 하나의 정보를 담는 모델
public class Article {
	private int no; //글번호
	private String title; //제목
	private String content; //내용
		
	public Article(int no, String title, String content) {
		super();
		this.no = no;
		this.title = title;
		this.content = content;
	}

	public Article() {		
	}
		
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}

ListService.java
package model;

//게시글 하나의 정보를 담는 모델
public class Article {
	private int no; //글번호
	private String title; //제목
	private String content; //내용
		
	public Article(int no, String title, String content) {
		super();
		this.no = no;
		this.title = title;
		this.content = content;
	}

	public Article() {		
	}
		
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}

list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!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>
	게시글 리스트를 보여주는 페이지 <br/>
	<table>
	</table>
	
	
	
	<s:iterator value="list"> <!-- List<Article> list;// 게시글이 5개 들어갈 것이다.    -->
		<s:property value="no" /> / 
		<s:property value="title" /> /
		<s:property value="content" /> 
	</s:iterator>
	
	<s:if test="true">
		true면 항상 나옵니다 <br/>
	</s:if>
	<s:if test="1<5">
		1<5 ? <br/>
	</s:if>
	<s:if test="false">
		if
	</s:if>
	<s:elseif test="2==3">
		elseif
	</s:elseif>
	<s:else>
		if, elseif, else 
	</s:else> <br />
	append는 2개의 리스트를 합칩니다. 
	<s:append id="totallist">
		<s:param value="list" />
		<s:param value="list" />
	</s:append>
	iterator는 list를 풀어서 반복시킵니다. 
	<s:iterator value="totallist"> 
		<s:property value="no"/> , <s:property value="title"/>
		, <s:property value="content" /> <br/>
	</s:iterator>
	generator는 iterator를 만듭니다. <br />
	
	<s:generator id="list" separator="," val="%{ ' 안,녕,하,세,요' }" 
			count="5" >
		<s:iterator>
			<s:property />
		</s:iterator>
	</s:generator>
	
	<br/> merge는 list를 합칠때 섞습니다 
	<s:merge id="totallist">
		<s:param value="list" />
		<s:param value="list" />
	</s:merge>
	
	<s:iterator value="totallist"> 
		<s:property value="no"/> , <s:property value="title"/>
		, <s:property value="content" /> <br/>
	</s:iterator>
	
	bean은 클래스의 객체를 만들때 사용합니다  <br/>
	<s:bean name="model.Article" id="art">
		<s:param name="no" value="7" />
		<s:param name="title" value="'타이틀'" />
		<s:param name="content" value="'~~컨텐트~~'" />
	</s:bean>   <br />
	
	 no: <s:property value="#art.no" />
	title :  <s:property value="#art.title" />
	content :  <s:property value="#art.content" />	
	
	set은 특정 영역에 값을 셋팅합니다. 예) 로그인 유무  <br />
	<s:set name="title" value="#art.title"  scope="application"></s:set>
	<s:set name="ses" value="'세션영역에 값 셋팅'" scope="session" />
	<s:set name="req" value="'리퀘스트 영역에 값 셋팅'" scope="request" />
	<s:set name="pag" value="'페이지 영역에 값 셋팅'" scope="page" />
	<s:set name="hello" value="#art.no"  />
	
	특정 영역에 셋팅된 값을 꺼내기 <br />
	app : <s:property value="#application.title" /> , ${title} <br/>
	ses : <s:property  value="#session.ses" /> , ${ses } <br />
	pag : <s:property value="#page.pag" /> , ${pag} <br/>
	hello : <s:property value="#hello"/> , ${hello } <br/>
	
</body>
</html>


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
		<action name="list" class="Service.ListService" >			
			<result name="success">/list.jsp</result>
		</action>
		
		
		<!--  맨 아래에 있어야 합니다.  
				디폴트 와일드카드 맵핑 
				-->		
		<action name="*">
			<result>{1}.jsp</result>
		</action>	
	</package>
	
	
</struts>

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>04.validate</display-name>
  <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>
  
  <filter>
	  <filter-name>struts2</filter-name>
	  
	  <filter-class>
	  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  </filter>
  <filter-mapping>
	  <filter-name>struts2</filter-name>
	  <url-pattern>/*</url-pattern> 
  </filter-mapping>  
  
</web-app>


프로젝트 생성시 버전을 2.5로 해줘야함..




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>04.vaildate</display-name>
  <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>
  
  <filter>
	  <filter-name>struts2</filter-name>	  
	  <filter-class>
		  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  	<init-param>
  		<description>한글인코딩하기, FilterDispatcher실행중에
  				struts.i18n.encoding의 값을 찾아서 셋팅합니다  			
  		</description>
  		<param-name>struts.i18n.encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  
  <filter-mapping>
	  <filter-name>struts2</filter-name>
	  <url-pattern>/*</url-pattern> <!--  사이트.com/abc.jsp -->
  </filter-mapping>  
</web-app>


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		
		<!--  지정된 패키지 내에서 .. 결과가 input 이면  -->
		<global-results>
			<result name="input">/LoginForm.jsp</result>
			<result name="error">/error.jsp </result>
		</global-results>
		
		<action name="LoginForm"   >
			<result>LoginForm.jsp</result>
		</action>
		
		<action name="LoginProcess"  class="Service.LoginProcess">			
			<result name="success">LoginSuccess.jsp</result>
		</action>
		
		<action name="LoginProcess2"  class="Service.LoginProcess2">
			<result name="input">/LoginForm2.jsp</result>			
			<result name="success">LoginSuccess2.jsp</result>
		</action>
		
		<!--  맨 아래에 있어야 합니다.  
				디폴트 와일드카드 맵핑 
				-->		
		<action name="*">
			<result>{1}.jsp</result>
		</action>	
	</package>
</struts>


LoginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>LoginForm.jsp</title>
</head>
<body>
	로그인폼.jsp<br/>
	패키지명:Service, 클래스명:LoginProcess.java</br>
	<form action="LoginProcess.action">
		id:<input type="text" name="id">${fieldErrors.id}</br>
		pw:<input type="text" name="pw"></br>
		email:<input type="text" name="email"></br>
		<input type="submit" value="보내기"></br>
	</form>
</body>
</html>


LoginSuccess.jsp
package Service;

import com.opensymphony.xwork2.ActionSupport;

public class LoginProcess extends ActionSupport {
	String id , pw, email;
	
	@Override
	public void validate() {
		//setter 메서드 다음에 호출된다
		if(id==null || id.length()<2){
			addFieldError("id", "아이디를 2자 이상 입력하세요");
			// return "input";이 됩니다. 
		}
		super.validate();
	}
	
	
	public String execute(){
		if(id.equals("error")){
			return "error";
		}
		return "success";
	}

	public String getId() {
		return id;
	}

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

	public String getPw() {
		return pw;
	}

	public void setPw(String pw) {
		this.pw = pw;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}





error.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>error</title>
</head>
<body>
	에러 페이지
</body>
</html>


LoginForm2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!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>LoginForm2.jsp </title>
</head>
<body>
	로그인폼2.jsp <br />
	
	<s:property value="message"/><br/>
	s:form 태그를 사용하면 필드에러(~~.java실행할 때 validate()메서드에서 addFiedError());)
	를 내가 직접 호출할 필요가 없습니다.<br/>
	
	<s:form action="LoginProcess2.action">
		<!--  실행될 ~.java 의 필드 String id= %{id} ;  -->
		<s:textfield label="아이디" name="id" value="%{id}" /><br/>
		<s:password label="비밀번호" name="pw" value="%{pw}" /> <br/>
		<s:textfield label="이메일" name="email" value="%{email}" /> <br/>
		<s:submit />
	</s:form>
	
</body>
</html>


LoginProcess2.java
package Service;

import DAO.DBHelper;

import com.opensymphony.xwork2.ActionSupport;

public class LoginProcess2 extends ActionSupport {
	String id , pw, email;
	String message;
	
	@Override
	public void validate() {
		//setter 메서드 다음에 호출된다
		if(id==null || id.length()<2){
			addFieldError("id", "아이디를 2자 이상 입력하세요");
			// return "input";이 됩니다. 
			message="다시 입력하세요";
		}
		super.validate();
	}
	
	
	public String getMessage() {
		return message;
	}


	public String execute(){
		if(id.equals("error")){
			return "error";
		}
		//db에서 id와 비번을 체크하는 기능을 넣었다고 가정
		Boolean check=new DBHelper().check(id, pw);
		if(check){
			message="로그인에 성공했습니다.";
		}
		else message="처음 방문했습니다.";
		return "success";
	}

	public String getId() {
		return id;
	}

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

	public String getPw() {
		return pw;
	}

	public void setPw(String pw) {
		this.pw = pw;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
}


DBHelper.java
package DAO;

public class DBHelper {
	String myId="abc";
	String myPw="123";
	
	public DBHelper(){
		
	}
	
	public boolean check(String id,String pw){
		if(id.equals(myId) && pw.equals(myPw)){
			System.out.println("db조회 결과 계정 맞습니다.");
			return true;
		}
		return false;
	}
}


04.vaildate.zip


05.sstl.zip


'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

4일차 chain result type  (0) 2012.06.08
3일차 Struts Standard Tag Library  (0) 2012.06.08
2일차 interface 활용하기  (0) 2012.06.05
2일차 ActionSupport 클래스를 확장한 액션  (0) 2012.06.05
2일차 form  (0) 2012.06.05



struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
			<result name="input">/login/LoginForm.jsp</result>
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
		<action name="LoginCheck2"  class="service.LoginCheck2" method="login">
			<result name="input">/login/LoginForm2.jsp</result>
			<result>/login/LoginSuccess2.jsp</result>
		</action>
	</package>
</struts>


index.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>Index Page</title>
</head>
<body>
	인덱스 페이지
	
	<jsp:forward page="/login/LoginForm2.jsp"></jsp:forward>
</body>
</html> 


LoginForm2.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> LoginForm.jsp  </title>
</head>
<body>
	LoginForm.jsp <br />
	<form action="LoginCheck2.action" method="get">
		userId : <input type="text" name="user.userId"> ${fieldErrors.userId} <br/>
		userPw : <input type="text" name="user.userPw"> ${fieldErrors.userPw} <br/>
		<input type="submit" value="보내기" >
	</form>
	
</body>
</html>


LoginSuccess2.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>LoginSuccess</title>
</head>
<body>
	LoginSuccess.jsp  <br/>
	
	객체.getUser.getId() 메서드가 호출됩니다. <br/>
	user Id : ${user.userId} / userPw : ${user.userPw} / <br/>
	${hello} <br/>
	${a.b.c.d.e} == getA().getB().getC().getD().getE();
</body>
</html>


LoginCheck.java
package service;

import model.User;

import com.opensymphony.xwork2.ActionSupport;

public class LoginCheck2 extends ActionSupport{
	User user;
	
	public String login(){
		System.out.println("LoginCheck2 - login");
		//db에 있는 사용자 정보를 체크하자
		new CheckUserService().check(user);
		
		//체크성공했다
		return "success";
	}

	public User getUser() {
		return user;
	}

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


User.java
package model;

//한명의 회원정보를 저장하는 클래스 - 필드, 생성자,set,get
public class User {
	String userId;
	String userPw;
	
	public User(){
		System.out.println("기본 생성자 User");
		
	}
	
	public User(String userId, String userPw) {
		super();
		this.userId = userId;
		this.userPw = userPw;
	}

	public String getUserId() {
		System.out.println("getUserId");
		return userId;
	}

	public void setUserId(String userId) {
		System.out.println("setUserId");
		this.userId = userId;
	}

	public String getUserPw() {
		System.out.println("getUserPw");
		return userPw;
	}

	public void setUserPw(String userPw) {
		System.out.println("setUserPw");
		this.userPw = userPw;
	}
	
	
}


CheckUserService.java
package service;

import model.User;

//db를 조회해서 id와 pw가 맞는지를 확인하는 클래스
public class CheckUserService {
	
	public void check(User user){
		//db 조회 했다.
		System.out.println("CheckUserServive - check 성공");
	}
}





struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
			<result name="input">/login/LoginForm.jsp</result>
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
		<action name="LoginCheck2"  class="service.LoginCheck2" method="login">
			<result name="input">/login/LoginForm2.jsp</result>
			<result>/login/LoginSuccess2.jsp</result>
		</action>
		
		<action name="LoginCheck3"  class="service.LoginCheck3">
			<result name="input">/login/LoginForm3.jsp</result>
			<result>/login/LoginSuccess3.jsp</result>
		</action>
	</package>
</struts>


index.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>Index Page</title>
</head>
<body>
	인덱스 페이지
	
	<jsp:forward page="/login/LoginForm3.jsp"></jsp:forward>
</body>
</html> 


LoginForm3.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> LoginForm.jsp  </title>
</head>
<body>
	LoginForm.jsp <br />
	<form action="LoginCheck3.action" method="get">
		userId : <input type="text" name="userId"> ${fieldErrors.userId} <br/>
		userPw : <input type="text" name="userPw"> ${fieldErrors.userPw} <br/>
		<input type="submit" value="보내기" >
	</form>
	
</body>
</html>


LoginCheck3.java
package service;


import model.User;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class LoginCheck3 extends ActionSupport 
					implements ModelDriven,Preparable{
	User user;
	
	//2번째
	public Object getModel() {
		System.out.println("getModel");
		return user;
	}
	
	//1번째 prepare는 execute직전에  호출되는 메서드로서 
	//execute를 하기 위한 준비작업 기능을 넣는다.
	public void prepare() throws Exception {
		System.out.println("prepare");
		user=new User();
	}
	public String execute(){
		return "success";
	}
	
	//3번째 jsp에서 실행됨
	public User getUser() {
		return user;
	}
}


LoginSuccess3.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>LoginSuccess3</title>
</head>
<body>
	LoginSuccess3.jsp  <br/>
	
	객체.getUser.getId() 메서드가 호출됩니다. <br/>
	user Id : ${user.userId} / userPw : ${user.userPw} / <br/>
	${hello} <br/>
	${a.b.c.d.e} == getA().getB().getC().getD().getE();
</body>
</html>




소스

03.form.zip




index.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>Index Page</title>
</head>
<body>
	인덱스 페이지
	
	<jsp:forward page="/select.jsp"></jsp:forward>
</body>
</html> 


select.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>
	<ul>
		<li>
			<a href="First.action">   첫번째 예제 </a>
		</li> 
		<li>
			<a href="Second.action">   두번째 예제 </a>
		</li>
		<li>
			<a href="Third.action">   세번째 예제 </a>
		</li>
	</ul>
</body>
</html>




struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
			<result name="input">/login/LoginForm.jsp</result>
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
		<action name="LoginCheck2"  class="service.LoginCheck2" method="login">
			<result name="input">/login/LoginForm2.jsp</result>
			<result>/login/LoginSuccess2.jsp</result>
		</action>
		
		<action name="LoginCheck3"  class="service.LoginCheck3">
			<result name="input">/login/LoginForm3.jsp</result>
			<result>/login/LoginSuccess3.jsp</result>
		</action>
		
		<action name="First">
		    <result type="dispatcher">/login/LoginForm.jsp</result>
		</action>
		<action name="Second">
		    <result type="dispatcher">/login/LoginForm2.jsp</result>
		</action>
		<action name="Third">
		    <result type="redirect">/login/LoginForm3.jsp</result>
		</action>
	
	</package>
</struts>





03.form.zip


index.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>Index Page</title>
</head>
<body>
	인덱스 페이지
	
	<jsp:forward page="/select.jsp"></jsp:forward>
</body>
</html> 


select.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>
	<ul>
		<li>
			<a href="First.action">   첫번째 예제 </a>
		</li> 
		<li>
			<a href="Second.action">   두번째 예제 </a>
		</li>
		<li>
			<a href="Third.action">   세번째 예제 </a>
		</li>
		<li>
			<a href="Hello.action">   Hello </a>
		</li>
		<li>
			<a href="Hello2.action">   Hello2 </a>
		</li>
	</ul>
</body>
</html>


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<action name="LoginForm2"   >
			<result>/login/LoginForm2.jsp</result>
		</action>
		
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
			<result name="input">/login/LoginForm.jsp</result>
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
		<action name="LoginCheck2"  class="service.LoginCheck2" 
				method="login">
			<result name="input">/login/LoginForm2.jsp</result>
			<result>/login/LoginSuccess2.jsp</result>
		</action>
		
		<!--  Hello.action 요청이 오면
			  service.Hello.class 객체생성후 execute 실행
			  return success/fail 결과에 따라 다른 액션 실행
		-->
		<action name="Hello" class="service.Hello">
			<result name="success" type="redirectAction">
				<param name="actionName">LoginForm</param>
			</result>
			<result name="fail" type="redirectAction">
				<param name="actionName">LoginForm2</param>
			</result>
		</action>
		
		<!-- Hello2.action요청이 오면 LoginCheck.action을 실행해
			 LoginCheck.action?userId=gusfree&userPw=12345
			 처럼 파라미터가 붙어서 실행이 된다
		 -->
		<action name="Hello2">
			<result type="redirectAction">
				<param name="actionName">LoginCheck</param>
				<param name="userId">gusfree</param>
				<param name="userPw">12345</param>
			</result>
		</action>
		
		<action name="LoginCheck3"  class="service.LoginCheck3" >
			<result name="input">/login/LoginForm3.jsp</result>
			<result>/login/LoginSuccess3.jsp</result>
		</action>
		
		<action name="First">
			<result type="dispatcher">/login/LoginForm.jsp</result>
		</action>
		<action name="Second">
			<result type="dispatcher">/login/LoginForm2.jsp</result>
		</action>
		<action name="Third">
			<result type="redirect">/login/LoginForm3.jsp</result>
		</action>
	</package>
</struts>


Hello.java
package service;

import java.util.Random;

public class Hello {
	public String execute(){
		System.out.println("Hello - execute");
		if(new Random().nextInt(100)<50){
			return "fail";
		}
		return "success";
	}
}



'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

3일차 Struts Standard Tag Library  (0) 2012.06.08
3일차 validate()  (0) 2012.06.07
2일차 ActionSupport 클래스를 확장한 액션  (0) 2012.06.05
2일차 form  (0) 2012.06.05
1일차 interceptor  (0) 2012.06.04

기타 세팅:http://gusfree.tistory.com/947 참조

교재 120page


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
		    <result name="input">/login/LoginForm.jsp</result>
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
	</package>
</struts>


LoginForm.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> LoginForm.jsp  </title>
</head>
<body>
	LoginForm.jsp <br />
	<form action="LoginCheck.action" method="get">
		userId : <input type="text" name="userId"> ${fieldErrors.userId} <br/>
		userPw : <input type="text" name="userPw"> ${fieldErrors.userPw} <br/>
		<input type="submit" value="보내기" >
	</form>
	
</body>
</html>


LoginCheck.java
package service;

import com.opensymphony.xwork2.ActionSupport;

public class LoginCheck extends ActionSupport{
	String userId;
	String userPw;
			
	@Override
	public void validate() {//유효성 검사
		System.out.println("validate");
		if(userId == null || userId.equals("")){
			//addFieldError(키,벨류);
			addFieldError("userId", "아이디를 입력하세요");
			//아이디를 제대로 입력하지 않았다면 필드에러를 만든다.
			//jsp에서 만든 필드 에러를 출력하자 ${fieldError.키값}
		}
		
		if(userPw == null || userPw.equals("")){
			addFieldError("userPw", "비번을 입력하세요");
		}
		
		//super.validate();
	}

	public LoginCheck(){
		System.out.println("LoginCheck 객체 생성");
	}
	
	public String execute(){
		System.out.println("execute");
		return "success";
	}
	
	// 자동으로 호출됩니다 
	public void setUserId(String userId){
		System.out.println("setUserId");
		this.userId=userId;
	}
	public void setUserPw(String userPw) {
		System.out.println("setUserPw");
		this.userPw = userPw;
	}
	public String getUserPw() {
		System.out.println("getUserPw");
		return userPw;
	}
	public String getUserId() {
		System.out.println("getUserId");
		return userId;
	}
}





id와 비번을 체크해서 관리자라면 인사를 하자


LoginCheck.java
package service;

import com.opensymphony.xwork2.ActionSupport;

public class LoginCheck extends ActionSupport{
	String userId;
	String userPw;
	String hello;	
	
	@Override
	public void validate() {//유효성 검사
		System.out.println("validate");
		if(userId == null || userId.equals("")){
			//addFieldError(키,벨류);
			addFieldError("userId", "아이디를 입력하세요");
			//아이디를 제대로 입력하지 않았다면 필드에러를 만든다.
			//jsp에서 만든 필드 에러를 출력하자 ${fieldError.키값}
		}
		
		if(userPw == null || userPw.equals("")){
			addFieldError("userPw", "비번을 입력하세요");
		}
		
		//super.validate();
	}

	public LoginCheck(){
		System.out.println("LoginCheck 객체 생성");
	}
	
	public String execute(){
		System.out.println("execute");
		//id와 비번을 체크해서 관리자라면 인사를 하자
		hello="";
		if(userId.equals("gusfree") && userPw.equals("12345")){
			hello="안녕하세요" +userId+"<img src='https://t1.daumcdn.net/cfile/tistory/125822404F8593850B'>";
		}
		return "success";
	}
	
	
	public String getHello() {//jsp에서 ${hello}로 호출
		return hello;
	}

	// 자동으로 호출됩니다 
	public void setUserId(String userId){
		System.out.println("setUserId");
		this.userId=userId;
	}
	public void setUserPw(String userPw) {
		System.out.println("setUserPw");
		this.userPw = userPw;
	}
	public String getUserPw() {
		System.out.println("getUserPw");
		return userPw;
	}
	public String getUserId() {
		System.out.println("getUserId");
		return userId;
	}
}


LoginSuccess.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>LoginSuccess</title>
</head>
<body>
	LoginSuccess.jsp  <br/>
	
	객체.getUserId() 메서드가 호출됩니다. <br/>
	user Id : ${userId} / userPw : ${userPw} / <br/>
	${hello}
</body>
</html>



'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

3일차 validate()  (0) 2012.06.07
2일차 interface 활용하기  (0) 2012.06.05
2일차 form  (0) 2012.06.05
1일차 interceptor  (0) 2012.06.04
1일차 한글 깨짐 현상  (0) 2012.06.04




struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

	
<struts>
	<package name="hi" extends="struts-default" 
		namespace="/"	>
		<action name="LoginForm"   >
			<result>/login/LoginForm.jsp</result>
		</action>	
		<!--  LoginCheck.action?userId=xxx&userPw=yyy -->
		<action name="LoginCheck"  class="service.LoginCheck">
			<result>/login/LoginSuccess.jsp</result>
		</action>
		
	</package>
</struts>


index.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>Index Page</title>
</head>
<body>
	인덱스 페이지
	
	<jsp:forward page="/login/LoginForm.jsp"></jsp:forward>
</body>
</html> 


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app  xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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>struts study start</display-name>
  
  <filter>
	  <filter-name>struts2</filter-name>	  
	  <filter-class>
		  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  	<init-param>
  		<description>한글인코딩하기, FilterDispatcher실행중에
  				struts.i18n.encoding의 값을 찾아서 셋팅합니다  			
  		</description>
  		<param-name>struts.i18n.encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  
  <filter-mapping>
	  <filter-name>struts2</filter-name>
	  <url-pattern>/*</url-pattern> <!--  사이트.com/abc.jsp -->
  </filter-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>


LoginForm.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> LoginForm.jsp  </title>
</head>
<body>
	LoginForm.jsp <br />
	<form action="LoginCheck.action" method="get">
		userId : <input type="text" name="userId"> <br/>
		userPw : <input type="text" name="userPw"> <br/>
		<input type="submit" value="보내기" >
	</form>
	
</body>
</html>


LoginSuccess.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>LoginSuccess</title>
</head>
<body>
	LoginSuccess.jsp  <br/>
	
	객체.getUserId() 메서드가 호출됩니다. <br/>
	user Id : ${userId} / userPw : ${userPw } / <br/>
</body>
</html>


LoginCheck.java
package service;

public class LoginCheck {
	String userId;
	String userPw;
	
	public LoginCheck(){
		System.out.println("LoginCheck 객체 생성");
	}
	
	public String execute(){
		System.out.println("execute");
		return "success";
	}
	
	// 자동으로 호출됩니다 
	public void setUserId(String userId){
		System.out.println("setUserId");
		this.userId=userId;
	}
	public void setUserPw(String userPw) {
		System.out.println("setUserPw");
		this.userPw = userPw;
	}
	public String getUserPw() {
		System.out.println("getUserPw");
		return userPw;
	}
	public String getUserId() {
		System.out.println("getUserId");
		return userId;
	}
}



'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

2일차 interface 활용하기  (0) 2012.06.05
2일차 ActionSupport 클래스를 확장한 액션  (0) 2012.06.05
1일차 interceptor  (0) 2012.06.04
1일차 한글 깨짐 현상  (0) 2012.06.04
1일차 form  (0) 2012.06.04


s2.Form.zip


'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

2일차 ActionSupport 클래스를 확장한 액션  (0) 2012.06.05
2일차 form  (0) 2012.06.05
1일차 한글 깨짐 현상  (0) 2012.06.04
1일차 form  (0) 2012.06.04
1일차 랜덤한 이미지  (0) 2012.06.04

Servers/Tomcat v6.0 Server at localhost-config/server.xml

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"
        useBodyEncodingForURI="true"/>


자신의 project최상위 폴더/WebContent/WEB-INF/web.xml

<filter>
	  <filter-name>struts2</filter-name>	  
	  <filter-class>
		  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  	<init-param>
  		<description>한글인코딩하기, FilterDispatcher실행중에
  				struts.i18n.encoding의 값을 찾아서 셋팅합니다  			
  		</description>
  		<param-name>struts.i18n.encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>



여러번 하는것 같다.....ㅡㅡ;

'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

2일차 form  (0) 2012.06.05
1일차 interceptor  (0) 2012.06.04
1일차 form  (0) 2012.06.04
1일차 랜덤한 이미지  (0) 2012.06.04
1일차 기본 페이지 설정 및 요청  (0) 2012.06.04

DB를 생성한건 아니고 DB가 있다고 생각하자~~



struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="tutorial" extends="struts-default">
      <action name="Form">
		<result>Form.jsp</result>          
      </action>
      <action name="Insert" class="DAO.DBHelper" method="insert">
          <result name="success">/success.jsp</result>
          <result name="fail">/fail.jsp</result>
      </action>                             
   </package>
</struts>


From.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>스트러츠 2번째</title>
</head>
<body>
	Form.jsp<br/>
	<form action="Insert.action" method="get">
		아이디:
		<input type="text" name="id" size="10" required="required"> <br/>
		비번 :
		<input type="password" name="pw" size="10" required="required"> <br/>
		
		좋아하는 동물:
		<input type="radio" name="animal" value="dog" checked="checked">강아지
		<input type="radio" name="animal" value="cat">고양이
		<input type="radio" name="animal" value="bird">새
		<br/><input type="submit" value="보내기">
	</form>
</body>
</html>


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app  xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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>struts study start</display-name>
  
  <filter>
	  <filter-name>struts2</filter-name>
	  
	  <filter-class>
	  org.apache.struts2.dispatcher.FilterDispatcher
	  </filter-class>
  </filter>
  <filter-mapping>
	  <filter-name>struts2</filter-name>
	  <url-pattern>/*</url-pattern> <!--  사이트.com/abc.jsp -->
  </filter-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>


DBHelper.java
package DAO;

public class DBHelper {
	
	public DBHelper(){
		System.out.println("DBHelper default Constructor");
	}
	
	public String execute(){
		return "success";
	}
	
	public String insert(){ //db에 값을 입력하는 메서드가 될것이다
		System.out.println("insert");
		try{
		//db에 저장하는 소스가 여기에 여러줄 있다고 생각하자
			System.out.println("db에 저장중입니다");
			System.out.println("db에 저장중입니다");
		}catch(Exception e){
			return "fail";
		}
		return "success";
	}
}


success.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>
	성공 성공
</body>
</html>


fail.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>
	fail fail fail
</body>
</html>



※DBHelper.java 에서 리턴 값을 fail 로 주면 fail.jsp가 실행된다~



'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

1일차 interceptor  (0) 2012.06.04
1일차 한글 깨짐 현상  (0) 2012.06.04
1일차 랜덤한 이미지  (0) 2012.06.04
1일차 기본 페이지 설정 및 요청  (0) 2012.06.04
1일차 파일 포함시키기  (0) 2012.06.04

연습문제:image.action=>

랜덤한 이미지가 화면에 나오도록 만들기

- 이미지는 root/image/폴더안에 넣으세요

- 예: image/image1.jpg, image/image2.jpg

- jsp 파일: <img src="./image/image1.jpg">


↓↓↓↓↓↓↓↓↓


1. www.localhost:8080/프로젝트명/Image.action

2. /* -> struts2 -> org.apache.struts2.dispatcher.FilterDispatcher 실행

3. struts.xml 파일을 찾아서 Image라는 네임의 액션을 찾는다

4. 그 액션에 class 속성이 있다면

4-1. 클래스의 객체를 하나 생성한다

4-2. 객체.execute(); 실행한다 

5. 그 액션에 class속성과 method 속성이 있다면 method를 실행한다.

6. return "success" 라면

<result name="success"> /~~.jsp 보여준다 </result>

7. return "false" 라면

<result name="false"> /~~.jsp 보여준다 </result>



struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	
	<!--  파일 포함시키기
	     struts-default.xml은 자동으로 포함됩니다-->
	<include file="struts_study.xml"></include> 
	
	
	<!--  tutorial이라는 패키지명을 default로 셋팅 
		   www / index.html /  tutorial 이 모두 default 	 -->
    <package name="tutorial" extends="struts-default">
    
    	<!--  요청할때 http://localhost:8080/s1.Hello/HelloWorld.action
    	                    ip / port /프로젝트명/패키지명/액션네임.action 
    		     http://localhost:8080/s1.Hello/tutorial/HelloWorld.action    	
    	-->
    	
    	<!--    HelloWorld.action 이라는 요청이 오면 
    	         tutorial.HelloWorld클래스 실행하고
    		     return이 success 라면 root/helloWorld.jsp를 사용자에게 보여준다 
    	 -->
    	 
    	 <!--  class="..안의 execute()를 실행해라  "  
    	 		execute()메서드를 실행하기 위해서는 객체를 생성해야만 하는데
    	 		그 객체생성작업을 struts가 합니다. 
    	 		1. new HelloWorld().execute();
    	 		2. String message = "Hello, World~~~~~~~! <hr/> hi"; 
    	 		3. => success 리턴 
    	 		4. 결과가(즉 리턴이) "success"라면 
    	 		5. helloWorld.jsp를 보여줘 
    	  -->
        <action name="HelloWorld" class="tutorial.HelloWorld"  
             method="myTest">          
            <result name="success">/helloWorld.jsp</result>
        </action>
        
      <!-- 이미지 랜덤 호출 -->
      <action name="Image" class="tutorial.ImageSelect" method="select">
          <result name="succ">/DefaultAction.jsp</result>
          <result name="fail">/study.jsp</result>
      </action>   
      
        	<!--  
        		jsp의 mvc모델에서는 컨트롤러 역활을 java 클래스가 하는데에 비해
                struts2 에서는 컨트롤러 역활을 struts.xml 이 합니다.     
               	구조는 동일     
       		-->
        
                                              
    </package>
    
    <!--  기본 페이지를 설정할 때 package를 따로 잡자 -->
	<package name="def" extends="struts-default">
	
	  <!--  default-action-ref 기본 페이지를 ~ 무엇으로 하겠다  -->           
      <default-action-ref name="DefaultAction"  />         
      
      <!-- 기본 페이지 요청이 왔을 때 실행할 class와 보여줄 page -->
      <action name="DefaultAction" class="tutorial.DefaultAction"> 
        	<result>/DefaultAction.jsp</result>
      </action>
      
                                   
   </package>
</struts>


DefaultAction.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>
	DefaultAction page <br />
	기본 페이지 ${message}<br />
	<img src="${imgsrc }"><br/>
</body>
</html>


ImageSelect.java
package tutorial;

import java.util.Random;

public class ImageSelect {
	
	String imgsrc;
	
	public ImageSelect(){
		System.out.println("ImageSelect 객체 실행중");
	}
	
	public String getImgsrc() {
		System.out.println("getter 메서드 실행중");
		return imgsrc;
	}
	
	public String select(){
		
		System.out.println("select 명령 실행중");
		int i =new Random().nextInt(4);//1,2,3,4
		imgsrc="./image/image"+i+".png";
		
		return "succ";
		//return "fail";
	}
	
}


※ 리턴 값을 succ로 하면 <result name="succ">/DefaultAction.jsp</result> 화면이 뜨고,

    리턴 값을 fail로 주면 <result name="fail">/study.jsp</result> 화면으로 실행된다.




'Struts2 > 2012.04월 강좌(MySQL)' 카테고리의 다른 글

1일차 한글 깨짐 현상  (0) 2012.06.04
1일차 form  (0) 2012.06.04
1일차 기본 페이지 설정 및 요청  (0) 2012.06.04
1일차 파일 포함시키기  (0) 2012.06.04
1일차 struts  (0) 2012.06.04

+ Recent posts