이클립스를 사용안하면 어떻게 클래스를 컴파일 시켜서 적용을 시킬까?
예전엔 그렇게 찾아도 안보이던 것이 .....이리 쉬울줄이야..
c:\Tomcat\conf\context.xml
혹시나 몰라서 써둔다.
<filter> <filter-name>char Encoding</filter-name> <filter-class>convert.KorConvert</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter>
java.servlet.Filter 의 생성 주기
웹 응용프로그램이 처음 실행 될때 개체가 생성되고 init() 을 실행
클라이언트 요청이 있을대마다 doFilter() 실행
웹 응용 프로그램이 종료될때 destory() 실행
src.convert.KorConvert.java 예제
package convert;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class KorConvert implements Filter{
private String encoding;
private FilterConfig fg;
private boolean ignore = true;
@Override
public void init(FilterConfig arg0) throws ServletException {
fg = arg0;
// 필터가 정의되어지는 XML 문서에서 정보를 가져온다.
encoding = fg.getInitParameter("encoding");
String value = fg.getInitParameter("ignore");
if(value == null) {
ignore = true;
} else if(value.equalsIgnoreCase("true")) {
ignore = true;
} else if(value.equalsIgnoreCase("yes")) {
ignore = true;
} else {
ignore = false;
}
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
if( ignore || arg0.getCharacterEncoding() == null) {
// ignore 가 true 이거나 setCharacterEncoding으로 설정된 캐릭터셋값이 없을 경우
// 이곳에서 전처리 코드 수행
if(encoding != null) {
arg0.setCharacterEncoding(encoding);
}
arg2.doFilter(arg0, arg1);
// 후처리 코드 수행
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="org.apache.commons.net.ftp.*" %>
<%
FTPClient ftp = null;
try{
String FilePath="";
FilePath=request.getParameter("FilePath");
ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
ftp.connect("아이피");
ftp.login("아이디", "패스워드");
ftp.changeWorkingDirectory("/vms/"); // 디렉토리 변경
File uploadFile = new File(FilePath);
FileInputStream fis = null;
try{
fis = new FileInputStream(uploadFile);
boolean isSuccess = ftp.storeFile(uploadFile.getName(), fis);
if (isSuccess)
{
System.out.println("Upload Success");
}
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally{
if (fis != null)
try{
fis.close();
} catch (IOException ex) {}
}
ftp.logout();
} catch (SocketException e){
System.out.println("Socket:" + e.getMessage());
} catch (IOException e){
System.out.println("IO:" + e.getMessage());
} finally{
if (ftp != null && ftp.isConnected()){
try{
ftp.disconnect();
} catch (IOException e){}
}
}
%>
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="java.util.*"%>
<!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=EUC-KR">
<title>▒▒</title>
</head>
<body>
<%
String savePath="c:\download"; // 저장할 디렉토리 (절대경로)
String formName="";
String fileName="";
String fullPath="";
int sizeLimit = 10 * 1024 * 1024 ; // 10메가까지 제한 넘어서면 예외발생
try{
MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit, new DefaultFileRenamePolicy());
Enumeration formNames=multi.getFileNames(); // 폼의 이름 반환
formName=(String)formNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
fileName=multi.getFilesystemName(formName); // 파일의 이름 얻기
fullPath=savePath+"/"+fileName;
if(fileName == null) { // 파일이 업로드 되지 않았을때
out.println("<script>alert(\"\\n파일 에러!. \\n\\n파일을 확인해주세요.! \");</script>");
} else { // 파일이 업로드 되었을때
out.println("<script>alert(\"업로드 완료! \");</script>");
}
}catch(Exception e){
System.out.println(e);
}
%>
</body>
</html>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
<taglib>
<taglib-uri>/WEB-INF/tld/struts-tiles.tld</taglib-uri>
<taglib-location>/WEB-INF/tld/struts-tiles.tld</taglib-location>
</taglib>
<action path="/main1" forward=".main1" /> <action path="/menu1" forward=".submenu1" /> <action path="/menu2" forward=".submenu2" />* 본인은 struts URL 설정에서 *.do로 해두었다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
<tiles-definitions>
<definition name=".main1" path="/Layout.jsp">
<put name="title" value="안냐세요" />
<put name="header" value="/header.jsp" />
<put name="menu" value="/menu.jsp" />
<put name="footer" value="/footer.jsp" />
<put name="body" value="/body.jsp" />
</definition>
<definition name=".submenu1" extends=".main1">
<put name="body" value="menu1.jsp" />
</definition>
<definition name=".submenu2" extends=".main1">
<put name="body" value="menu2.jsp" />
</definition>
</tiles-definitions>
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="/WEB-INF/tld/struts-tiles.tld" prefix="tiles"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1><tiles:getAsString name="title" /></h1>
<table border="1" width="100%">
<tr>
<td colspan="2"><tiles:insert attribute="header" /></td>
</tr>
<tr>
<td width="140"><tiles:insert attribute="menu" /></td>
<td><tiles:insert attribute="body" /></td>
</tr>
<tr>
<td colspan="2"><tiles:insert attribute="footer" /></td>
</tr>
</table>
</body>
</html>
* web.xml을 아래와 같이 변경해준다.
<servlet-class>my.MyActionServlet</servlet-class>
package my;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.*;
import org.apache.struts.action.*;
import org.apache.struts.config.*;
import org.apache.struts.util.*;
/**
* <pre>
* struts-config.xml과 메시지 리소스 파일의 수정사항을
* 서버의 재시작 없이 사용하도록 하는 ActionServlet이다.
*
* [사용방법]
* web.xml 파일을 다음과 같이 수정한다.
* <servlet-class>my.MyActionServlet</servlet-class>
*
* reload.do 를 호출한다.
* </pre>
*/
public class MyActionServlet extends ActionServlet {
protected void process( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException {
String uri = request.getRequestURI();
if( uri.indexOf( "reload.do" ) != -1 ) {
removeAttribute();
init();
ModuleUtils.getInstance().selectModule( request, getServletContext() );
ModuleConfig config = getModuleConfig( request );
getRequestProcessor( config ).init( this, config );
System.out.println( "reload ok..." );
} else {
super.process( request, response );
}
}
private void removeAttribute() {
ServletContext context = getServletContext();
Enumeration applications = context.getAttributeNames();
List contextAttributes = new ArrayList();
//-스트러츠프레임워크에서 설정한 모든 모듈 설정 클래스들의 이름을 얻는다.
while ( applications.hasMoreElements() ) {
String attributeName = (String) applications.nextElement();
if ( attributeName.startsWith( "org.apache.struts." ) ) {
contextAttributes.add( attributeName );
}
}
//- 에플리케이션 속성(영역)에 바인딩되어 있는 클래스들을 메모리에서 해제 한다.
for (int i = 0; i < contextAttributes.size(); i++) {
context.removeAttribute( (String) contextAttributes.get( i ) );
}
}
}
web.xml 파일소스 닫기
<display-name>GuestBook</display-name> <!-- ActionServlet를 등록한다. --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/config/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>2</param-value> </init-param> <!-- ActionServlet은 이 웹 어플리케이션 시작시에 함께 시작되어야 한다. --> <load-on-startup>1</load-on-startup> </servlet> <!-- “*.do”로 끝나는 모든 URL 패턴은 ActionServlet을 거쳐서 수행되어야 한다. --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
web.xml 파일소스 닫기
struts-config.xml 소스파일 닫기
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> <struts-config> <action-mappings> <action path="/Welcome" forward="/index.jsp"/> </action-mappings> </struts-config>
struts-config.xml 소스파일 닫기
간단히 action을 지정해줬는데 http://localhost:8080/SimpleGuestBook/Welcome.do 라고 실행하게 되면 index.jsp를 포워딩하는 그런 것이다.
WebContent폴더에 index.jsp를 생성한 뒤
index.jsp 소스파일 닫기
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>스트럿츠로 제작된 방명록입니다.</title>
</head>
<body>
<a href="list.do">환영합니다.</a>
</body>
</html>
index.jsp 소스파일 닫기
이렇게 적어보자. 그런 뒤 SimpleGuestBook(프로젝트이름)에 대고 오른쪽버튼을 누른 뒤
Run As -> Run on Server해서 우리가 추가한 서버로 실행해보자.
그러면 http://localhost:8080/SimpleGuestBook/ 라고 주소창에 뜨고 환영합니다 라는 말이 뜰 것이다. 이것은 index.jsp를 바로 실행한 것이기 때문에
http://localhost:8080/SimpleGuestBook/Welcome.do 라고 쳐보자. 똑같이 나올 것이다.
스트럿츠 설정파일에서 Welcome은 index.jsp를 포워딩하기 때문이다.
만약 실행이 안된다면 프로젝트명에 대고 F5를 눌러서 Refresh를 해보던가 lib파일을 넣지 않았던가 하는 설정 문제 일것이다.
자 오늘은 여기까지-_-;
<servlet>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<servlet-class>org.apache.jsp.index_jsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>org.apache.jsp.index_jsp</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>