05.JSP2014. 4. 1. 16:53
반응형
출처 : http://warmz.tistory.com/739

Ajax 로 다른 도메인에 있는 url 을 호출해 데이터나 HTML을 가져오는건 보안상 안된다고 한다. 되면 참 좋을텐데;;


뭐 아무튼 이걸 해결하기 위한 방법으로 JSONP 라는 형식으로 호출하던가 아니면 Proxy Servlet 을 하나 맹글어 그 서블릿을 거쳐 HttpClient 로 가져오는 방법, 훌래쉬를 이용하는 방법이 있다고 한다.!

그중에서 이번엔 JSONP 형식으로 호출하는 방법을 연구해 보겠다.

JSONP 형식이란 뭐 별건 아닌것 같고 기존에 서버에서 리턴해 주던 

{"key1" : "value1",  "key2" : "value2"} 요런 json 문자열을 

callback({"key1" : "value1",  "key2" : "value2"}); 요런식으로 임의의 함수를 호출해 주는 형식의 문자열로 리턴해 주는것을 말하는것 같다.

즉, jsonp 로 ajax 호출을 하기 위해선 아무 url 이나 안되고  callback({"key1" : "value1",  "key2" : "value2"});  요런식으로 함수안에 json 문자열이 들어간 형식으로 서버에서 리턴을 해줘야 가능하다.

각설하고 jQuery를 활용해 맹글어 보자.



jQuery에서 jsonp 호출하는 방법#1
1
2
3
    //d.key;
});

jQuery에서 jsonp 호출하는 방법#2
1
2
3
4
5
6
7
8
$.ajax({
    dataType : "jsonp",
    jsonp : "callback",
    success : function(d){
        // d.key;
    }
});

방법#1 이나 방법#2는 작동하는게 동일하다. 취향에 맞게 쓰임새에 맞게 쓰면된다. 개인적으로 방법#2 를 여러가지 원하는 ajax 호출 옵션을 줄수 있어서 더 좋아한다.

살짝 설명해 보면 방법#2 에서 쓴 ajax 옵션중 jsonp는 데이터를 넘겨줄 서버에서 받는 callback 함수명 파라메터이다. 서버에 따라 원하는 callback 함수명을 적어줘야 한다. 방법#1을 보면 대충 이해할 수 있다.

jsonp 옵션에다 적어준 함수명은 ajax 호출 url 뒤에다 방법#1에서 처럼 파라메터 형식으로 자동 추가된다.



전체소스코드 client.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!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>Jsonp test with jquery</title>
     
    <script type="text/javascript" src="/resource/js/jquery-1.6.2.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#testBtn").click(function(){
                $.getJSON("http://127.0.0.1:8080/server/data.jsp?callback=?", function(d){
                    $.each(d, function(k, v){
                        $("#getjson").append("<div>" + k + " : " + v + "</div>");
                    });
                    $("#getjson").show();
                });
                             
                $.ajax({
                    url : "http://127.0.0.1:8080/server/data.jsp",
                    dataType : "jsonp",
                    jsonp : "callback",
                    success : function(d){
                        $.each(d, function(k, v){
                            $("#ajax").append("<div>" + k + " : " + v + "</div>");
                        });
                        $("#ajax").show();
                    }
                });
            });
        });
    </script>
     
    <style>
        div{margin-bottom:10px;padding:2px;}
        #getjson{border:1px solid red;display:none;}
        #ajax{border:1px solid blue;display:none;}
    </style>
</head>
 
<body>
    <button id="testBtn">테스트!</button>
    <div id="getjson"></div>
    <div id="ajax"></div>
</body>
</html>



다음으로 간단한 테스트를 위해 초간단 심플 데이터 제공용 jsp 파일을 하나 맹글어 보자. JSON 변환용 라이브러리로 Jackson JSON Processor를 사용했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
 
<%@ page import="java.io.StringWriter"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
 
<%@ page import="org.codehaus.jackson.map.ObjectMapper"%>
 
<%
    Map<String, String> dummyData = new HashMap<String, String>();
    dummyData.put("value1", "값1");
    dummyData.put("value2", "값2");
    dummyData.put("value3", "값3");
    dummyData.put("value4", "값4");
     
    StringWriter sw = new StringWriter();
     
    // Jackson JSON Mapper 를 사용해서 Map 을 JSON 문자열로 변환
    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, dummyData);
     
    request.setAttribute("sw", sw);
%>
 
<%-- ajax 에서 넘겨준 callback 함수 파라메터 가져오기 --%>
${param.callback}(${sw});
ajax로 호출한 url 경로에 맞게금 /server/data.jsp 로 저장하고 http://localhost:8080/client.html 로 접속해보자. 왜냐하면 localhost 랑 127.0.0.1 은 도메인이 다르니깐.  

음 잘 작동된다~~ 초간단 심플 예제이기 때문에 간단하게 JSP로 구현했는데 다음번에 쫌더 실제적으로 프로젝트에 써먹을수 있도록 Spring으로 예제를 하나 맹글어 봐야긋다~

[샘플소스]CrossDomain1.war


Posted by 1010
05.JSP2013. 2. 13. 16:20
반응형
Posted by 1010
05.JSP2012. 4. 9. 11:35
반응형

ScriptX printing: technical manual

January 2011 (Version 6.6 and later)


Contents

Overview
Introduction
Summary of examples
Advanced Control of HTML Printing with ScriptX
Technical support
How do I use ScriptX?
Client-side (within Internet Explorer)
Basic functionality: smsx.cab
Advanced functionality: smsx.cab
How to check whether or not the object is properly installed
Testing your print-outs
Server-side deployment
Within a desktop application
Reference

Overview

Introduction

MeadCo's ScriptX is a suite of ActiveX technology components designed to provide absolute control over document printing operations from client and server computers running the Microsoft Windows Web Browsing Platform.

Part of its purpose is to ensure the consistent formatting and appearance of printed output from any local or networked printer, regardless of the printing attributes already set in that computer's Internet Explorer (IE) browser. ScriptX applies a document author's desired attributes at the time of printing browser window or framed content, but thereafter automatically restores all default settings and makes no permanent changes.

ScriptX 1.0 was introduced by MeadCo in 1998 as a freely distributable utility offering a limited set of print formatting functionality - the scripted control of the printing of HTML frame or window content (with or without a prompt), and the specification by script of printing parameters such as page headersfootersmarginsand paper orientation within IE.

That basic functionality is still available at no charge and is freely distributable. Features that are part of that 'free' printing subset are marked in this document asbasic.

With the releases of later versions, significantly more advanced printing functionality was introduced which is only accessible in the presence of a paid-for MeadCopublishing license.

Target platform

ScriptX has been tested on and supports Microsoft Windows Web Browsing Platform versions 4.01 SP1 - 7.0 on all Microsoft Windows Win32 OS platforms (including Vista).

ScriptX v6.4 and later no longer support Windows 9x/NT. For maintenance support of these operating systems, please see ScriptX win9xNT/NT Maintainance Mode Binaries.

ScriptX v6.4 and later are supported on all Microsoft Windows client and server platforms from Windows 2000 onwards with Internet Explorer 5.5 or later.

Product credits

ScriptX has been widely adopted and acknowledged by the Web and intranet development communities. Check out:

Summary of examples

    Basic
    Illustrates the straightforward use of the freely distributable ScriptX basic printing functionality: headersfootersmargins and paper orientation.

    Advanced
    Illustrates the typical use of ScriptX advanced printing functionality for which a publishing license is required.

    Techie
    An all-in-one technical example illustrating the most advanced use of licensed ScriptX functionality.
    Printing reports and customised documents
    Provides a discussion of printing customised documents and reports with ScriptX and a number of samples of differing techniques. A download of all the sample code is included.
    Direct printing
    Illustrates direct printing to a Zebra thermal label printer using the ZBL command language, a publishing license is required.

Feel free to investigate the source code from any of the examples and to cut & paste fragments into your own applications.

Advanced control of HTML Printing with ScriptX

Advanced printing functionality can only be used with a paid-for publishing license. Some of the advanced features enabled with a license are:

  • Control over the printing of a document's background color and images (printBackground).

  • SetMarginMeasure method to ensure that the chosen unit of measure for margins (inches or millimeters) will be consistent across machines with different locale settings.

  • Facilities to select a non-default printer, paper size & source, page range & collation and number of copies to print.

  • Reliability and scalability. The PrintHTML(url) method can queue and print any number of documents without compromising system performance. This is especially important for server side printing. On the client side, PrintHTML works in the HTTP session context of the calling page (SSL is supported as well).

  • Precise tracking of spooler activity (IsSpoolingWaitForSpoolingCompleteonafterprint). By default, when the Internet Explorer window is closed or the page navigated away from whilst a print-out is still being spooled, the user will be prompted. The prompt can be customized or disabled (onbeforeunload).

  • Print settings changes (headersbasicfootersbasicmarginsbasicpaper orientationbasicprinter namepaper sizepaper sourcepage range selectionnumber of copiescollationduplex mode) once made from script now become active for Internet Explorer's native UI Print... and Page Setup... commands, as well as for the native window.print() script method, during the time that the document is displayed. Now an author doesn't need to put a [Print] button on an HTML page.

  • Internet Explorer's native printing UI can be trapped and cancelled, or handled in a particular way (disableUIonuserprintonuserpreviewonuserpagesetup). A document's DHTML user interface can also be updated in response to user changes in the Page Setup and Print dialogs (onpagesetup). See the Techie printing example for an illustration of UI handling.

  • All changes made to print settings affect only the current document (in the current tab) when it is printed or previewed. Settings are untouched in other IE windows or tabs and will not apply to any other documents viewed in the current window/tab.

  • A redirect of print data can be made to a specified file name (printToFileName).

  • Basic printing of Microsoft Officetm documents.

  • Printing of PDF documents (PrintPDF and BatchPrintPDF).

Backwards compatibility

All releases of ScriptX are fully backwards compatible with previous releases and for advanced functionality will work with all existing publishing licenses. ScriptX works in close concert with the Microsoft Windows Web Browsing Platform and as a result  is updated to work with all latest releases and patches. All code updates are free; there is never a charge for obtaining the latest code.

We strongly recommend that you update your <OBJECT> elements to reference the current version 7,0,0,8 and update smsx.cab on your servers.

  • An important compatibility issue is that ScriptX printing will always prompt when called in the context of Internet Explorer's Internet Security Zone (check the zone icon in the browser's status bar). This is done to prevent anonymous Internet content invoking printing without a prompt (see PRB: Printing with WebBrowser from Internet Explorer Raises Print Dialog Box in Internet Explorer 5).

    For the My Computer, Local Intranet and Trusted Sites Security Zones promptless printing will work. If you need promptless printing for the Internet Security Zone, you should obtain a publishing license that will bind the deployment of ScriptX to the URL addresses from which you want to serve ScriptX-enabled content.

  • Another important note concerns margin units of measure (inches and millimeters). By default ScriptX uses the units of measure set on the client machine. This is OK when pages are being authored for a known environment such as a small corporate intranet where all Regional Settings are identical, but in a broader environment users' Number settings are certain to vary. So an author should specify the SetMarginMeasure method with a value of either 1 (mm) or 2 (inches). ScriptX will then print to the margins specified regardless of -- and without affecting -- a user's default Regional Number Settings.

What's New Summary

A full listing of the release of ScriptX versions and the modifications they contained is available on the ScriptX History page.

v6.2

Version 6.2 introduces the printerControlJobs and Job objects to provide detailed information about the available printers and control of the print queue for a printer. The use of methods that control the print queue requires that the user has administrator rights on the printer.

Also included in this version is an extension of the MeadCo licensing scheme to provide a usable distribution model and allow the use of ScriptX within desktop applications.

v6.3

Version 6.3 provides support for Internet Explorer 7 on Windows XP and Windows Vista; v6.3 is required on the IE 7 platform ... previous versions of ScriptX arenot compatible.

This release includes a new print template that provides the same functionality as that within Internet Explorer 7 - scale to fit printing by default and enhanced print preview with draggable margins and switchable headers. This template is available for all versions of Internet Explorer from v5.5 so, whilst your users may be running anything from IE 5.5 onwards, you can give them all a consistent print experience.

The use of the new template is optional - by default ScriptX will use the default template for the platform (IE5.5 style on IE 5.5/IE 6 and IE 7 style on IE7. The particular template required can be specified in script using the templateUrl property or may be specified as a parameter to the ScriptX object.

Frames can now be previewed. This was a MaxiPT only feature but is now also included in the Advanced licensed feature set for ScriptX.

A code review has been undertaken with this release, with APIs checked for behaviour and consistency. This has resulted in some cases where in previous releases a property/method would not report an error when an error occurred - errors are now reported. This may necessitate changes to script code if it was assumed that code would run without error.

v6.3.435

From the first build of this version onwards, ScriptX comes in a single signed CAB - smsx.cab. In addition to fixes for a number of issues, this release introduces improvements for application licenses and the ability to install license updates without requesting permission from the user (this will only occur for updates of an already accepted license).

Two new methods are introduced to provide additional control over the behaviour of the new IE 7 style template. These methods require a publishing license:

  • SetPreviewZoom -  provides control over the zoom factor used on print preview.
  • SetPrintScale -  provides control over the scaling used when printing.

v6.3.436

Version 6,3,436 introduces the ability to send raw text to an attached printer. The text is not rendered to the printer, it is interpreted by the printer. This is useful in scenarios such as controlling a thermal label printer. For more information, see rawPrinting.

v6.4

ScriptX v6.4 and later no longer support Windows 9x/NT. For maintenance support of these operating systems, please see ScriptX win9xNT/NT Maintainance Mode Binaries.

This release also introduces Enterprise+ licensing and preliminary support for IE8. Please note that this release has been tested against IE 8 Beta 1 only, there are no known problems other than under Vista where there are a number of small issues which will be addressed in future releases of IE/ScriptX.

v6.5

ScriptX v6.5 and later fully supports IE8 on all supported platforms (Windows 2000 and later). ScriptX 6.5 is a required upgrade for correct operation with IE8.

In support of IE8 one new property has been added: headerFooterFont. Note that scale to fit and print background colours functionality was already included with ScriptX.

A number of problems have also been resolved, including an issue with the SetPageRange() method. Our documentation has been updated to better describe its behaviour. A development history - as well as latest test version of ScriptX - is available on the ScriptX beta page.

v6.6

ScriptX v6.6 introduces a 64-bit Edition for x64 systems and controlled printing of PDF documents with the licensed Corporate 32-bit Edition of ScriptX. ScriptX v6.6 also includes support for Internet Explorer 9 Beta 1 and IE 9 Preview up to Preview 7.

ScriptX 6.6 is a required upgrade for correct operation with IE9.

How do I use the ScriptX object?

Before reading further, please have a look at our illustrative BasicAdvanced and Techie examples of ScriptX printing to get an idea of what ScriptX can do for you.

There are three scenarios in which ScriptX provides the solution for printing of HTML documents with the Microsoft Windows Web Browsing Platform:

  1. Within the Internet Explorer browser, on client-side HTML or XML pages. Here, ScriptX provides full scripted control of the printing experience within IE, allowing choosing the output printer, orientation, page header and footers etc and the initiation of the print. ScriptX is ideal for deployment within web applications hosted within Internet Explorer.
  2. On the server, where ScriptX performs as part of server side request processing, printing an html document loaded from the same or different server.
  3. As part of a desktop application, ScriptX can be used to print HTML documents from the file system, a web server or generated as an 'inline' string.

Note that the use of ScriptX on the server always requires a license. All licenses are available (on request to feedback@meadroid.com) for a trial period to enable full and proper evaluation of the suitability of ScriptX for a particular usage.

Client-side deployment within Internet Explorer (x86 32-Bit Edition).

Typically ScriptX is deployed as a client-side ActiveX control, instantiated and scripted on an HTML or XML page as an <OBJECT> element. Download and installation is a one-time client-side event and is handled automatically by the standard Internet Explorer Component Download technology.

Requirements for a successful installation

  • The end user's system must have the "Download Signed ActiveX Controls" and "Script ActiveX control marked as safe for scripting" security settings enabled for the corresponding Security Zone. These are the default settings for the My ComputerLocal IntranetTrusted Sites and Internet Security Zones.
  • In addition, on Windows 2000 systems and later, the user must be logged on as an Administrator/Power User with the ability to write to the HKEY_LOCAL_MACHINE registry hive and the Windows system folder (typically c:\windows\system32). For Windows Vista and later, the user must be able to complete an Account Control elevation dialog, either through accepting the dialog since they are logged in as an administrator or by entering the user name and password of a suitable administrators account.

Alternative installers (and 64-bit Edition of ScriptX)

If the above requirements cannot be met we suggest that you ask to review our Corporate Resource Kit, a $500-per-year cost-option for licensees which comes as a collection of .msi and merge modules and documentation. The Corporate Kit enables more modern and flexible installation choices than can be provided from our historic .cab-based schema, including the ability to develop a custom installer to requirement using the supplied merge modules.

In addition, the Corporate Resource kit includes the 64 bit Edition of ScriptX. Whilst primarily intended for deployment on server systems for server side printing, the 64 bit Edition can be deployed for use with the 64 bit Edition of Internet Explorer. Please note that, at the time of writing, the default edition of Internet Explorer is 32 bit on all Microsoft Windows operating systems, including 64 bit OSs.

Codebase referencing and use of the object

From the first 6,3,435,x version onwards, ScriptX comes as standard in a single signed CAB - smsx.cab - which is part of a download package obtainable from theScriptX site. The CAB file should be placed on the web server and its location should be referenced by the CODEBASE attribute of the <OBJECT> tag, as shown below.

NOTE: In your own code, we recommend that you place the ScriptX <OBJECT> elements in the document's <BODY> container.

  • Make sure that you provide the correct relative or fully-qualified path to the CAB file and the correct version info (7,0,0,8) in your CODEBASE attributes.

  • Start to script the ScriptX object only when the page is fully loaded i.e. once the window.onload event has occured.

  • Use the defer attribute where appropriate in your scripts: <SCRIPT defer>...<SCRIPT> and avoid immediate script statements (i.e. code which is outside of any function scope). This is an under-appreciated but very useful feature which instructs the script to execute only when the whole document's DHTML content is completely parsed. This way you can be sure of accessing every element on the page.

  • The 'de-facto' standard, started by this documentation is to use the id 'factory' for the ScriptX object. Any id that is desired may be used.

  • For simplicity, these documents directly refer to the object via its id rather than using document.getElementById(). Either approach is acceptable; if the samples are inspected via View Source it will be seen that the jQuery library is used in the samples, along with a wrapper class to safely access the ScriptX object. The use of jQuery etc is also entirely optional.

The following code snippets assumes that smsx.cab exists in the same folder as the hosting page itself.

Basic functionality:

<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
  codebase="smsx.cab#Version=7,0,0,8">
</object>

The Basic printing example illustrates the use of the basic printing subset.

The viewastext attribute prevents an authoring tool such as Microsoft FrontPagetm or Visual InterDevtm from running the object at design time. This attribute is not required if you do not use these tools and note that it can cause problems in some environments; for example strict xhtml documents.

NOTE: with the 'basic' subset, you can only script headerfooterpage marginspaper orientationPrint and PageSetup methods and properties.

Specifying a template (e.g. IE 7)

With version 6.3 and later, you may specify the template to use; this is particularly useful when wishing to provide the Internet Explorer style template (default scaled to fit printing) to users with IE 5.5/6.0 browsers or when specifying the use of the MaxiPT template.

<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
  codebase="smsx.cab#Version=7,0,0,8">
	<param name="template" value="MeadCo://IE7" />
</object>

The ability to specify a particular in-built template is included in the 'basic' subset.

Advanced functionality:

<!-- MeadCo Security Manager -->
<object viewastext style="display:none"
  classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
  codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id=factory viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

NOTE: the {0ADB2135-6917-470B-B615-330DB4AE3701} value of the GUID parameter used above identifies the MeadCo evaluation license that authors may use to experiment with Advanced printing capabilities. The license validates local filesystem (file://) and local website (http://localhost/) content for evaluation purposes only on a single development computer.

The evaluation license is periodic. It will expire in a few months and will be replaced by a new one with a different GUID, so any code depending on the evaluation license may suddenly stop working at any time.

Registered customers are issued with an unique license identifier and a digitally signed sxlic.mlf license file. See the licensing page for more details.

Check out the sources of the Advanced and Techie printing examples for a complete illustration of how to use licensed ScriptX functionality. The following JScript code snippet shows how to modify printing settings so as to print to a specific printer:

<script defer>
function SetPrintSettings() {
  // -- advanced features
  factory.printing.SetMarginMeasure(2); // measure margins in inches
  factory.printing.printer = "HP DeskJet 870C";
  factory.printing.paperSize = "A4";
  factory.printing.paperSource = "Manual feed";
  factory.printing.collate = true;
  factory.printing.copies = 2;
  factory.printing.SetPageRange(false, 1, 3); // need pages from 1 to 3

  // -- basic features
  factory.printing.header = "This is MeadCo";
  factory.printing.footer = "Advanced Printing by ScriptX";
  factory.printing.portrait = false;
  factory.printing.leftMargin = 1.0;
  factory.printing.topMargin = 1.0;
  factory.printing.rightMargin = 1.0;
  factory.printing.bottomMargin = 1.0;
}

function Print(frame) {
  factory.printing.Print(true, frame) // print with prompt
}
</script>

A subtle JScript syntax issue may occur when setting a printer name that contains back slashes. Don't forget to double the slashes:

factory.printing.printer = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

How to check whether or not the object is properly installed

Upon the window.onload event, test whether or not the object property of the ScriptX or the Security Manager object returns as a valid object. The way to do that is shown in the script snippet below.

In the event that you experience any problems with automatic client-side download and installation, check out HOWTO: Find More Information About Why Code Download Failed and Description of Internet Explorer Security Zones Registry Entries as part of your troubleshooting.

<!-- MeadCo Security Manager - using the evaluation license -->
<object id="secmgr" viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  if ( !factory.object ) {
    alert("MeadCo's ScriptX Control is not properly installed!");
    navigate("scriptx-install-error.htm");
    return;
  }
  if ( !secmgr.object ) {
    alert("MeadCo's Security Manager Control is not properly installed!");
    navigate("secmgr-install-error.htm");
    return;
  }
  if ( !secmgr.validLicense ) {
    alert("The MeadCo Publishing License is invalid or has been declined by the user!");
    navigate("license-error.htm");
    return;
  }
  alert("Ready to script MeadCo's ScriptX!")
}
</script>

Testing your print-outs

The development and testing of code to produce good-looking printed reports usually takes a number of iterations. To save toner, paper, trees and our own precious time :-) we regularly use the FinePrinttm application from FinePrint Software.

FinePrinttm installs a virtual printer driver that serves as indirection layer between the printing application (Internet Explorer in our case) and a physical or networked printer. In 'bypass' mode it lets us accurately preview and repaginate ScriptX-enabled content before it is actually printed or discarded.

It's also a very handy testing device with which to diagnose printing problems. So because we are physically unable to test ScriptX with every model and version of printer and printer driver that exists in the world, we would greatly appreciate it if you would try printing to the FinePrint driver before reporting errors against ScriptX from your particular printing environment.

NOTE: Mead & Co Limited has no commercial affiliation with FinePrint Software, LLC.

Working with Visual Studio and ASP.NET

The samples on this site are implemented using ASP.NET and the MVC extensions. The samples system is used in various locations, including the Infopages where the latest release, hotfixes and development versions of ScriptX may be obtained. The samples system itself provides a compreshensive set of demonstrations of the capabilities and working of ScriptX under all document types and modes.

When working with ASP.NET we recommend creating a server-side control or for MVC a partial view that will outout the various object tags required by ScriptX. We recommend values such as codebase location and version are obtained from AppSettings stored in web.config.

Please note that when working with ASP.NET Forms we recommend that the ScritpX objects are placed outside the <form /> element.

Technical support

Licensees of ScriptX' advanced printing functionality are entitled to unlimited direct-to-company email support and access to new versions of the ScriptX software as-and-when issued, both at no additional charge.

Please send us feedback & bug reports.

Web support links

Microsoft Internet Explorer printing and Internet Explorer Component Download support articles:

INFO: WebCast: How Does Internet Component Download Work?

HOWTO: Find More Information About Why Code Download Failed

PRB: Trust Provider Warning Message Appears When You Attempt to Download Components

PROBLEM: Blank Page Is Printed in Internet Explorer 5.5

General information on Internet Explorer printing:

Beyond Print Preview: Print Customization for Internet Explorer 5.5

Print Preview 2: The Continuing Adventures of Internet Explorer 5.5 Print Customization

Print Template Reference

Style Sheets and Printing횂쨩

Inside Technique : Printing Techniques횂쨩

Printing Tables on Multiple Pages

INFO: Page Break Styles Supported Only with Block Elements


ScriptX printing: technical reference

Unless otherwise indicated by the basic icon, the use of any property or method requires a publishing license.

Objects

BinsFormsfactoryprintingprinterControlJobsJobrawPrinting

Properties

attributesbottomMargincollatecopiescurrentPrinterdisableUIduplexfooterheaderheaderFooterFontisLocalisNetworkisSharedJobsleftMargin,locationnameonafterprintonbeforeunloadonpagesetuponuserpagesetuponuserprintonuserprintpreviewpageHeightpageWidthpaperSizepaperSource,port,  portraitprintBackgroundprinterprinter (direct printing), printerControlprintToFileNamerightMarginserverNameshareNamestatustemplateURL,topMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

Methods and Functions

BatchPrintPDFDeleteDefaultPrinterEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueuePageSetup,PausePreviewPrintPrintDocumentPrintHTMLPrintPDFPrintSetupPrintStringPurgeRestartResumeSetMarginMeasureSetPageRangeSetPrintScale,SetPreviewZoomSleepWaitForSpoolingComplete

Objects

Bins


Description

Lists the available paper sources for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScriptfor..each loop).

The names returned are suitable for use with the paperSource property.

Syntax

oJobs = printerControl.Bins

Properties

Item(nIndex) - returns the name of the paper source item at nIndex
Count - returns the number of available paper sources.

Methods

None.

Example

<script defer>
function listBins() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Bins;
	var e = new Enumerator(j);
	var s = "";
	while ( !e.atEnd() ) {
		if ( s.length > 0 ) s+="\n";
		s += e.item(0);
		e.moveNext();
	}
	alert("There are " + j.Count + " available sources:\n\n" + s);
}
<script>

Applies To

printerControl

See Also

paperSource

Forms


Description

Lists the available paper sizes (forms) for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScriptfor..each loop).

The names returned are suitable for use with the paperSize property.

Syntax

oJobs = printerControl.Forms

Properties

Item(nIndex) - returns the name of the paper at nIndex
Count - returns the number of available paper sizes.

Methods

None.

Example

<script defer>
function listForms() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Forms;
	var e = new Enumerator(j);
	var s = "";
	while ( !e.atEnd() ) {
		if ( s.length > 0 ) s+="\n";
		s += e.item(0);
		e.moveNext();
	}
	alert("There are " + j.Count + " available paper sizes:\n\n" + s);
}
<script>

Applies To

printerControl

See Also

paperSize

factory


Description

Represents the ScriptX object itself on an HTML page for scripting by its id . For historical reasons, we name it factory.

For WSH or ASP (i.e. server-side) use only, create a ScriptX instance dynamically with the JScript new ActiveXObject횂쨩 or the VBScript CreateObject횂쨩.

Note that you can not use CreateObject or new ActiveXObject to call ScriptX client-side. You should call ScriptX in all client-side cases by the id of the on-page ScriptX object.

See How do I use the ScriptX object for deployment details.

Examples

HTML page:

<object id=factory viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814"
codebase="smsx.cab#Version=7,0,0,8">
</object>

WSH script (JScript):

var factory = new ActiveXObject("ScriptX.Factory")
factory.printing.PrintHTML("http://msdn.microsoft.com/workshop/author/script/dhtmlprint.asp")

ASP page (VBScript):

<%
 set factory = CreateObject("ScriptX.Factory")
 factory.printing.PrintHTML "http://localhost/orders/order.asp?number=" & Request.Form("number")
 set factory = nothing
%>

Properties

printingrawPrinting

printing


Description

Represents the printing functionality of ScriptX. See HTML Printing with ScriptX for more information and examples.

Syntax

printing = factory.printing

Properties

bottomMargincollatecopiescurrentPrinterdisableUIduplexfooterheaderheaderFooterFontleftMarginonafterprintonbeforeunload,onpagesetuponuserpagesetuponuserprintonuserprintpreviewpageHeightpageWidthpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

Methods

BatchPrintPDFDefaultPrinterDoPrintEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueue,PageSetupPreviewPrintPrintHTMLPrintPDFPrintSetupPrintXMLSetMarginMeasureSetPageRangeSetPrintScaleSetPreviewZoomSleep,WaitForSpoolingComplete

Applies To

factory

printerControl


Description

Represents the ability to determine a range of printer properties and control the print queue for the printer. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the string does not exist or is written incorrectly then an error will be thrown (e.g. "The printer name is invalid").

Syntax

oControl = factory.printing.printerControl(sPrinterName)

Properties

attributesBinsFormsisLocalisNetworkisSharedJobslocationnameport,  serverNameshareNamestatus

Methods

PausePurgeRestartResume

Example

<script defer>
function networkServer() {
	var oControl = factory.printing.printerControl(factory.printing.currentPrinter);
	if ( oControl.isNetwork )
		alert("The current printer is on the network server: " + oControl.serverName);
}
<script>

Applies To

printing

rawPrinting (v6.3.436 and later)


Description

Represents the direct printing from within Internet Explorer functionality of ScriptX. Version 6.3.436 or later of ScriptX is required.

Note: Direct printing is a cost-option which can be enabled on a 'standard' client-side license for an additional fee of $500.

Direct printing allows for printing to programmable devices such as thermal label printers, whereby a label string can be sent directly to the printer. The Internet Explorer print engine is not used and takes no part in the process. The functionality available from rawPrinting is completely separate from that available from the printing object, and for this reason settings such as printerpaper sizeorientation, etc. that may have been set on the printing object for Internet Explorer do not apply to the rawPrinting object.

NOTE: rawPrinting is not supported in any form of usage outside of Internet Explorer.

Syntax

raw = factory.rawPrinting

Properties

printer

Methods

printStringprintDocument

Applies To

factory

Jobs


Description

Represents the list of jobs currently in the queue for a printer. The object is a collection (it can be passed to the JScript Enumerator method or used in a VBScript for..each loop).

Syntax

oJobs = printerControl.Jobs

Properties

Item(nIndex) - returns a printJob object for the item at nIndex
Count - returns the number of items in the queue.

Methods

None.

Example

<script defer>
function listJobs() {
	var j = factory.printing.printerControl(factory.printing.DefaultPrinter()).Jobs;
	var e = new Enumerator(j);
	alert("There are " + j.Count + " jobs in the queue");
	while ( !e.atEnd() ) {
		alert("Job name: " + e.item().document);
		e.moveNext();
	}
}
<script>

Applies To

printerControl

See Also

EnumJobsGetJobsCount

Job


Description

Represents a single job in the queue for a printer. A job is obtained from the list of print jobs available on a printer.

Syntax

oJob = printerControl.Jobs.Item(nIndex)

Properties

All properties are read only:

PropertyDescripion
documentSpecifies the name of the print job, typically the title of the html document that has been printed.
machineNameSpecifies the name of the machine that created the print job.
pagesPrintedSpecifies the number of pages that have printed. This value may be zero if the print job does not contain page delimiting information.
positionSpecifies the job's position in the print queue.
printerNameSpecifies the name of the printer for which the job is spooled.
sizeSpecifies the size, in bytes, of the job.
statusSpecifies the job status, can be one or more of the following values:
MeaningValue
JOB_STATUS_PAUSED0x00000001
JOB_STATUS_ERROR0x00000002
JOB_STATUS_DELETING0x00000004
JOB_STATUS_SPOOLING0x00000008
JOB_STATUS_PRINTING0x00000010
JOB_STATUS_OFFLINE0x00000020
JOB_STATUS_PAPEROUT0x00000040
JOB_STATUS_PRINTED0x00000080
JOB_STATUS_DELETED0x00000100
JOB_STATUS_BLOCKED_DEVQ0x00000200
JOB_STATUS_USER_INTERVENTION0x00000400
JOB_STATUS_RESTART0x00000800
statusTextA string containing a description of the status. This may be provided by the printer driver or may be generated by ScriptX from the value of status. If generated by ScriptX the description is in English only.
submittedAtSpecifies the time when the job was submitted.
totalPagesSpecifies the number of pages required for the job. This value may be zero if the print job does not contain page delimiting information.
userNameSpecifies the name of the user who owns the print job.

The value of all properties are determined at the time that the Jobs collection is created, no properties are dynamic (for example a loop inspecting the value of pagesPrinted will not see the value decrease as might be expected).

Methods

DeletePauseRestartResume

Properties

attributes


Description

Returns the attributes of the printer; can be any reasonable combination of the following values:

ValueMeaning
PRINTER_ATTRIBUTE_DEFAULT (0x00000004)Windows 95/98/Me: Indicates the printer is the default printer in the system.
PRINTER_ATTRIBUTE_DIRECT (0x00000002)Job is sent directly to the printer (it is not spooled).
PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST (0x00000200)If set and printer is set for print-while-spooling, any jobs that have completed spooling are scheduled to print before jobs that have not completed spooling.
PRINTER_ATTRIBUTE_ENABLE_BIDI (0x00000800)Windows 95/98/Me: Indicates whether bi-directional communications are enabled for the printer.
PRINTER_ATTRIBUTE_FAX (0x00004000)Windows XP: If set, printer is a fax printer. 
PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS (0x00000100)If set, jobs are kept after they are printed. If unset, jobs are deleted.
PRINTER_ATTRIBUTE_QUEUED (0x00000001)If set, the printer spools and starts printing after the last page is spooled. If not set and PRINTER_ATTRIBUTE_DIRECT is not set, the printer spools and prints while spooling.
PRINTER_ATTRIBUTE_SHARED (0x00000008)Printer is shared.
PRINTER_ATTRIBUTE_WORK_OFFLINE (0x00000400)Windows 95/98/Me: Indicates whether the printer is currently connected. If the printer is not currently connected, print jobs will continue to spool.
PRINTER_ATTRIBUTE_PUBLISHED (0x00002000)Windows 2000/XP: Indicates whether the printer is published in the directory service.
PRINTER_ATTRIBUTE_NETWORK (0x00000010)Printer is a network printer connection.
PRINTER_ATTRIBUTE_LOCAL (0x00000040)Printer is a local printer.
PRINTER_ATTRIBUTE_RAW_ONLY (0x00001000)Indicates that only raw data type print jobs can be spooled.

 

Syntax

attributes = printerControl.attributes

Settings

This is a read only property.

Applies To

printerControl

bottomMarginbasic


Description

Specifies the bottom margin height for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableBottom), in which case it will be automatically corrected to the minimum allowed value. If top and bottom margins are set to overlap, they will be corrected to an arbitrary default value of 1/10 of page height.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The bottomMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.bottomMargin = numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

leftMarginpageHeightpageWidthportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

collate


Description

Specifies whether or not to collate the pages of HTML print-outs when more than one copy is printed.

Syntax

printing.collate = true|false

Settings

This is a read/write property. Use true to collate.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

duplexprinter

PrintPrintHTMLPrintSetup

copies


Description

Specifies the number of copies for HTML print-outs.

Syntax

printing.copies = numCopies

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

collateduplexprinter

PrintPrintHTMLPrintSetup

currentPrinter


Description

Specifies the printer to print to. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the string does not exist or is written incorrectly, printing will be directed to the default printer.

Syntax

printing.currentPrinter = sPrinterName

Settings

This a read/write property. With JScript, take care to double a backslash if one appears in the printer name, as in the example below.

Usage

The internal implementation of writing to the currentPrinter property is the same as writing to the printer property, other than the implementation ofcurrentPrinter does not 'eat' any error. Therefore an error in currentPrinter will be reported in the same way as any other error that occurs in an ActiveX object property/method call.

Example

factory.printing.currentPrinter = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

Applies To

printing

See Also

HTML Printing with ScriptX

printerEnumJobsEnumPrintersGetJobsCountIsTemplateSupportedPrint

 

disableUI


Description

Set to true to disable all of Internet Explorer's printing facilities, including the File/Page Setup, File/Print main menu commands, the Print context menu command and the window.print() scripting method. Given this, the only way left to print is via the ScriptX Print and PrintHTML methods.

Syntax

printing.disableUI = true|false

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing example.

See Also

HTML Printing with ScriptX

onpagesetuponuserpagesetuponuserprintonuserprintpreview

PageSetupPreviewPrintPrintSetup

duplex


Description

Duplex mode (if supported by the targeted printer).

Syntax

printing.duplex = number

Settings

This is a read/write property. Use for simplex mode (no duplex), for vertical duplex, for horizontal duplex.

Applies To

printing

See Also

HTML Printing with ScriptX

collatecopies

PrintPrintHTMLPrintSetup,

footerbasic


Description

Specifies the string to be used as the footer for HTML print-outs. String can include Internet Explorer header/footer metasymbols. If you need to use HTML for your headers and footers, check MaxiPT 1.0횂쨩 (Internet Explorer 5.5 or later).

The footer property is part of the basic freely-distributable printing subset.

Syntax

printing.footer = sFooter

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

header

headerFooterFont

PageSetupPrintPrintHTML

headerbasic


Description

Specifies the string to be used as the header for HTML print-outs. String can include Internet Explrore header/footer metasymbols. If you need to use HTML for your headers and footers, check MaxiPT 1.0횂쨩 (Internet Explorer 5.5 or later).

The header property is part of the basic freely-distributable printing subset.

To print specific information as part of the header or footer, include the following characters as part of the string:

ShorthandMeaning
&wWindow title
&uPage address (URL)
&dDate in short format (as specified by Regional Settings in Control Panel)
&DDate in long format (as specified by Regional Settings in Control Panel)
&tTime in the format specified by Regional Settings in Control Panel
&TTime in 24-hour format
&pCurrent page number
&PTotal number of pages
&&A single ampersand (&)
&bThe text immediately following these characters as centered.
&b&bThe text immediately following the first "&b" as centered, and the text following the second "&b" as right-justified.

Syntax

printing.header = sHead

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

footer

headerFooterFont

PageSetupPrintPrintHTML

headerFooterFontbasic


Description

From version 6.5.439, ScriptX supports retrieving and specifying the font used to render the document header and footer. The use of this feature requires Internet Explorer 8 or later.

Specifies or retrieves the description of the font to use. The font is described using a css style definition, one or more of the following semicolon-delimited values:

ValueDescription
font-familyThe font family name to use.
font-sizeThe size to use, units should be pixels.
colorThe colour for rendering the text, given as an RGB value - for example, rgb(255,0,0)
font-weightThe weight of the font as normal or bold
font-styleThe font style, as italicnormal, or oblique

Note: No error is thrown if this property is used with versions of Internet Explorer prior to 8 - settings are simply ignored.

Syntax

printing.headerFooterFont sFontSpec

Settings

This a read-write property.

Applies To

printing

Example

factory.printing.headerFooterFont = "font-family: Comic Sans MS; font-size: 10px; color: rgb(0,128,0); font-weight: bold;"

See Also

headerfooter

isLocal


Description

Returns whether the printer is a local printer (true) or not (false). isLocal tests whether PRINTER_ATTRIBUTE_LOCAL is set in the attributes.

Syntax

bIs = printerControl.isLocal

Settings

This is a read only property.

Applies To

printerControl

isNetwork


Description

Returns whether the printer is a network printer (true) or not (false). isNetwork tests whether PRINTER_ATTRIBUTE_NETWORK is set in the attributes.

Syntax

bIs = printerControl.isNetwork

Settings

This is a read only property.

Applies To

printerControl

isShared


Description

Returns whether the printer is a shared printer (true) or not (false). isShared tests whether PRINTER_ATTRIBUTE_SHARED is set in the attributes.

Syntax

bIs = printerControl.isShared

Settings

This is a read only property.

Applies To

printerControl

leftMarginbasic


Description

Specifies the left margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableLeft), in which case it will be automatically corrected to the minimum allowed value. If left and right margins overlap, they will be corrected to an arbitrary default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The leftMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.leftMargin numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

pageHeightpageWidthportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

location


Description

Returns a string describing the physical location of the printer.

Syntax

sLoc = printerControl.location

Settings

This is a read only property.

Applies To

printerControl

name


Description

Returns a string giving the name of the printer.

Syntax

sName = printerControl.name

Settings

This is a read only property.

Applies To

printerControl

onafterprint


Description

Event handler to be called when print spooling is done. The event is applicable to the results of a Print call but not to that of a PrintHTML call. It can be used to update the user interface accordingly. It is similar to the WaitForSpoolingComplete blocking call, but is asynchronous.

Note the difference between ScriptX's onafterprint event and the DHTML window.onafterprint event: the latter occurs after Internet Explorer has just made a document snapshot for printing and not after the actual print spooling job (see PRB: onafterprint Event Fires Before the Print Dialog Box Appears). So these two events are not interchangeable.

In fact, the DHTML window.onbeforeprint and window.onafterprint exist to give the document's script a chance to customize DHTML content before it goes to print-out or preview (and not to signal actual printing). The same effect can be achieved with the CSS  media=print or media=screen specific styles. Check out the following InsideDHTML.com articles: Printing TechniquesUsing CSS to specify alternate document to print out.

Syntax

printing.onafterprint = function_object

Settings

This is a read/write property.

Applies To

printing

Example

<script defer>
factory.printing.onafterprint = AfterPrint;

function AfterPrint() {
  alert("The document has been sent to the print spooler!");
}
</script>

See Also

HTML Printing with ScriptX

onpagesetuponuserpagesetuponuserprintonuserprintpreview

PrintWaitForSpoolingComplete

onbeforeunload


Description

String to prompt a user with when spooling (or a download originated by a PrintHTML call) is still in progress but the page is being closed or navigated away. By default, ScriptX waits 5 seconds in blocking mode to let spooling complete, then prompts the user with the choice to cancel the printing process. The user may decide to wait for another 5 seconds, and so on.

Note: to suppress the prompt you can force the blocking wait state with WaitForSpoolingComplete after any Print or PrintHTML call or before leaving the page. However the use of WaitForSpoolingComplete() after each PrintHTML call in a sequence of calls is not recommended. Use it only after the last call in the sequence.

Syntax

printing.onbeforeunload = string

Settings

This is a read/write property.

Applies To

printing

See Also

HTML Printing with ScriptX

PrintPrintHTMLWaitForSpoolingComplete

onpagesetup


Description

Event handler to be called when the current print or page setup settings are changed on the Internet Explorer Page Setup dialog. 

Use it to update the page's user interface accordingly. This is exactly what the ScriptX Techie Printing example does.

Syntax

printing.onpagesetup = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonuserpagesetuponuserprintonuserprintpreview

PageSetup

onuserpagesetup


Description

Event handler to be called when a user invokes the Page Setup... command from Internet Explorer's File menu. 

You may cancel this operation within the event handler simply by returning, or you may call PageSetup to provide the expected behavior. In the latter case, once the user has made changes on the Page Setup dialog an onpagesetup event will be fired to update the page's user interface. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserpagesetup = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserprintonuserprintpreview

PageSetup

onuserprint


Description

Event handler to be called when a user invokes the Print... command from the Internet Explorer File menu, or presses Print on the document's right-click context menu, or hits the printer button on the toolbar, or presses the Ctrl-P key combination, or when a script calls window.print().

You may cancel this operation within the event handler simply by returning, or you may call Print to provide the expected behavior. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserprint = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserpagesetuponuserprintpreview

PageSetup

onuserprintpreview


Description

Event handler to be called when a user invokes the Preview... command from the Internet Explorer File menu or hits the print preview button on the toolbar.

You may cancel this operation within the event handler simply by returning, or you may call Preview to provide the expected behavior. ScriptX Techie Printing implements this behavior.

Syntax

printing.onuserprintpreview = function_object

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

disableUIonafterprintonpagesetuponuserpagesetuponuserprint

PageSetup

pageHeight


Description

Returns the physical height of the current printer paper selection.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

Syntax

height = printing.pageHeight

Settings

This is a read-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageWidthpaperSizeportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

PageSetupSetMarginMeasure

pageWidth


Description

Returns the physical width of the current printer paper selection.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

Syntax

width = printing.pageWidth

Settings

This is a read-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpaperSizeportraitrightMargintopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupSetMarginMeasure

paperSize


Description

Specifies the paper size for HTML print-outs by its string name. ScriptX tries to find the longest string match amongst the list of available paper size names for the current printer. Read back the paperSize value to see the actual result.

Syntax

printing.paperSize = sPaperSize

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

FormspageHeightpageWidthpaperSourceportraitunprintableBottomunprintableLeftunprintableRightunprintableTop

PageSetupPrintPrintHTMLPrintSetup,

paperSource


Description

Specifies the paper source (tray) for HTML print-outs by its string name. ScriptX tries to find the longest string match amongst the list of available paper source names for the current printer. Read back the paperSource value to see the actual result.

Syntax

printing.paperSource = sPaperSource

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

BinspaperSize

PageSetupPrintPrintHTMLPrintSetup

port


Description

Returns a string string that identifies the port(s) used to transmit data to the printer. If a printer is connected to more than one port, the names of each port will be separated by commas (for example, "LPT1:,LPT2:,LPT3:").

Windows 95/98/Me: This member can specify only one port because multiple ports per printer are not supported.

Syntax

sName = printerControl.port

Settings

This is a read only property.

Applies To

printerControl

portraitbasic


Description

Specifies the page orientation for HTML print-outs.

The portrait property is part of the basic freely-distributable printing subset.

Syntax

printing.portrait = true|false

Settings

This is a read/write property. Use true to specify portrait and false for landscape.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetemplateURLtopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupPrintPrintHTMLPrintSetup

printBackground


Description

Specifies whether or not to print a page's background colors and images.

Syntax

printing.printBackground = true|false

Settings

This is a write-only property.

Applies To

printing

Example

Check out the source code of the ScriptX Techie Printing example.

See Also

HTML Printing with ScriptX

PreviewPrintPrintHTML

printer


Description

Specifies the printer to print to. Only the exact printer name strings as they appear on Internet Explorer's Print dialog can be specified. If the printer specified does not exist or is written incorrectly, printing will be directed to the default printer.

Syntax

printing.printer = sPrinterName

Settings

This a write-only property. With JScript, take care to double a backslash if one appears in the printer name, as in the example below.

Please note that providing an invalid name will not raise an error - the request will be ignored and the printer to use remain unchanged. To trap errors specifying the printer to use, use the currentPrinter property.

Applies To

printing

Example

factory.printing.printer = "\\\\FS-LYS-01\\HP5n-759" // print to \\FS-LYS-01\HP5n-759

Also check out the source code of the ScriptX Techie Printing example.

SSee Also

HTML Printing with ScriptX

rawPrinting

bottomMargin,collatecopiescurrentPrinterduplexfooterheaderleftMarginpaperSizepaperSourceportraitprintBackgroundprintToFileName,rightMargintemplateURLtopMargin

DefaultPrinterEnumJobsEnumPrintersGetJobsCountIsSpoolingIsTemplateSupportedPrintHTMLPrintSetupSetPageRange,WaitForSpoolingComplete

printer  (v6.3.436 and later)


Description

Specifies the printer to directly print to. Only the exact printer name strings as they appear in the Printers Control Panel may be used.

Syntax

rawPrinting.printer = sPrinterName

Settings

This a read-write property. With JScript, take care to double a backslash if one appears in the printer name.

Please note that an error will be thrown if the printer cannot be connected to.

Applies To

rawPrinting

Example

factory.rawPrinting.printer = "Zebra  LP2844-Z"

See Also

printStringprintDocument

 

printToFileName


Description

The file name to print to. Use the full path specification. The file created doesn't accumulate subsequent print-outs and - for security reasons - doesn't get overwritten if it already exists. Specify a new filename for each new print-out.

Printing to file name is supported for Internet Explorer 5.0 and later.

Syntax

printing.printToFileName = sPathFileName

Settings

This is a read/write property. With JScript, take care to double a backslash if one appears in the file path, as in the example below. An empty string indicates that the print-out should go to the printer driver.

Applies To

printing

Example

factory.printing.printToFileName = "d:\\temp\\printout.prn"

See Also

HTML Printing with ScriptX

printer

IsSpoolingPrintPrintHTMLPrintSetupWaitForSpoolingComplete

rightMarginbasic


Description

Specifies the right margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableRight), in which case it will be automatically corrected to the minimum allowed value. If left and right margins overlap, they will be corrected to an arbitrary default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The rightMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.rightMargin numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

pageHeightpageWidthportraitleftMargintopMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

serverName


Description

Returns a string giving the name of the server computer controlling the printer. If the string is empty then the printer is controlled locally.

Syntax

sName = printerControl.serverName

Settings

This is a read only property.

Applies To

printerControl

shareName


Description

Returns a string identifying the share point of the printer. This value is only present if PRINTER_ATTRIBUTE_SHARED is set on attributes.

Syntax

sName = printerControl.shareName

Settings

This is a read only property.

Applies To

printerControl

status


Description

Specifies the status of the printer, it can be any reasonable combination of the following values.

ValueMeaning
PRINTER_STATUS_BUSY (0x00000200)The printer is busy.
PRINTER_STATUS_DOOR_OPEN (0x00400000)The printer door is open.
PRINTER_STATUS_ERROR (0x00000002)The printer is in an error state.
PRINTER_STATUS_INITIALIZING (0x00008000)The printer is initializing.
PRINTER_STATUS_IO_ACTIVE (0x00000100)The printer is in an active input/output state
PRINTER_STATUS_MANUAL_FEED (0x00000020)The printer is in a manual feed state.
PRINTER_STATUS_NO_TONER (0x00040000)The printer is out of toner.
PRINTER_STATUS_NOT_AVAILABLE (0x00001000)The printer is not available for printing.
PRINTER_STATUS_OFFLINE (0x00000080)The printer is offline.
PRINTER_STATUS_OUT_OF_MEMORY (0x00200000)The printer has run out of memory.
PRINTER_STATUS_OUTPUT_BIN_FULL (0x00000800)The printer's output bin is full.
PRINTER_STATUS_PAGE_PUNT (0x00080000)The printer cannot print the current page.

Windows 95/98/Me: Indicates the page is being "punted" (that is, not printed) because it is too complex for the printer to print.

PRINTER_STATUS_PAPER_JAM (0x00000008)Paper is jammed in the printer
PRINTER_STATUS_PAPER_OUT (0x00000010)The printer is out of paper.
PRINTER_STATUS_PAPER_PROBLEM 0x00000040)The printer has a paper problem.
PRINTER_STATUS_PAUSED (0x00000001)The printer is paused.
PRINTER_STATUS_PENDING_DELETION (0x00000004)The printer is being deleted.
PRINTER_STATUS_POWER_SAVE (0x01000000)The printer is in power save mode.
PRINTER_STATUS_PRINTING (0x00000400)The printer is printing.
PRINTER_STATUS_PROCESSING (0x00004000)The printer is processing a print job.
PRINTER_STATUS_SERVER_UNKNOWN (0x00800000)The printer status is unknown.
PRINTER_STATUS_TONER_LOW (0x00020000)The printer is low on toner.
PRINTER_STATUS_USER_INTERVENTION (0x00100000)The printer has an error that requires the user to do something.
PRINTER_STATUS_WAITING (0x00002000)The printer is waiting.
PRINTER_STATUS_WARMING_UP (0x00010000)The printer is warming up.

Syntax

printerControl.status = nStatus

Settings

This is a read/write property. The user will require printer administrator writes in order to update the status.

Applies To

printerControl

templateURLbasic (v6.3 and later)


Description

 

For ScriptX v6.3 and later, this property is available as basic  property, the value set must be one of the following special values:

ValueDescription
MeadCo://IE55The IE 5.5/IE 6 style template - note can be used on IE 7.
MeadCo://IE7The IE 7 style template - note free usage on all versions of IE 5.5 or later.
MeadCo://DefaultThe default template for the IE version in use, i.e. the template matches the browser version. This is the default behaviour.
MeadCo://maxiptThe MaxiPT template (requires a license).

Syntax

printing.templateURL templateURL

Settings

This is a read/write property.

Applies To

printing

See Also

 PrintPrintHTML

topMarginbasic


Description

Specifies the top  margin for HTML print-outs. Cannot be set to be less than the printer's physically unprintable area (unprintableTop), in which case it will be automatically corrected to the minimum allowed value. If top and bottom margins overlap, they will be corrected to default value of 1/10 of page width.

ScriptX uses the default units of measure of the user's system. In a broad network environment default units are certain to vary (they could be either inches or millimeters) so you may wish to specify a fixed unit of measure with the licensed function SetMarginMeasure.

The topMargin property is part of the basic freely-distributable printing subset.

Syntax

printing.topMargin = numMargin

Settings

This is a read/write property.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

leftMarginpageHeightpageWidthportraitrightMarginbottomMarginunprintableBottomunprintableLeftunprintableRightunprintableTop

GetMarginMeasurePageSetupPrintPrintHTMLSetMarginMeasure

unprintableBottom


Description

Returns the bottom unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the bottom edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableBottom

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableLeftunprintableRightunprintableTop

PageSetupPrintPrintSetup

unprintableLeft


Description

Returns the left unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the left edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableLeft

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableRightunprintableTop

PageSetupPrintPrintSetup

unprintableRight


Description

Returns the right unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the right edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableRight

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableLeftunprintableTop

PageSetupPrintPrintSetup

unprintableTop


Description

Returns the top unprintable page area (in current system measure units, inches or millimeters) for the current printer. It indicates the distance from the top edge of the page where no printing may occur.

Syntax

numMargin = printing.unprintableTop

Settings

This is a read/only property.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizetopMarginunprintableBottomunprintableLeftunprintableRight

PageSetupPrintPrintSetup



Methods and Functions

BatchPrintPDF (ScriptX Corporate 32 bit Edition)


Description

Downloads Adobe Acrobattm or Microsoft Officetm files and prints them out in batch mode in the background. Any number of print-outs can be queued.

For Microsoft Officetm files, BatchPrintPDF prints only on the default printer using default settings.

For Adobe Acrobattm files, relevant current printing settings are used as described in the syntax section.

This updated functionality now requires v6.6 or later of ScriptX Corporate 32-bit Edition and an Enhanced PDF Printing license.

Please contact MeadCo sales for details.

Use IsSpooling to check if there are any outstanding downloads in the queue created by BatchPrintPDF. Use WaitForSpoolingComplete to wait for all documents to be downloaded and spooled.

Syntax

printing.BatchPrintPDF(url)

ParameterDescription
urlThe url of the document to be printed.

For Adobe Acrobattm files, the following printing settings are used:

printing.printer
printing.paperSize
printing.paperSource
printing.portrait
printing.copies
printing.collate
printing.duplex
printing.SetPrintScale(-1). 
    [The use of SetPrintScale(-1) enables "Shrink to Fit" of the printed output. Also, rotate pages to fit on the output medium, and center on the page is set. Any other value given to SetPrintScale is ignored.] printing.SetPageRange(false,startPage,endPage) to set the page range to print.

These settings are used per file submitted to the batch, so each document can be printed using different settings, for example, each document to a different printer.

Example

Here is a basic example of BatchPrintPDF use

<body>
<script>
function BatchPrintPDF(url) {
  factory.printing.SetPrintScale(-1); // ensure shrinks to fit if needed
  factory.printing.BatchPrintPDF(url);
}
</script>
<button id="idPrint" onclick="BatchPrintPDF('report.pdf')">BatchPrintPDF('report.pdf')</button>
</body>

Applies To

printing

See Also

HTML Printing with ScriptX

DefaultPrinterEnumJobsEnumPrintersGetJobsCountIsSpoolingPrintHTMLPrintPDFSleepWaitForSpoolingComplete

DefaultPrinter


Description

Returns the name of the default printer (if any).

Syntax

printerName = printing.DefaultPrinter()

Applies To

printing

See Also

HTML Printing with ScriptX

printer

EnumJobsEnumPrintersGetJobsCountIsTemplateSupportedPrint

DoPrint


Description

The alias for the Print method (retained for compatibility reasons).

Applies To

factory

See Also

printingPrintPrintHTML

EnumJobs


Description

Enumerates active jobs on the given printer.

Syntax

var jobName = {}
status = printing
.EnumJobs(printerName, index, jobName)

ParameterDescription
printerName(String) printer name on which to enumerate the jobs
index(Number) Zero-based index of the job. Increment this value for each new EnumJobs call for a given printerName
An index of -1 will return the status of the printer, rather than a particular job.
jobName(Object) obtains a name for the job (available as jobName[0])

Return Value

Returns a numeric value indicating the current status of the job. The bits have the following meaning:

MeaningValue
JOB_STATUS_PAUSED0x00000001
JOB_STATUS_ERROR0x00000002
JOB_STATUS_DELETING0x00000004
JOB_STATUS_SPOOLING0x00000008
JOB_STATUS_PRINTING0x00000010
JOB_STATUS_OFFLINE0x00000020
JOB_STATUS_PAPEROUT0x00000040
JOB_STATUS_PRINTED0x00000080
JOB_STATUS_DELETED0x00000100
JOB_STATUS_BLOCKED_DEVQ0x00000200
JOB_STATUS_USER_INTERVENTION0x00000400
JOB_STATUS_RESTART0x00000800

Example

<script defer>
function window.onload() {
  for ( i = 0; printer = factory.printing.EnumPrinters(i); i++ ) {
    alert("Printer name: "+printer);
    var job = {};
    for ( j = 0; status = factory.printing.EnumJobs(printer, j, job); j++ )
      alert("Job name: "+job[0]+", status: "+status);
  }
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumPrintersGetJobsCountPrint

EnumPrinters


Description

Enumerates locally-available printers.

Syntax

printerName = printing.EnumPrinters(index)

ParameterDescription
index(Number) Zero-based index of the printer. Increment this value for each new EnumPrinters call

Return Value

Returns the string name of the next printer. An empty value means that enumeration is over.

Example

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<p><small id=idOutput></small>

<script defer>
function OutputHtml(html) {
  idOutput.insertAdjacentHTML("BeforeEnd", html)
  idOutput.scrollIntoView(false)
}

function EnumAll() {
  OutputHtml("Default printer: <b>" + factory.printing.DefaultPrinter() + "</b><br>")
  for ( i = 0; name = factory.printing.EnumPrinters(i); i++ ) {
    OutputHtml("Printer: <b>" + name + "</b><br>Job count: " + factory.printing.GetJobsCount(name) + "<br>")
    var jobName = {}
    for ( j = 0; status = factory.printing.EnumJobs(name, j, jobName); j++ )
      OutputHtml("Job: <b>" + jobName[0]+"</b>Status: " + new Number(status).toString(16) + "<br>")
  }
}

function window.onload() {
  EnumAll()
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumJobsEnumPrintersGetJobsCountPrintPrintSetup

GetJobsCount


Description

Returns the number of printing jobs for the specified printer.

Syntax

numJobs = printing.GetJobsCount(printer)

Return Value

Returns a numeric value.

Applies To

printing

See Also

HTML Printing with ScriptX

printer

DefaultPrinterEnumJobsEnumPrintersPrint

GetMarginMeasure


Description

Returns current units of measure for print-out margins, either millimeters or inches. Use SetMarginMeasure to switch the default units.

Syntax

units = printing.GetMarginMeasure()

Return Value

Returns the currently-set units of measure. 1 stands for millimeters, 2 for inches.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthrightMargintemplateURLtopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

PageSetupPrintPrintPrintSetupSetMarginMeasure

IsSpooling


Description

Checks if spooling is in progress as result of a Print call, or for any downloads outstanding in the queue created by PrintHTML PrintXML orBatchPrintPDF calls.

You can force the blocking wait state with WaitForSpoolingComplete to make sure all downloads are complete and spooling is done at any point in your code.

Syntax

isSpooling = printing.IsSpooling()

Return Value

Returns a boolean value indicating whether or not there are still outstanding unspooled downloads to be printed

Example

The following example closes the window when the spooling is done:

<script defer>

function PrintAllDocs() {
  factory.printing.PrintHTML("info.htm");
  factory.printing.PrintXML(src1);
  factory.printing.PrintXML(src2);
  CheckSpooling();
}

function CheckSpooling() {
  if ( !factory.printing.IsSpooling() ) window.close()
  setTimeout("CheckSpooling()", 1000);
}

</script>

See Also

HTML Printing with ScriptX

onafterprintonbeforeunload

BatchPrintPDFOwnQueuePrintPrintHTMLPrintXMLSleepWaitForSpoolingComplete

IsTemplateSupportedbasic


Description

Checks whether or not Print Templates are supported on the end user's system (i.e. checks for Internet Explorer 5.5 or later).

Syntax

isTemplateSupported = printing.IsTemplateSupported()

Return Value

Returns a boolean value indicating whether or not Print Templates are supported.

Applies To

printing

See Also

HTML Printing with ScriptX

templateURL

PreviewPrintPrintHTML

OwnQueue


Description

OwnQueue is used to organize a detached printing queue. Use this method to queue all PrintHTML calls in a separate process. The process is disconnected from the current session (cookies, SSL context, etc) but the calling window can be closed at any time without waiting for spooling to compete. 

OwnQueue should be called before any PrintHTML or PrintXML commands to take effect.

Syntax

printing.OwnQueue()

Applies To

printing

See Also

PrintHTMLPrintXML

PageSetupbasic


Description

Invokes the standard Internet Explorer Page Setup... dialog. If the user closes the dialog with the OK button, current settings will be updated and anonpagesetup event will be fired. 

The PageSetup method is part of the basic freely-distributable printing subset.

Syntax

result = printing.PageSetup()

Return Value

Returns a boolean value indicating whether or not a user has closed the dialog with the OK button.

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMargindisableUIfooterheaderleftMarginonpagesetuponuserpagesetuppaperSizepaperSourceportraitrightMargintopMargin

PrintPrintHTMLPrintSetup

Pause


Description

Pauses either the entire print queue or an individual job. In order to pause a print queue the user must possess administration rights on the printer, jobs belonging to the user may be paused.

Syntax

o.Pause()

Applies To

printerControlJob

See Also

Resume

Previewbasic


Description

Invokes the Print Preview... pane in Internet Explorer 5.5 and later.

The Preview method is part of the basic freely-distributable printing subset.

Syntax

printing.Preview(oFrame)

ParameterDescription
oFrame[Optional] HTML frame to preview. By default, the top-level containing page will be previewed (i.e. the whole browser window content).

The use of this parameter is not part of the basic subset, a license is required. Without a license, default behaviour (preview the whole window) will occur.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

onuserprintpreviewtemplateURL

IsTemplateSupportedPrint

Printbasic


Description

Prints the contents of the specified window or frame using the current printing settings. Please note these important changes regarding printing without a prompt.

This method is part of the basic freely-distributable printing subset.

However, the acquisition of a MeadCo Publishing License means that you can customize various printing properties such as copiesduplexpaperSize,printBackground etc., target specific printer or print externally-located documents with PrintHTML. See HTML Printing with ScriptX for more info. 

Syntax

printing.Print([prompt[, frameOrWindow]])

ParameterDescription
prompt(Bool) whether or not to prompt
frameOrWindow(Object) optional HTML frame or window횂쨩 to print. By default, the containing page (that hosts the ScriptX object) will be printed

Return Value

Returns false if printing with a prompt and the user cancels the printing.

Example

Check out the source code of the ScriptX BasicAdvanced and Techie printing examples.

The following simple but complete example shows how to print the containing page:

<head>
<title>MeadCo's ScriptX: Print</title>
<!-- special style sheet for printing -->
<style media="print">
.noprint { display: none }
</style>
</head>

<body scroll="auto">

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  factory.printing.header = "MeadCo's ScriptX: Print"
  factory.printing.footer = "The de facto standard for advanced web-based printing"
  factory.printing.portrait = false
  idPrint.disabled = false; // enable UI button
}

function Print() {
  factory.printing.Print(false); // no prompt
}
</script>

<p>Hello, world!</p>

<div class=noprint>
<hr>The button itself will not be printed:
<input id=idPrint disabled type="button" value="Print w/o prompt" onclick="Print()">
</div>

</body>

Applies To

printing

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

DefaultPrinterEnumJobsEnumPrintersGetJobsCountGetMarginMeasureIsSpoolingIsTemplateSupportedOwnQueuePageSetupPreviewPrint,PrintHTMLPrintPDFPrintSetupPrintXMLSetMarginMeasureSetPageRange,, WaitForSpoolingComplete

printDocument  (v6.3.436 and later)


Description

Loads the specified file and sends the content directly to the printer. The file bytes are not rendered in any way, they are sent to the printer for the printer to interpret. In this way, postscript can be sent directly to the printer or label printing commands.

This method is synchronous; it will not return until the file load and print is complete.

Syntax

rawPrinting.printDocument(url)

ParameterDescription
url(String) url of the file whose contents are to be sent to the printer. The url must be absolute but may refer to local (file://) resources.

Return Value

none.

Applies To

rawPrinting

Examples

The following simple but complete example shows how to print a label stored on the web server to a Zebra printer. The sample is assuming that some process has run on the server to generate and store the required label.

<head>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>

function printLabel() {
  var p = factory.rawPrinting;

  // select the Zebra printer
  p.printer = "Zebra  LP2844-Z"

  // must give the full url of the file...
  // The printDocument method is synchronous
  p.printDocument(factory.baseURL("label.txt"));

}
</script>


</head>

See Also

printString

PrintHTML


Description

Prints either specified HTML text or the HTML or XML document specified by the URL using the current printing settings in the same session context. The method is asynchronous. It returns before the document is downloaded and printed.

Important note:

The html to be printed must not be 'ScriptX-enabled' - it must not contain an object tag referencing the ScriptX object nor script code that uses that object. Attempting to print html (either specified html text or document specified by url) that contains the ScriptX object can lead to strange errors and failure of the entire printing process, including causing Internet Explorer to stop responding.

PrintHTML may be used to organize a printing queue in a separate process, in which case the current window may be closed without waiting for pending downloads to complete. See OwnQueue for more details.

Syntax

printing.PrintHTML(url[, prompt = false])

ParameterDescription
url(String) URL/html text to print:
ProtocolPrints
html://The html is loaded and printed, e.g. html://<html><head><title>Dynamic Printing</title></head><body>Hello world!</body></html>
any other, e.g. http://, https:// or if no protocol specified.The document is downloaded and printed. A relative (to the current page) url may be given.

Note: The target document at 'url' must NOT be 'ScriptX-enabled'.
prompt(Bool) Specifies whether or not the user should be prompted before the download is queued

Return Value

Returns false if printing with a prompt and the user cancels the printing.

Applies To

printing

Examples

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

The following simple but complete example shows how to print an externally-located document:

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  idPrint.disabled = false;
}

function PrintHTML(url) {
  factory.printing.PrintHTML(url);
}
</script>

<input id=idPrint disabled type="button" value="PrintHTML('info.htm')"
 onclick="PrintHTML('info.htm')">

</body>

The following example illustrates dynamic creation of the HTML to be printed:

 <!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script>
function doPrintDemo() {

	var n;
	var str = "<html><head>";
	str += "<link rel='stylesheet' type='text/css' href='/zeepe/resources/zp_content.css' />";
	str += "<title>ScriptX Dynamic Reports</title></head><body>";

	for (n=0; n<10; n++) {
		str += "<p>Dynamically created line number: " + (n+1) + "</p>";
	}

	str += "<hr/><p>Note that style sheets, scripts, images etc must be referenced by their full url</p>");
	str += "</body></html>";

	factory.printing.header = "ScriptX Dynamic Printing";
	factory.printing.footer = "";
	factory.printing.printHTML("html://"+str);
}
</script>

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

BatchPrintPDFIsSpoolingOwnQueuePageSetupPrintPrintSetupPrintXMLWaitForSpoolingComplete

PrintPDF (ScriptX Corporate 32 bit Edition)


Description

Downloads and prints a PDF document - the method will not return until the download and print has completed.

For greater control over printing, such as being able to select paper size and source and the printer to use and for a responsive experience for the user, please see the BatchPrintPDF method.

This updated functionality now requires v6.6 or later of ScriptX Corporate 32-bit Edition and an Enhanced PDF Printing license.

Please contact MeadCo sales for details.

Syntax

printing.PrintPDF(PDF[, prompt = true[, shrinkToFit = true [, from = -1[, to = -1]]]);

ParameterDescription
PDFAnonymous javascript object with the member value url containing the location of the document to be printed, as illustrated below.
prompt(Bool) Indicates whether or not to prompt the user before printing
shrinkToFit(Bool) Shrink the PDF page to fit the paper, optional, true by default
from(Number) Print from the specified page, optional, all pages by default
to(Number) Print to the specified page, optional, all pages by default

Example

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function PrintPDF() {
  factory.printing.PrintPDF({ url: "example.pdf" });
}
</script>

<input id=idPrint type="button" value="Print the PDF"
 onclick="PrintPDF()">

</body>

Applies To

printing

See Also

HTML Printing with ScriptX

BatchPrintPDFPrintPrintHTML

PrintSetup


Description

Invokes the standard Windows Print Setup... dialog, thus allowing a user to modify current print settings. If the user closes the dialog with the OK button, current settings will be updated and an onpagesetup event will be fired. No printing will occur in either case. 

Syntax

result = printing.PrintSetup()

Return Value

Returns a boolean value indicating whether or not the user has closed the dialog with the OK button.

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

Applies To

printing

See Also

HTML Printing with ScriptX

collatecopiesdisableUIduplexprinterprintToFileName

DefaultPrinterPageSetupPrintPrintHTML

printString


Description

Sends the specified text directly to the printer. The string is not rendered in any way, its is sent to the printer for the printer to interpret. In this way, label printing commands or (say) postscript can be sent directly to the printer.

This method is synchronous; it will not return until the print is complete.

Syntax

rawPrinting.printString(sText)

ParameterDescription
sText(String) text to print. The string is converted from Unicode to an ANSI string (bytes) and sent as-is to the printer.

Return Value

none.

Applies To

rawPrinting

Examples

The following simple but complete example shows how to print a label to a Zebra printer:

<head>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>

function printLabel() {
  var p = factory.rawPrinting;

  p.printer = "Zebra  LP2844-Z"
  p.printString("^XA^FO50,50^ADN,36,20,^FDScriptX RawPrinting^FS^FO50,100^ADN,36,20,^FDMead & Company^FS^XZ");

}
</script>


</head>

See Also

printDocument

PrintXML


Description

This method is an alias for PrintHTML, preserved for compatibility reasons. You can print both XML (XSL-processed) and HTML files with PrintHTML. See the PrintHTML method description for more info.

Example

The following simple but complete example shows how to print an externally-located XML document:

<head>
<title>MeadCo's ScriptX: PrintXML</title>
<!-- special style sheet for printing -->
<style media="print">
.noprint     { display: none }
</style>
</head>

<body>

<!-- MeadCo Security Manager - using evaluation license -->
<object viewastext style="display:none"
classid="clsid:5445be81-b796-11d2-b931-002018654e2e"
codebase="smsx.cab#Version=7,0,0,8">
  <param name="GUID" value="{0ADB2135-6917-470B-B615-330DB4AE3701}">
  <param name="Path" value="sxlic.mlf">
  <param name="Revision" value="0">
</object>

<!-- MeadCo ScriptX -->
<object id="factory" viewastext style="display:none"
classid="clsid:1663ed61-23eb-11d2-b92f-008048fdd814">
</object>

<script defer>
function window.onload() {
  idPrint.disabled = false;
}

function Print() {
  // set footer
  factory.printing.footer = "Printed with MeadCo's ScriptX";

  // print this page
  factory.printing.Print(false);

  // print linked pages
  var links = idLinks.all.tags("A");
  for ( i = 0; i < links.length; i++ )
    factory.printing.PrintXML(links[i].href)
}
</script>

<p><input id=idPrint class=noprint disabled type="button" value="Print the page and links"
 onclick="Print()">

<p>XML links:
<span id=idLinks>
<a href="info1.xml">Info 1</a>
<a href="info2.xml">Info 2</a>
<a href="info3.xml">Info 3</a>
</span>

</body>

See Also

HTML Printing with ScriptX

bottomMargincollatecopiesduplexfooterheaderleftMarginonafterprintonuserprintpaperSizepaperSourceportraitprintBackgroundprinter,printToFileNamerightMargintemplateURLtopMargin

BatchPrintPDFIsSpoolingOwnQueuePageSetupPrintPrintHTMLPrintSetupWaitForSpoolingComplete

Purge


Description

Purges all pending print jobs in the queue for the printer. The user must posses administration rights on the printer.

Syntax

o.Purge()

Applies To

printerControl

See Also

Pause

Restart


Description

Restarts the print job - the job must belong to the user or the user must possess administration rights on the printer.

Syntax

job.Restart()

Applies To

Job

See Also

Pause

Resume


Description

Resumes either the entire print queue or an individual job. In order to resume a paused print queue the user must possess administration rights on the printer, paused jobs belonging to the user may be resumed.

Syntax

o.Resume()

Applies To

printerControlJob

See Also

Pause

SetMarginMeasure


Description

Sets the units of measure for print-out margins.

Syntax

printing.SetMarginMeasure(units)

ParameterDescription
units(Number) 1 stands for millimeters, 2 for inches.

Applies To

printing

Example

Check out the source code of the ScriptX Advanced Printing and ScriptX Techie Printing examples.

See Also

HTML Printing with ScriptX

bottomMarginleftMarginpageHeightpageWidthpaperSizerightMargintopMarginunprintableBottomunprintableLeftunprintableRight,unprintableTop

GetMarginMeasurePageSetupPrintPrintPrintSetup

SetPageRange


Description

Sets the page selection to print.

It is not possible to know in advance the exact number of pages which will be printed unless you're using a custom Print Template (Internet Explorer 5.5 or later). MeadCo's MaxiPT횂쨩 custom Print Template allows you to specify arbitrary page ranges, as well as only odd, even or both odd and even pages with different margin and header/footer settings. 

Syntax

printing.SetPageRange(selectionOnly[, fromto])

ParameterDescription
selectionOnlyif true, prints the highlighted selection only (if there is one) and from and to are ignored.
If there is no selection, all pages are printed.
fromThe (1-based) page number to start printing from - use 0 to signify all pages should be printed. Only used if selectionOnly is false.
toThe (1-based) page number to print to, used only if selectionOnly is false and from is >= 1

Default behaviour is SetPageRange(false,0)

Applies To

printing

SSee Also

HTML Printing with ScriptX

collatecopiesduplex

PageSetupPreviewPrintPrintSetup

SetPrintScale (v6.3.435 and later)


Description

Use this method to specify the scale to be used during printing - this is print scalingnot view zooming.

The IE 7 style template is required for this method to have any effect.

Syntax

printing.SetPrintScale(lScale,)

ParameterDescription
lScale

(Number) The print scale to use, expressed as a percentage. The value must be either -1 or between 30 and 999 or it will be ignored.

The special value -1 denotes 'scale to fit' where, if necessary, the content is scaled to fit the width of the paper - if scaling is not necessary to fit, 100% scaling is used.

Applies To

printing

Example

function startPreview() {
	var s = document.getElementById("selectScale");
	factory.printing.SetPrintScale(s.options[s.selectedIndex].value);
}

  

See Also

SetPreviewZoomtemplateUrl

 

SetPreviewZoom (v6.3.435 and later)


Description

Use this method to specify the Zoom to be used during print preview - this is view zooming, not print scaling.

Syntax

printing.SetPreviewZoom(lZoom,,pagesX,pagesY)

ParameterDescription
lZoom(Number) The Zoom scaling to use, either expressed as a percentage (e.g. 200 for double full size) or one of the following special values:
-1Zoom to show the full page width in the view.
-2Zoom to show the full page height in the view.
-3Zoom to show 2 full height pages in the view.
0Zoom to show full height pages, layed out as described by the pagesX and pagesY parameters (requires the IE 7 style template).
For the IE 6 and earlier style template, the default value is 75%. For IE 7 and later style template, the default value is -2.
pagesX (optional, requires the IE 7 style template)(Number) Only used with the IE 7 style template when lZoom is 0. Specifies the number of pages to display across the view (columns).
pagesY (optional, requires the IE 7 style template)(Number) Only used with the IE 7 style template when lZoom is 0. Specifies the number of rows of pages to display.

Applies To

printing

Example

function startPreview() {
	var z,x=0,y=0;

	if ( document.getElementById("selectTemplate").selectedIndex != 1 ) { // if not IE 7 template
		var s = document.getElementById("selectZoom");
		z = s.options[s.selectedIndex].value;
	}
	else {
		var s = document.getElementById("selectZoom");
		var s1 = document.getElementById("selectPages");

		var o = parseInt(s1.options[s1.selectedIndex].value);

		switch (o) {
			case 0: // zoomed one page
				z = s.options[s.selectedIndex].value;
				break;

			case 2: // the rest are multi-page views.
				z = 0;
				x = 2;
				y = 1;
				break;

			case 3:
				z = 0;
				x = 3;
				y = 1;
				break;

			case 6:
				z = 0;
				x = 3;
				y = 2;
				break;

			case 12:
				z = 0;
				x = 4;
				y = 3;
				break;

		}
	}

	factory.printing.SetPreviewZoom(z,x,y);
	factory.printing.Preview();
}

  

See Also

SetPrintScale

Sleep


Description

Suspends (sleeps) script execution for a specified timeout or until a passed callback function returns true. This is an efficient way to wait for an event without burning CPU cycles.

Syntax

printing.Sleep(timeout, [callback])

ParameterDescription
timeout(Number) the timeout in milliseconds.
callback(Function) the optional pointer to the function to be periodically called within the Sleep method.
When the function returns true, the sleep is canceled.

Return Value

Returns true if the sleep was canceled by a callback function.

Applies To

printing

Example

The following code snippet navigates a frame to a file then prints its content:

<script defer>
function NavigatePrintFrame(url) {
  idFrame.navigate(url);
  factory.printing.Sleep(100) // let the navigation start
  factory.printing.Sleep(1000*60, IsReady) // sleep for 1 minute or until the document is ready
  factory.printing.Print(true, idFrame)
}
function IsReady() {
  return idFrame.document.readyState == "complete"
}
</script>

See Also

HTML Printing with ScriptX

onafterprint

IsSpoolingPrintWaitForSpoolingComplete

WaitForSpoolingComplete


Description

Waits for all pending download and spooling operations originated with PrintPrintHTML/PrintXML and BatchPrintPDF calls to complete.WaitForSpoolingComplete provides visual feedback such as a modal window state and an hourglass cursor.

Syntax

printing.WaitForSpoolingComplete()

Return Value

Returns a boolean value indicating whether or not there are still outstanding unspooled downloads to be printed.

Example

Check out the source code of the ScriptX Techie Printing example.

<script defer>
function PrintAndGo() {
  if ( factory.printing.Print() )
    factory.printing.WaitForSpoolingComplete()
  window.close()
}
</script>

Applies To

printing

See Also

HTML Printing with ScriptX

onafterprintonbeforeunload

BatchPrintPDFIsSpoolingOwnQueuePrintPrintHTML,  Sleep


MeadCo's ScriptX, MaxiPT and the MeadCo Security Manager are Copyright (c) Mead & Co Limited, 1998-2008.

Microsoft, Windows, Internet Explorer are registered trademarks of Microsoft Corporation. All companies and product names mentioned are trademarks of the respective companies.

MeadCo ScriptX Control

Posted by 1010
05.JSP2010. 3. 24. 09:42
반응형

Jsp File Browser

An easy to use and easy to install file browser java server page. This JSP program allows remote web-based file access and manipulation.
Features:
Main Screen (Dir viewer) with preview of directory 1.
  • Create, copy, move, rename and delete files and directories
  • Shortkeys
  • View Files (pictures, movies, pdf, html,...)
  • Javascript filename filter
  • Edit textfiles
  • Upload files to the server (Status via Upload monitor)
  • Download files from the server
  • Download groups of files and folders as a single zip file that is created on the fly
  • Execute native commands on the server (e.g ls, tar, chmod,...)
  • View entries and unpack zip, jar, war and gz files on the server
  • Just one file, very easy to install (in fact, just copy it to the server)
  • Customizable layout via css file
  • Restrict file access via black or whitelist
  • Changeable to a read-only (with or without upload) solution
  • ...

It should work with any JSP1.1 compatible server(e.g. Tomcat>=3.0), I have tested it on Tomcat 4.0 and 5.5, Resin 2.1.7 and Jetty.
If you found any bugs or have a feature request, please use the bug tracking system, or write me an email.
I will also add common questions here.
If you want to get informed about new releases, please enter the Mailinglist (only for new release announces, no discussion). Write a mail with empty body to jspfilebrowser-subscribe@vonloesch.de.
Please submit bugs here.

Download version 1.2
Screenshots
Online Demo (no upload and command execution, can be very slow)
Bug tracking and Feature requests

Posted by 1010
05.JSP2009. 9. 14. 18:03
반응형

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailBean {
//        private String host = "121.131.70.113";
        private String host = "127.0.0.1"; 
        private String to = null; 
        private String tname = null;
        private String from = null;
        private String fname = null;
        private String msgSubj = null;
        private String msgText = null;
        private Message msg = null;
       
        
        public SendMailBean(){  super();        }
       
        /**
         * 메일 설정
         * @param to 받는 사람 
         * @param tname 받는 사람 이름
         * @param from 보내는 사람
         * @param fname 보내는 사람 이름
         * @param msgSubj 메일 제목
         * @param msgText 메일 내용
         */
        public void setMail(String to, String tname, String from, String fname, String msgSubj, String msgText) {
                this.to = to;
                this.tname = tname;
                this.from = from;
                this.fname = fname;
                this.msgSubj = msgSubj;
                this.msgText = msgText;
               
                this.send();
        }
       
       
        public void send()  {
                try {
                        Properties props = new Properties();
                       
                        props.put("mail.smtp.host", host);
                         Session sess = Session.getInstance(props,null);
                         MimeMessage msg = new MimeMessage(sess);
                        
                        
                        // create a message
                        InternetAddress address = new InternetAddress(to, tname, "EUC-KR");
                        InternetAddress fadd = new InternetAddress(from, fname, "EUC-KR");
                       
                       
                        msg = new MimeMessage(sess);
                       
                        msg.setFrom(fadd);
                        msg.setRecipient(Message.RecipientType.TO, address);
                        msg.setSubject(msgSubj);
                        msg.setSentDate(new Date());
                        msg.setContent(msgText,"text/html;charset=euc-kr"); // HTML type
                        msg.setText(msgText); // 본문
       
                        Transport.send(msg);
                       
               
                } catch (Exception e) {
                        e.printStackTrace();
//                        return false;
                }  // end try
//                return true;
        }
}


Posted by 1010
05.JSP2009. 8. 12. 15:44
반응형
  Developer Guide Title
   
 

Expanded Syntax Reference
Output Comment Generates a comment that can be viewed in the HTML source file.
Hidden Comment Documents the JSP page but is not sent to the client.
Declaration Declares a variable or method valid in the scripting language used in the page.
Expression Contains an expression valid in the scripting language used in the page.
Scriptlet Contains a code fragment valid in the scripting language used in the page.
Include Directive Includes a file of text or code when the JSP page is translated.
Page Directive Defines attributes that apply to an entire JSP page.
Taglib Directive Defines a tag library and prefix for the custom tags used in the JSP page.
<jsp:forward> Forwards a client request to an HTML file, JSP file, or servlet for processing.
<jsp:getProperty> Gets the value of a Bean property so that you can display it in a JSP page.
<jsp:include> Sends a request to an object and includes the result in a JSP file.
<jsp:plugin> Downloads a Java plugin to the client Web browser to execute an applet or Bean.
<jsp:setProperty> Sets a property value or values in a Bean.
<jsp:useBean> Locates or instantiates a Bean with a specific name and scope.
Posted by 1010
05.JSP2009. 7. 30. 16:11
반응형

-- 웹접근성을 고려한 게시판 페이징 처리
파라미터(전체게시물수,현재페이지번호,한페이지당보여줄갯수,링크주소)

package com.bizconsult.util;

public class NavigationUtil {

        private int totalCnt;   // 전체건수
        private int maxPageNo;  // 최대페이지
        private int curPageNo;  // 현재페이지
        private int pageVol;    // 페이지당갯수

        private String baseLink=""; // 링크페이지 
       
       

        public NavigationUtil(int totalCnt, int pageNo, int pageVol, String baseLink) {
                // TODO Auto-generated constructor stub

                super();

               
                // 한화면에 보여줄 글 갯수
                this.pageVol = pageVol;
               
                // 현재 페이지 번호
                this.curPageNo = pageNo;
               
                // 링크페이지
                this.baseLink = baseLink;

                // 전체 페이지 수
                this.totalCnt = (totalCnt / pageVol) + (totalCnt % pageVol == 0 ? 0 : 1);  
        }


        public String goLink() { 
                // TODO Auto-generated constructor stub

                StringBuffer sb_PageLink = new StringBuffer();
               
                //이전
                if(this.curPageNo > 1){
                        sb_PageLink.append("<a href='");
                        sb_PageLink.append(this.baseLink);
                        sb_PageLink.append("?pageNo=");
                        sb_PageLink.append(1);
                        sb_PageLink.append("&");
                        sb_PageLink.append("pageVol=");
                        sb_PageLink.append(this.pageVol);
                        sb_PageLink.append("'>");
                        sb_PageLink.append("[처음]");    
                        sb_PageLink.append("</a>");   
                       
                        sb_PageLink.append("<a href='");
                        sb_PageLink.append(this.baseLink);
                        sb_PageLink.append("?pageNo=");
                        sb_PageLink.append(this.curPageNo -1);
                        sb_PageLink.append("&");
                        sb_PageLink.append("pageVol=");
                        sb_PageLink.append(this.pageVol);
                        sb_PageLink.append("'>");
                        sb_PageLink.append("[이전]");    
                        sb_PageLink.append("</a>");
                }
               
               
                // 게시물 목록
                for(int i =1 ; i <= this.totalCnt ; i ++){
                        sb_PageLink.append("<a href='");
                        sb_PageLink.append(this.baseLink);
                        sb_PageLink.append("?pageNo=");
                        sb_PageLink.append(i);
                        sb_PageLink.append("&");
                        sb_PageLink.append("pageVol=");
                        sb_PageLink.append(this.pageVol);
                        sb_PageLink.append("'>");
                        sb_PageLink.append(i);    
                        sb_PageLink.append("</a>");
                        sb_PageLink.append("&nbsp;&nbsp;");
                }
               
                //다음
                if(this.curPageNo < this.totalCnt){ 
                        sb_PageLink.append("<a href='");
                        sb_PageLink.append(this.baseLink);
                        sb_PageLink.append("?pageNo=");
                        sb_PageLink.append(this.curPageNo +1);
                        sb_PageLink.append("&");
                        sb_PageLink.append("pageVol=");
                        sb_PageLink.append(this.pageVol);
                        sb_PageLink.append("'>");
                        sb_PageLink.append("[다음]");    
                        sb_PageLink.append("</a>");   
                       
                        sb_PageLink.append("<a href='");
                        sb_PageLink.append(this.baseLink);
                        sb_PageLink.append("?pageNo=");
                        sb_PageLink.append(this.totalCnt);
                        sb_PageLink.append("&");
                        sb_PageLink.append("pageVol=");
                        sb_PageLink.append(this.pageVol);
                        sb_PageLink.append("'>");
                        sb_PageLink.append("[마지막]");    
                        sb_PageLink.append("</a>");
                }
               
                return sb_PageLink.toString();

        }

        public String goView(String baseLink, int seq) {
                StringBuffer sb_goView = new StringBuffer();
                sb_goView.append("<a href='");
                sb_goView.append(baseLink);
                sb_goView.append("?");
                sb_goView.append("mod=V");
                sb_goView.append("&");
                sb_goView.append("seq=" + Integer.toString(seq));
                sb_goView.append("'>");
                // sb_goView.append("</a>");

                return sb_goView.toString();
        }

        public String goView(String baseLink, String bizid, int seq) {
                StringBuffer sb_goView = new StringBuffer();

                sb_goView.append("<a href='");
                sb_goView.append(baseLink);
                sb_goView.append("?");
                sb_goView.append("mod=V");
                sb_goView.append("&");
                sb_goView.append("seq=" + Integer.toString(seq));
                sb_goView.append("'>");
                sb_goView.append("image insert");
                sb_goView.append("</a>");

                return sb_goView.toString();
        }

        public int getCurPageNo() {
                return curPageNo;
        }


        public void setCurPageNo(int curPageNo) {
                this.curPageNo = curPageNo;
        }

        public int getMaxPageNo() {
                return maxPageNo;
        }


        public void setMaxPageNo(int maxPageNo) {
                this.maxPageNo = maxPageNo;
        }


        public int getPageVol() {
                return pageVol;
        }


        public void setPageVol(int pageVol) {
                this.pageVol = pageVol;
        }


        public int getTotalCnt() {
                return totalCnt;
        }


        public void setTotalCnt(int totalCnt) {
                this.totalCnt = totalCnt;
        }


        public String getBaseLink() {
                return baseLink;
        }


        public void setBaseLink(String baseLink) {
                this.baseLink = baseLink;
        }


     

}

Posted by 1010
05.JSP2009. 7. 29. 11:58
반응형

http://blog.naver.com/wldud_0729/150015317564

매번 페이징을 구현할 때마다, 한 두시간 씩 끙끙대는 것 같다.

생각을 의사코드로 적은 후에 그걸 코드화 하는 습관을 들여야하는데,

성질이 급해서 일단 생각을 코드화 해서 버그를 잡은 다음에.. 그제서야 의사코드로 적고 있다.

다음은 생각의 흐름를 정리해본 것이다.

************************************************************************************************


 총 데이터 수가 37개인 데이터를 페이징 처리 해보자.

 데이터는 DB에서 가져오거나 xml파일을 읽어올 것이다.

  페이지를 3 페이지씩 보여줄 수도 있고 [1] [2] [3] [다음]

 혹은 10페이지씩 보여줄 수도 있다. [1] [2] [3] [4] [5] ...[10] [다음]

 값 셋팅에 따라 달라질 수 있도록 페이지그룹 사이즈(pageGroupSize) 변수를 사용하겠다.

 셋팅할 수 있는 값이 페이지그룹 사이즈 말고 또 무엇이 있을까?

  한 페이지 당 보여주는 리스트 갯수도 변할 가능성이 많다.

 이것은 페이지 사이즈(pageSize) 변수로 놓자.

 그러면, 페이징 로직의 결과를 예측하기 위해서 이 두개의 변수에 값을 넣어보자.

less..

 총 데이터 갯수 (count): 37

 페이지그룹 사이즈 (페이지그룹을 몇개씩 묶을 것인가) : 3
 페이지 사이즈 (한 페이지 당 리스트 갯수): 4

 이렇게 셋팅을 할 경우, 나오는 결과는?

 총 페이지 수(pageCount)는 37 / 4 = 9.25 니까 10 페이지 되겠다.

  pageCount = (count / pageSize ) + ( count % pageSize == 0 ? 0 : 1); 

  => count % pageSize == 0 ? 0 : 1 이 수식을 풀어서 쓰면

            if(count % pageSize == 0)
                return 0;
            else
                return 1;

    이렇게 표현된다.

 =============================================================================
                                       
          [1][2][3]   [4][5][6]   [7][8][9]   [10]
 페이지그룹넘버(numPageGroup) :   - 1 -           - 2 -           - 3 -      - 4 -
 =============================================================================
 
 페이지 그룹은 위와같이 총 4개로 나올 것이다. (pageGroupCount : 4)

 이 페이지 그룹을 본 후, 현재페이지가 호출될 경우를 생각해보면

 5페이지가 호출된다면 numPageGroup이 2인 상태로 페이지바가 보여질 것이다.

 그렇다면, 호출된 현재페이지를 가지고 페이지그룹넘버를 구하고,

 페이지그룹넘버값으로 페이지바의 첫번째 페이지를 계산해보자.

 numPageGroup = 올림(currentPage/pageGroupSize)

  => int numPageGroup = (int) Meth.ceil ((double)currentPage/pageGroupSize)                   

 => numPageGroup : 올림(5/3) = 2

 startPage = (numPageGroup - 1)*pageGroupSize + 1;

 => stratPage : (2-1)*3+1 = 4

 이제 시작페이지를 가지고 마지막 페이지도 구해보자

 endPage = startPage + pageGroupSize -1 => 4+3-1 = 6

 이런식으로 시작페이지와 마지막페이지를 구했다면, for문을 돌려서 페이지바를 출력할 수 있을 것이다.

 그런데, 마지막 페이지그룹을 위 공식대로 계산하면 endPage가 12페이지가 나온다.

  총 페이지수가 10개인데 12페이지까지 출력되면 안 될것이다.

 따라서, if문 처리를 추가해주자.

 if( 마지막페이지 > 총페이지 )
  마지막페이지 = 총 페이지    => endPage = 10

************************************************************************************************

로직은 자바 클래스로, 출력부분은 JSTL 코드로 작성했는데.. 페이징 부분 코드는 다음과 같다.
 

[ 자바 클래스 ]

          //한 페이지 당 보여줄 글 갯수
17:         private final static int pageSize = 4;
18:         //페이지그룹안의 페이지 갯수 ex) [이전] 1 2 3 4 5 [다음] 일 경우 페이지 갯수는 5
19:         private final static int pageGroupSize = 3;

             String pageNum = request.getParameter("pageNum");//페이지 번호
25:
26:         if (pageNum == null) {
27:             pageNum = "1";
28:         }
29:        
30:         int currentPage = Integer.parseInt(pageNum);
31:         int startRow = (currentPage - 1) * pageSize + 1;//한 페이지의 시작글 번호
32:         int endRow = currentPage * pageSize;//한 페이지의 마지막 글번호
33:         int count = 0;
34:         int number=0;


35:         ArrayList articleList = new ArrayList();
36:         BoardDAO dbPro = BoardDAO.getInstance();//DB연동
37:         count = dbPro.getTotalCnt();//전체 글의 수
38:        
39:         if (count > 0) {       
40:                 if(endRow>count)
41:                         endRow = count;
42:             articleList = dbPro.select(startRow,endRow);//현재 페이지에 해당하는 글 목록
43:            
44:         } else {
45:             articleList = null;
46:         }
47:                
48:                 number=count-(currentPage-1)*pageSize;//글목록에 표시할 글번호
49:                
50:                 //페이지그룹의 갯수
51:                 //ex) pageGroupSize가 3일 경우 '[1][2][3]'가 pageGroupCount 개 만큼 있다. 
52:                 int pageGroupCount = count/(pageSize*pageGroupSize)+( count % (pageSize*pageGroupSize) == 0 ? 0 : 1);
53:                 //페이지 그룹 번호
54:                 //ex) pageGroupSize가 3일 경우  '[1][2][3]'의 페이지그룹번호는 1 이고  '[2][3][4]'의 페이지그룹번호는 2 이다.
55:                 int numPageGroup = (int) Math.ceil((double)currentPage/pageGroupSize);

          //해당 뷰에서 사용할 속성
57:         request.setAttribute("currentPage", new Integer(currentPage));
58:         request.setAttribute("startRow", new Integer(startRow));
59:         request.setAttribute("endRow", new Integer(endRow));
60:         request.setAttribute("count", new Integer(count));
61:         request.setAttribute("pageSize", new Integer(pageSize));

             request.setAttribute("number", new Integer(number));
63:         request.setAttribute("pageGroupSize", new Integer(pageGroupSize));
64:         request.setAttribute("numPageGroup", new Integer(numPageGroup));
65:         request.setAttribute("pageGroupCount", new Integer(pageGroupCount));
66:         request.setAttribute("articleList", articleList);
67:       
68:         return "./list.jsp";//해당 뷰


[ JSP 부분 ]

<c:if test="${count > 0}">
   <c:set var="pageCount" value="${count / pageSize + ( count % pageSize == 0 ? 0 : 1)}"/>
   <c:set var="startPage" value="${pageGroupSize*(numPageGroup-1)+1}"/>
   <c:set var="endPage" value="${startPage + pageGroupSize-1}"/>
  
   <c:if test="${endPage > pageCount}" >
     <c:set var="endPage" value="${pageCount}" />
   </c:if>
         
   <c:if test="${numPageGroup > 1}">
        <a href="./list.do?pageNum=${(numPageGroup-2)*pageGroupSize+1 }">[이전]</a>
   </c:if>


   <c:forEach var="i" begin="${startPage}" end="${endPage}">
       <a href="list.do?pageNum=${i}">[
        <font color="#000000" />
          <c:if test="${currentPage == i}">
          <font color="#bbbbbb" />
        </c:if>
        ${i}
       </font>]
       </a>
   </c:forEach>


   <c:if test="${numPageGroup < pageGroupCount}">
        <a href="./list.do?pageNum=${numPageGroup*pageGroupSize+1}">[다음]</a>
   </c:if>
</c:if>

출처 : Tong - 민뎅님의 java통

Posted by 1010
05.JSP2009. 7. 14. 10:57
반응형

J2EE에서 한글

공식처럼 대부분의 사이트가 EUC-KR 인코딩을 사용한다. 그런데 EUC-KR이 올바른 한글 인코딩일까?

결론은 아니다. EUC-KR로는 한글을 모두 표현할 수 가 없다. 똠방각하, 펲시콜라 이런 글자가 안되는 한글 페이지라니... EUC-KR에서는 ?방각하 ?시콜라 처럼 보여진다. google에서 펲시콜라를 입력해보라, 아니 이 블로그만 보더라도... 어처구니없이 외국사이트보다도 세종대왕의 자손들이 만들고 운영하는 사이트들에서 한글이 제대로 쓰여지고 있지 않다.
완성형, 조합형으로까지 거슬러 올라가 전산상의 한글 구현에 대해서 구구절절 읊지 않더라도 한글 자모로 구성 가능한 문자가 표현되지 않는 character set이나 encoding을 사용하는 것은 올바른 습관이 아니라고 본다.

여타의 기술 자료나 QnA 등에서 그래도 앞서나간 사람들이 jsp한글...tomcat 한글... 이런 글에 몽땅 EUC-KR로 기술하고있는 것은 문제라고 생각한다.

마땅히 한글 표현이 우수한 UTF-8를 사용해야한다. 한글 뿐만 아니라 국제화를 고려한다면 더더욱.

Tomcat에서 contentType을 UTF-8으로 하는 경우 jsp 파일은 UTF-8인콩딩으로 작성되어야한다. Eclipse를 사용한다면 문서의 Properties에서 수정할 수 있다. UTF-8인경우 한글 출력 및 post로 submit된 한글 값도 문제가 없지만 get 으로 전송된 파라미터 값은 한글이 깨진다.

Tomcat의 url decoding 과정에서 한글 처리에 문제가 있다.

String qry = request.getQueryString();
msg = URLDecoder.decode(qry.split("msg=")[1],"UTF-8");
out.println(msg)

처럼 직접 url decoding을 하면 get 전송된 한글도 정상적으로 출력된다.

request.getParameter()에서 UTF-8으로 decoding되지 않는 문제를 ... 음. 시간이 날 때 좀 더 파헤쳐보면 해법을 찾을 수 있을 거 같다.
꼭 찾아야지.
Posted by 1010
05.JSP2009. 7. 14. 10:55
반응형
Posted by 1010
05.JSP2009. 7. 8. 15:08
반응형

JavaScript를 이용

window.open, location.href, location.replace 등을 이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

      <script>location.href = "admin.jsp"; </script>

<% } else { %>

      <script>alert('권한이 없어요!'); window.history.back(); </script>

<% } %>

         

특징적인부분은 브라우져의 주소창이 변경되며

(이말은 즉슨 클라이언트가 다시 admin.jsp를 서버에 요청한다는 말입니다)

login_process.jsp 에서 jsp가 다 실행되고 브라우져에 out put된 html 및 javascript들만으로

실행된 코드들이라는 것입니다


response.sendRedirect를 이용

login_process.jsp

<% if (a == null) {

          response.sendRedirect("admin.jsp");

     } else {

          response.sendRedirect("login.jsp");

     }


     a = "test 입니다";

     System.out.println(a);

%>


이 코드에서 a가 출력될까요 안될까요?

출력 됩니다.

sendRedirect가 되더라도 밑에 jsp 코드들은 모두 실행 된다는 말입니다

response.sendRedirect는 기본적으로 모든 로직들을 다 처리한 후 코드 맨 마지막 부분에

사용하는 것이 올바른 방법입니다

만약 그렇지 못한 경우는 response.sendRedirect 다음 바로 return; 이라는 코드를 집어 넣어야 합니다


response.sendRedirect은 HTTP 헤더정보를 변경하여 redirect시키기 때문에 역시 브라우져의 주소창이 변경되며 sendRedirect가 실행되기전 html이나 javascript로 out put되는 코드들은 모두 실행되지 않습니다.


forward 이용

jsp 태그의 <jsp:forward> 나 servlet의 RequestDispatcher.forward 를 이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

          <jsp:forward page="admin.jsp"/>

<% } else { %>

          <jsp:forward page="login.jsp"/>

<% }


     a = "test 입니다";

     System.out.println(a);

%>


그럼 위의 코드의 경우 a가 출력 될까요 안될까요?

정답은 출력 안됩니다. 바로 forward 되어 버립니다.

클라이언트로 응답주지 않고 바로 서버측에서 admin.jsp로 이동하기 때문에

주소창이 바뀌지 않고 그로인해 브라우져에 출력되는 응답속도 또한 사용자가 보기에는

응답이 빠른 장점이 있습니다


하지만 forward 이후 JSP 코드들이 실행되지 않는것 사실이지만 만약 finally절이 있는경우

finally절은 실행 됨으로 확실히 알아둡시다.


meta 태그 이용

마지막으로 meta 태그를 이용할 수도 있습니다.


<META http-equiv=refresh content="0;url=admin.jsp">


즉 요약하자면..

페이지 이동 방법이 여러가지가 있습니다.

그 특성들을 잘 알고 올바르게 사용하여야 합니다

출처 : Tong - 난 하늘을 볼테야님의 JSP Study통

Posted by 1010
05.JSP2009. 6. 19. 15:28
반응형
Tomcat 5.5 에서 JNDI Datasource 사용하기
JSP 프로그래밍에서 쉽게 볼 수 있는 DB를 사용하는 방법대신 왜 DBCP, JNDI Datasource 같은 복잡한 것들을 왜 해야할까요?

DBCP, JNDI에 대한 자세한 정의는 따로 위키등에서 참고하세요.

- DBCP는 데이터베이스 커넥션풀링으로 접속객체를 풀에 넣어두고 필요할때 꺼내서 사용하여 성능을 향상시키기 위함입니다.
- JNDI(Java Naming and Directory Interface)는 분산된 자원을 디렉토리 형태로 이름지어 검색할 수 있게 하는 것입니다.
- 톰캣의 JNDI Datasource 라는 것은 데이터소스를 JNDI를 이용, 찾아서 연결해 사용하자는 것입니다.

JNDI Datasource를 이용하면 웹어플리케이션 자체에 DB접속을 위한 잡다한 코드를 넣지 않아도 되므로 환경변화에 유연합니다.

우선 컨텍스트(Context)에 데이터소스를 적어줘야 합니다.
컨텍스트 파일의 작성에 대해서는 Tomcat 5.5에서의 <Context>를 참고하시기 바랍니다.
컨텍스트에 아래와 같이 Resource를 자신의 환경에 맞게 적어줍니다.
<?xml version="1.0"?>
<Context docBase="yourapp" path="/yourapp">
<Resource description="Test database connection"
name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="yourid" password="yourpw" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb?autoReconnect=true"/>
</Context>
위에서 driverClassName은 로드할 드라이버를 설정하는 부분입니다.
driverClassName와 url의 값은 Java에서 일반적인 DB 접속시 많이 쓰던 것임을 알 수 있습니다.
name은 프로그램 코드에서 이 데이터소스를 참조하기 위한 이름입니다.

위에서 com.mysql.jdbc.Driver를 사용하였는데 이런 jdbc 드라이버는 톰캣의 기본 라이브러리가 아니므로 $CATALINA_HOME/common/lib 디렉토리에 mysql-connector-java-버전-bin.jar 파일을 넣어줘야 합니다.
DBCP를 위해 필요한 라이브러리는 톰캣에 기본으로 존재하며 naming-factory-dbcp.jar 입니다.

DB 드라이버를 로드하고 DBCP에 대한 복잡한 설정을 하는 프로그램 코딩 없이 설정파일에 기술하는 것만으로 JNDI Datasource로 DBCP를 이용하는데 필요한 준비는 끝났습니다.

이제 간단한 소스를 실행하여 문제없이 동작하는지 테스트 해보겠습니다.

import javax.naming.InitialContext;
import javax.sql.DataSource;

try {
    InitialContext initContext = new InitialContext();
    Context envContext = (Context)initContext.lookup("java:/comp/env");
    DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB"); //위에서 설정한 데이터소스의 name
   
    Connection conn = ds.getConnection();
    System.out.println(conn);
    conn.close();
} catch(Exception e) {
    e.printStackTrace();
}

위의 코드에 문제가 없다면 org.apache.tomcat.dbcp.dbcp.PoolableConnection@15d4de6 와 같은 결과가 출력됩니다.
이제 Connection 객체를 이용해서 기존과 똑같이 데이터베이스 관련 코딩을 하면 됩니다.

JNDI를 이용하여 DataSource를 가져오는 방법은 톰캣만이 가능한것이 아니라 다른 WAS들도 가능합니다. 참조하는 name을 일치시켜주면 기존 프로그램의 코드수정 없이 WAS의 설정파일만 수정하면 됩니다.

* Name [jdbc/TestDB] is not bound in this Context 에러가 발생하면 jdbc/TestDB(해당이름)를 JNDI가 찾을 수 없다는 것으로써 설정의 name이 틀리지 않았는지 확인해보고 문제가 없다면 컨텍스트 파일을 못읽는 것일 수 있으므로 컨텍스트 파일의 위치와 파일명을 확인합니다.

* web.xml의 <resource-ref> 설정에 대한 자료도 봤는데 설정하지 않더라도 동작에 문제가 없었습니다.
Posted by 1010
05.JSP2009. 6. 16. 20:33
반응형
출처 : http://passion818.tistory.com/84

정말 오랜만에 글을 쓰네요..일본에서 돌아오고는 완전히 초 귀차니즘이..;;;
요즘은 우분투를 프로그램 개발용으로 쓰려고 별 짓을 다하고 있는 덕에 이렇게 블로그 등에 기록해 두지 않으면 좋지 않은 머리로 다 기억 못할거 같아 지금까지 삽질하며 구축한 내용을 글로 남기려고 합니다.

일단 시작은 본편인 JSP 환경 구축부터 해서 C/C++, Flex3, APM 설치 등의 순으로 글을 쓰려고 합니다.
우분투 버전은 9.04 Jauty이고 제가 참고 한 자료들이 대부분 8.04이후의 글들을 참고 하였으므로 8.04나 8.10도 잘 될거라고 예상됩니다.
그럼 본 내용으로 들어가보도록 하지요..

[ 참고한 글들 ]

1. JDK 6 설치

JSP 환경을 구축하는데 JDK는 당연히 빠질 수 없겠지요..ㅎㅎ. 여기서 사용할 JDK 패키지는 sun-java6-jdk 패키지로 시냅틱에서 jdk로 검색을 하여 설치하면 아주 간단히 설치가 가능합니다. 예외적인 상황으로는 오픈오피스의 의존성 관계로 OpenJDK가 설치되어 있을것인데 위의 패키지를 설치한 후엔 다음 명령으로 기본 Java를 변경해 주시거나 OpenJDK를 삭제하시면 됩니다.
$ sudo update-alternatives --config java
jdk-doc은 무슨 이유에서인지 에러를 뿜으며 설치가 안되는군요..뭐..api는 자바 사이트에서 보면서 해도 되니 doc은 패스..ㅡㅡ;

JAVA 환경변수 등록
$ sudo gedit /etc/profile

다음 내용을 추가하고 저장
export JAVA_HOME=/usr/lib/jvm/java-6-sun

source명령으로 수정한 profile를 반영합니다.
$ source /etc/profile

2. Tomcat 설치

이제 Java 구동 환경은 구축 되었으니 JSP파일을 구동 시킬 서버를 구축해줘야 하는데 그 역할을 하는 것 이 톰캣 서버이지요.ㅎㅎ 윈도우는 그냥 냅다 다운받아 설치하고 실행시키면 되지만 우분투는 쪼끔 귀찮게 하더군요..ㅡㅡ;;
원 래는 시냅틱에서 검색하여 패키지로 설치하려 했으나..이게 이클립스와 연동시키려니 이래저래 해줘야할 것도 많고 구글 검색을 통해 제가 해본 방법으로는 잘 안되서 결국 리눅스용 톰캣을 인터넷으로 다운받아 설치했습니다. 실제로 서버를 구축해서 서비스를 한다면 추천하고 싶지 않은 방법이지만 단지 공부등의 이유로 간단히 자신의 컴에 JSP구동 환경을 구축하려고 한다면 이방법이 제일 간편할 듯 싶군요.
 
우선 톰캣을 다운로드 합니다. 저의 경우에는 Tomcat 6 버전을 다운로드하였습니다.(교육 과정에서 이 버전을 써서요..ㅎㅎ;;)

다운로드한 디렉토리에서 다음 명령을 입력해 압축을 해제합니다.
$ tar xvfz apache-tomcat-6.0.20.tar.gz

압축 해제한 톰캣 디렉토리를 적당한 위치로 옮깁니다. 저의 경우엔 /usr/local/tomcat6이란 디렉토리를 만들어 옮겼습니다.
$ sudo mkdir /usr/local/tomcat6
$ sudo mv ./apache-tomcat-6.0.20/* /usr/local/tomcat6/

이것으로 톰캣의 설치는 끝났습니다. 이제 톰캣을 구동시키고(Start) 정지시키고(Stop) 재시작(Restart)시킬 스크립트를 작성합니다.
$ sudo gedit /etc/init.d/tomcat6

다음 내용을 입력 후 저장합니다.
export JAVA_HOME=/usr/lib/jvm/java-6-sun
case $1 in
start)
sh /usr/local/tomcat6/bin/startup.sh
;;
stop)
sh /usr/local/tomcat6/bin/shutdown.sh
;;
restart)
sh /usr/local/tomcat6/bin/shutdown.sh
sh /usr/local/tomcat6/bin/startup.sh
;;
esac
exit 0

만든 스크립트 파일을 실행 가능하도록 권한을 부여하면 시냅틱으로 설치한 톰캣 서버처럼 구동이 가능합니다.
$ sudo chomod 755 /etc/init.d/tomcat6
$ sudo /etc/init.d/tomcat6 start
       stop
       restart 이런식의 구동이 가능하게 됩니다.

저 같은 경우에는 이클립스에서 구동하고 정지 시킬 것이기에 톰캣이 우분투가 시작하면서 자동으로 실행 될 필요가 없지만 혹시나 자동으로 실행되길 바라신다면 다음 명령을 추가로 입력하여 링크를 겁니다.
$ sudo ln -s /etc/init.d/tomcat /etc/rc1.d/K99tomcat
$ sudo ln -s /etc/init.d/tomcat /etc/rc2.d/S99tomcat

3. Oracle 10g XE 설치

오라클의 경우엔 저장소가 있기 때문에  소스리스트에 저장소를 추가 후 시냅틱이나 터미널에서 apt-get install 명령으로 간단히 설치가 가능합니다. 원래는 데비안용 패키지인것 같지만 우분투 자체가 데비안을 기반으로 만든 것이여서 그런지 아무 문제 없이 설치가 가능합니다.

시스템 > 관리 > 소프트웨어 소스에서 써드 파티 소프트웨어 탭에서 다음 저장소를 추가합니다.
deb http://oss.oracle.com/debian unstable main non-free #Oracle 10g Express Edition

8.10부터 저장소를 추가하면 해당 저장소의 인증키가 있어야 되는데 오라클의 경우 터미널에서 다음 명령으로 키를 얻어옵니다.
$ sudo wget http://oss.oracle.com/el4/RPM-GPG-KEY-oracle  -O- | sudo apt-key add -
$ sudo aptitude update

이제 오라클을 설치하면 되는데 다국어 지원을 위해 universal버전을 설치합니다. ( 시냅틱에서 oracle로 검색하여 설치하셔도 무방합니다. )
$ sudo aptitude install oracle-xe-universal

설치가 끝나면 이제 본인의 컴에 맞게 설정을 해야겠죠? 다음 명령으로 설정을 합니다.
$ sudo /etc/init.d/oracle-xe configure

다음은 설정 화면으로 [Enter]라고 쓰인 부분에서 엔터키를 치면 기본 설정값을 쓰겠다는 의미입니다. 포트 설정의 경우 톰캣이 8080포트를 사용해야 하므로 포트 충돌을 막기 위해 8087로 설정합니다.
Oracle Database 10g Express Edition Configuration
-------------------------------------------------
This will configure on-boot properties of Oracle Database 10g Express
Edition.  The following questions will determine whether the database should
be starting upon system boot, the ports it will use, and the passwords that
will be used for database accounts.  Press <Enter> to accept the defaults.
Ctrl-C will abort.

Specify the HTTP port that will be used for Oracle Application Express [8080]: 8087

Specify a port that will be used for the database listener [1521]: [ENTER]

Specify a password to be used for database accounts.  Note that the same
password will be used for SYS and SYSTEM.  Oracle recommends the use of
different passwords for each database account.  This can be done after
initial configuration:
Confirm the password:

Do you want Oracle Database 10g Express Edition to be started on boot (y/n) [y]: [ENTER]

Starting Oracle Net Listener...Done
Configuring Database...Done
Starting Oracle Database 10g Express Edition Instance...Done
Installation Completed Successfully.
To access the Database Home Page go to "http://127.0.0.1:8087/apex"
pcandme@behemoth:/etc/apt$ sudo /etc/init.d/oracle-xe configure
Oracle Database 10g Express Edition is already configured

설정이 끝났으면 오라클도 역시 환경변수를 등록합니다.
$ sudo gedit /etc/profile

다음 내용을 추가합니다.
ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
PATH=$PATH:$ORACLE_HOME/bin
export ORACLE_HOME
export ORACLE_SID=XE
export NLS_LANG='KOREAN_KOREA.AL32UTF8'

source명령으로 수정한 profile를 반영합니다.
$ source /etc/profile

여기까지 끝났으면 웹브라우저에 다음 주소를 입력하여 제대로 설치가 되었는지 확인합니다. 올바르게 설치가 되었다면 로그인 페이지가 나올 것입니다.
http://127.0.0.1:8087/apex


4. Eclipse 설치

금방 끝날줄 알았더니 이거..상당히 길어지네요..;; 이제 JSP구동 환경도 구축 되었고 데이터베이스를 구축할 오라클도 설치가 끝났으니 JSP 개발을 위한 IDE인 이클립스를 설치하도록 하지요. 설치할 버전은 3.4 Ganymede 입니다. 우분투의 기본 저장소에 있는 이클립스는 이상하게 아직도 3.2버전을 고집하고 있더군요..ㅡㅡ;; 나중에 플렉스도 설치해야 하므로 전 이클립스 공시 홈페이지에서 Eclipse J2EE버전을 다운로드하였습니다.( 플렉스 설치할 때 알았지만..3.4버전이..버그가 많더군요..;; 뭐 심각한건 없었으므로 괜찮았지만 쪼금 삽질을 했다는..;;; )

톰캣이 정상적으로 설치가 되었다면 이클립스와의 연동은 간단합니다. 다운로드한 이클립스를 압축해제 후 적당한 위치로 옮깁니다. 저는 홈 디렉토리로 옮겼습니다.( 권한 설정등이 귀찮아서..ㅡㅡ;; )


이클립스를 구동하면 퍼스펙티브가 J2EE로 기본 설정되어있어 아래와 같이 화면 하단에 보면 서버탭이 보이실겁니다.


저는 이미 설정을 해서 위와 같이 나왔지만 처음 설정할 때는 위의 서버 탭에서 오른쪽 클릭 > new를 해주시면 다음과 같은 창이 뜨는데 서버 목록에서 Apache를 누르면 연동 가능한 톰캣 목록이 뜹니다.


Tomcat 6버전을 선택하고 Next를 누르면 톰캣이 설치된 경로와 JRE버전을 선택하는 화면이 나오는데 JRE는 기본 그대로 놔두셔도 되지만 JDK를 여러버전이 설치가 되어있다면 사용할 JDK버전에 맞는 JRE를 선택해주셔야 합니다. 톰캣은 아까 설치한 경로를 입력해주시면 됩니다.


문제가 없다면 다음과 같이 서버가 추가 된 화면을 보실 수 있습니다. 서버 구동은 우측에 있는 플레이 버튼처럼 생긴 아이콘을 클릭해주시면 톰캣이 구동 됩니다.


이제 테스트를 위해 JSP 프로젝트를 하나 생성하여 테스트 페이지를 작성한 후 서버를 구동해 실제로 작동하는지 확인하면 되겠군요..
테스트 페이지 작성까지 글을 쓰면 너무 길어지므로( 이미 여기까지도 길지요..;; ) 생략하겠습니다.
이상으로 우분투에서 JSP환경 구축편을 마칩니다. 오랜만에 장문의 글을 쓰려니..힘드네요..@.@

Posted by 1010
05.JSP2009. 6. 16. 20:02
반응형

JSP 가 실행되기 위해서는 JSP 파일을 서블릿 파일로 변환하는 과정을 거치게 된다.
이 작업은 클라이언트의 요청이 있을 경우, 또는 JSP 파일이 변경되었을 경우 변경된
JSP 파일을 로딩하기 위해서 이루어진다.

JSP 동작구조
 
1.클라이언트가 jsp 페이지 요청
2. 웹 서버가 요청한 페이지를 를 처리하기 위해 JSP 컨테이너에게 처리를 넘긴다.
3. 해당 JSP 파일이 처음 요청된 것이면 JSP 파일을 서블릿으로 변환.
(JSP 컨테이너가 수행) 이전에 요청되었던 페이지일 경우 5 단계 실행
4.서블릿 파일은 자바에서 실행 가능한 상태인 클래스 파일로 컴파일
5. 클래스 파일을 메모리에 적재 후 실행
6. 실행 결과가 웹 서버에게 넘겨짐
7. 웹 서버는 브라우저가 인식할 수 있는 HTML 형태로 결과를 웹 브라우저에 응답
 
* jsp가 servlet으로 변환된 소스는 WAS마다 다르다
 
tomcat은 변환된 서블릿 소스를
C:\apache-tomcat-5.5.26\work\Catalina\localhost웹 어플리케이션 디렉토리\org\apache\jsp\jspsrc 에 저장
 
eclipse에서는

C:\워크스페이스명\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\프로젝트명\org\apache\jsp 

사용자 삽입 이미지
Posted by 아돌
Posted by 1010
05.JSP2009. 3. 16. 19:49
반응형

input 태그에서 type="image"는 form.submit 속성을 가지고 있어서 값을 무조건 넘겨준다.

 

'검색' 같은 이미지를 만들고 나서 type을 image로 하면 텍스트 박스를 검사 할 수 없음.

 

 

input 태그를 img 태그로 바꿔야 한다.

 

 

- 한시간 여 동안 날 화나게 한 원인이 이거구나.

Posted by 1010
05.JSP2009. 3. 10. 12:49
반응형

SQL에 parameter를 삽입하여 실행하는 기능

SQL에 parameter를 삽입하여 실행하는 방법이 있습니다.

String sSql = "select * from mytable where name = ? and address = ?";
Connection conn = get database connection;
PreparedStatement prestmt = null;
Statement stmt = null;
prestmt = conn.prepareStatement(sSql);
prestmt.setString(1,"Mike");
prestmt.setString(2,"LA");
rs = prestmt.executeQuery();
while (rs.next())
{
 xxx = rs.getString(1);
 yyy = rs.getString(2);
}

위와 같은 parameter name,address를 삽입하여 SQL을 실행할 수 있습니다.
실행되는 SQL은 다음과 같습니다.

select * from mytable where name = 'Mike' and address = 'LA'

위와 같은 방식으로 많은 개발자들이 web application을 개발합니다.
위와 같은 방식은 개발 생산성 측면에서 몇가지 문제가 있었습니다.
가장 큰 문제가 실제 실행되는 SQL을 개발자가 알 수 없습니다.
물론 parameter를 일일이 대입해서 볼수는 있지만 실제 값이 대입된 SQL을 개발자가 볼 수
없다는 것입니다.
문제가 되는 경우를 보겠습니다.

update mytalbe set name=? where id=?
prestmt.setString(1,"123456789012345678901234567890");
prestmt.setString(2,"2334");

그런데 mytable.name field는 varchar(16) 으로 선언이 되어 있다고 하겠습니다.
즉 입력한 값이 16 byte만 설정이 될 수 있습니다.
이와 같은 경우 개발자는 parameter가 설정된 실행되는 SQL을 trace log에서 볼 수 없기때문에
오류를 쉽게 파악하기 힘들 수 있습니다.

그래서 필자는 자체적으로 parameter가 설정된 SQL을 build하는 program을 개발해 보았습니다.
WCStmt.makeQuery method가 이것입니다.
parameter는 WCProperties로 전달하도록 하였습니다.

String sSql = "insert into table_name (name,address) values ('$name','$address')";
WCProperties pParam = new WCProperties();
pParam.setValue("name","jane");
pParam.setValue("address","L'A");
WCStmt oStmt = new WCStmt();
sSql = oStmt.makeQuery(sSql,pParam);

sSql 값 "insert into table_name (name,address) values ('jane','L''A')" 이와 같이 됩니다.
개발자는 sSql의 값을 확인하여 정확한 SQL이 생성되었는지를 점검할 수 있습니다.
그러나 개발을 하고 보니 이 방법도 몇가지 문제가 있었습니다.
parameter value값이 SQL에 삽입될때 몇가지 변환이 되어야 하는데 이 변환이
database의 type에 따라 약간씩 다르다는 것입니다.
L'\A 이와 같은 값이 있다고 하겠습니다.

- oracle,mssql : L''\A
update table_name set field_name = 'L''\A' where id = 37

- mysql : L''\\A
update table_name set field_name = 'L''\\A' where id = 37

이와 같이 변환이 되어야 합니다. 그래서 위의 makeQuery 함수를 다음과 같이 변경해야 했습니다.

String sDsn = "WDLDatabasePool";
sSql = oStmt.makeQuery(sSql,pParam,sDsn);

위에서 처럼 makeQuery에 database connection pool 이름을 전달하여 database type을 얻어와서
해당 database type에 대한 변환을 하도록 하였습니다.

-- JSP sample code 시작
<%@ page language="java" import="wdl.*,java.util.*,java.sql.*,java.lang.*,
java.io.*,java.io.File " contentType="text/html; charset=EUC-KR"%><%
 insertRecord();
%>
<%!
public void insertRecord()
{
 WCProperties rSqlParam = new WCProperties();
 rSqlParam.setValue("parentid",100);
 rSqlParam.setValue("text","hello");
 rSqlParam.setValue("url","-");
 rSqlParam.setValue("guid","g");
 rSqlParam.setValue("idx",0);
 rSqlParam.setValue("depth",0);
 rSqlParam.setValue("child",0);

 String sSql = "insert into mytable (\n";
 sSql += "parentid\n";
 sSql += ",text\n";
 sSql += ",url\n";
 sSql += ",guid\n";
 sSql += ",idx\n";
 sSql += ",depth\n";
 sSql += ",child\n";
 sSql += ")\n";
 sSql += "values(\n";
 sSql += "'$parentid' -- parentid\n";
 sSql += ",'$text' -- text\n";
 sSql += ",'$url' -- url\n";
 sSql += ",'$guid' -- guid\n";
 sSql += ",'$idx' -- idx\n";
 sSql += ",'$depth' -- depth\n";
 sSql += ",'$child' -- child\n";
 sSql += ")";
 WCStmt oStmt = new WCStmt();
 String sSql2 = oStmt.makeQuery(sSql,rSqlParam,"WDLDatabasePool");
 oStmt.executeUpdate(sSql2, null,"WDLDatabasePool");
}
%>
-- JSP sample code 끝

아래의 소스코드는 WCStmt.java의 일부분 코드입니다. makeQuery와 toSqlValue 입니다.

-- WCStmt.java에서 makeQuery 부분 추출 시작
public String makeQuery(String sSql,WCProperties rParam,String sDsn)
{
 if (WCString.isEmpty(sSql) || WCString.isEmpty(sDsn))
  return null;

 String sTail = "";
 String sHead = "";
 String sMid = "";

 String sRet = new String();
 String sSrc = sSql;
 do
 {
  int nIndex = sSrc.indexOf("$");
  int nSqlLen = sSrc.length();
  if (nIndex < 0)
   break;
  sMid = sSrc.substring(nIndex+1,nSqlLen);
  String sTok = getTok(sMid); // getToken
  int nTok = sTok.length();
  sTail = sSrc.substring(nIndex + nTok+1,nSqlLen);
  sHead = sSrc.substring(0,nIndex);
  // sSrc = sHead;
  String sVal = rParam.GetStrValue(sTok);
  if (sVal == null)
  {
   sVal = "";
   if (nIndex > 0)
   {
    char c = sSrc.charAt(nIndex-1);
    if (c == '\'' || c == '\"')
     sVal = "";
   }
  }
  else
  {
   if (sVal.length() <= 0)
   {
    sVal = "";
    if (nIndex > 0)
    {
     char c = sSrc.charAt(nIndex-1);
     if (c == '\'' || c == '\"')
      sVal = "";
    }
   }
  }
  sVal = WCString.nullCheck(WCStmt.toSqlValue(sVal,sDsn));
  sRet += sHead;
  sRet += sVal;
 
  sSrc = sTail;
 } while (true);
 if (WCString.isEmpty(sRet))
 {
  sRet = sSql;
 }
 else
 {
  sRet += sTail;
 }
 return sRet;
}


public static String toSqlValue(String sSrc,String sDsn)
{
 if (WCString.isEmpty(sSrc) || WCString.isEmpty(sDsn))
 {
  return null;
 }
 String sRet = new String();
 int nLen = sSrc.length();
 String sDatabaseType = WCDBConnectionManager.getDatabaseType(sDsn);
 if (WCString.compareNoCase(sDatabaseType,"mysql") == 0)
 {
  for (int i=0;i<nLen;i++)
  {
   char cChar = sSrc.charAt(i);
   if (cChar == '\'')
   {
    sRet += "'";
   }
   else if (cChar == '\\')
   {
    sRet += "\\";
   }
   sRet += cChar;
  }
 }
 else if (WCString.compareNoCase(sDatabaseType,"mssql") == 0
  || WCString.compareNoCase(sDatabaseType,"oracle") == 0)
 {
  for (int i=0;i<nLen;i++)
  {
   char cChar = sSrc.charAt(i);
   if (cChar == '\'')
    sRet += "'";
   sRet += cChar;
  }
 }
 return sRet;
}
-- WCStmt.java에서 makeQuery 부분 추출 끝

아래의 소스가 완벽히 실행하기 위해서는 WCProperties,WCVector,WCLog,WCSystem 등의 source코드가 필요합니다.
이러한 java source는 Web Development Library(www.webdevlib.net)에서 download 받아 사용하실 수 있습니다.
물론 www.webdevlib.net에서 소스코드를 받지 않고, 아래의 소스 코드를 수정하여 사용하실 수도 있습니다.
의도적으로 소스코드의 일부만 글로 쓰는 것은 아닙니다. 모든 소스에 대한 설명은 차차 하겠습니다.

첨부파일 : sql_makeQuery.zip
sql_makeQuery.jsp
WCDBConnection.java
WCDBConnectionPool.java
WCDBConnectionManager.java
WCStmt.java
WCProperties.java

출처 : 고급 웹 UI 개발 라이브러리 Web Development Library 소스공개 : http://www.webdevlib.net

Posted by 1010
05.JSP2009. 3. 9. 18:04
반응형

먼저 다음 페이지 이동 특성들을 미리 알아볼 필요가 있습니다

JSP에서는 페이지 이동시 다음 4가지 정도의 방법이 있습니다


 JavaScript를 이용

window.open, location.href, location.replace 등을 이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

      <script>location.href = "admin.jsp"; </script>

<% } else { %>

      <script>alert('권한이 없어요!'); window.history.back(); </script>

<% } %>

         

특징적인부분은 브라우져의 주소창이 변경되며

(이말은 즉슨 클라이언트가 다시 admin.jsp를 서버에 요청한다는 말입니다)

login_process.jsp 에서 jsp가 다 실행되고 브라우져에 out put된 html 및
javascript들만으로

실행된 코드들이라는 것입니다


response.sendRedirect를 이용

login_process.jsp

<% if (a == null) {

          response.sendRedirect("admin.jsp");

     } else {

          response.sendRedirect("login.jsp");

     }


     a = "test 입니다";

     System.out.println(a);

%>


이 코드에서 a가 출력될까요 안될까요?

출력 됩니다.

sendRedirect가 되더라도 밑에 jsp 코드들은 모두 실행 된다는 말입니다

response.sendRedirect는 기본적으로 모든 로직들을 다 처리한 후 코드
맨 마지막 부분에사용하는 것이 올바른 방법입니다

만약 그렇지 못한 경우는 response.sendRedirect 다음 바로 return;
이라는 코드를 집어 넣어야 합니다


response.sendRedirect은 HTTP 헤더정보를 변경하여 redirect시키기
때문에 역시 브라우져의 주소창이 변경되며 sendRedirect가 실행되기전
html이나 javascript로 out put되는 코드들은 모두 실행되지 않습니다.


forward 이용

jsp 태그의 <jsp:forward> 나 servlet의 RequestDispatcher.forward 를
이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

          <jsp:forward page="admin.jsp"/>

<% } else { %>

          <jsp:forward page="login.jsp"/>

<% }


     a = "test 입니다";

     System.out.println(a);

%>


그럼 위의 코드의 경우 a가 출력 될까요 안될까요?

정답은 출력 안됩니다. 바로 forward 되어 버립니다.

클라이언트로 응답주지 않고 바로 서버측에서 admin.jsp로 이동하기 때문에

주소창이 바뀌지 않고 그로인해 브라우져에 출력되는 응답속도 또한 사용자가
보기에는응답이 빠른 장점이 있습니다


하지만 forward 이후 JSP 코드들이 실행되지 않는것 사실이지만 만약 finally절이
있는경우finally절은 실행 됨으로 확실히 알아둡시다.


meta 태그 이용

마지막으로 meta 태그를 이용할 수도 있습니다.


<META http-equiv=refresh content="0;url=admin.jsp">


즉 요약하자면..

페이지 이동 방법이 여러가지가 있습니다.

그 특성들을 잘 알고 올바르게 사용하여야 합니다.


출처: http://jakartaproject.com/article/jsptip/1114929726078
Posted by 1010
05.JSP2009. 3. 4. 09:33
반응형

JSP 페이지 head에 두줄만 적어주세요.


1. 엑셀파일로 다운받고 싶은 페이지(list.jsp)에 엑셀파일 버튼을 만들고

   excel.jsp(파일명은 각자) 파일을 링크한다.


2. excel.jsp는 엑셀파일로 다운받고 싶은 페이지(list.jsp)와 동일하게 생성한다.


3. excel.jsp 파일에 <head>에 아래 두줄을 작성한다.

<head>
 <title>엑셀 다운로드</title>
<%
 //모든 HTML은 Excel 파일형식으로 변환됨 (편하지 않나요?)
 // 엑셀 파일 다운로드 처리
 response.setHeader("Content-Disposition", "attachment; filename=myexcel.xls");
 response.setHeader("Content-Description", "JSP Generated Data");
%>
</head>


4. list.jsp 페이지에서 excel.jsp로 파라미터 값을 넘겨야 겠죠?
히든값으로 해서 넘겨줘요

list.jsp 파일 form 안에 적어주세요.
<!-- 엑셀 다운로드를 위한 프레임 시작-->
 <iframe name="excel" width="0" height="0" frameborder="0"></iframe>
<!-- 엑셀 다운로드를 위한 프레임 끝-->


5. excel.jsp에서 각자 상황에 맞게 테이블 모양을 변경해주세요

Posted by 1010
05.JSP2009. 2. 26. 12:21
반응형

JSP Tomcat 개발환경 구축(window기준)

1. JDK 설치 

 1) 다운로드: http://developers.sun.com/downloads/

 2) 설치(6u10 Beta b25 for Windows기준):
     jdk기본경로 -> C:\Program Files\Java\jdk1.6.0_10
     jre기본경로 -> C:\Program Files\Java\jre6

 3) 환경변수(내컴퓨터->오른쪽단추->팝업페뉴->속성(등록정보)->고급->환경변수->(시스템변수 or 사용자변수)):
 
  JAVA_HOME = C:\Program Files\Java\jdk1.6.0_10
  (새로 만들어야 함, 주의할 것은 마지막에 ;(쌔미콜론)이 없어야함)
 
  CLASSPATH = .;%JAVA_HOME%\jre\lib\rt.jar;%JAVA_HOME%\lib\tools.jar

  Path = %Path%;%JAVA_HOME%\bin; (기존의 Path 뒷쪽에 추가)
  (%Path%;부분은 이전의 path를 의미)
  (실재로 추가하는 것은 ;%JAVA_HOME%\bin; 뿐임)
  (이때 ;(쌔미콜론)은 변수들을 구분하는 구분자로 사용되는 것임)

  예)Path = %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%\bin;

2. Tomcat 설치

 1) 다운로드: http://tomcat.apache.org/download-60.cgi -> Binary Distributions  Core: Windows Service Installer 버전 다운로드

 2) 설치(tomcat6.x기준)
     1. License Agreement -> I Agree 선택
     2. Choose Componets -> Full 선택(Examples 설치를 위해)
     3. Choose Install Location -> C:\Program Files\Apache Software Foundation\Tomcat 6.0 (tomcat기본경로)
     4. Configuration ->
   prot = 8080(수정가능)
   User Name = admin, Password = 1234 (tomcat manager와 tomcat admin 창에 들어가기 위해 필요)
     5. Java Virtual Machine -> C:\Program Files\Java\jre6 (기본 jre 경로)


 3) 환경변수(내컴퓨터->오른쪽단추->팝업페뉴->속성(등록정보)->고급->환경변수->(시스템변수 or 사용자변수)):

  CATALINA_HOME
  = C:\Program Files\Apache Software Foundation\Tomcat 6.0

  (새로 만들어야 함, 주의할 것은 마지막에 ;(쌔미콜론)이 없어야함)

  Path = %Path%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin;
  (기존의 Path 뒷쪽에 추가)(실재로 추가하는 것은 ;%CATALINA_HOME%\bin; 뿐임)

  예)Path = %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%\bin;%CATALINA_HOME%\bin;

  ## command(프롬프트)창에서 set 입력해서 환경변수 적용 결과 확인 할 수 있음 ##


 4) 자바 ext폴더에 library 추가
   원본 파일 위치 = %CATALINA_HOME%\lib\servlet-api.jar 
    (javax.servlet패키지와 javax.servlet.http패키지 가 들어있다.)
   복사할 폴더 위치  =  %JAVA_HOME%\jre\lib\ext



3. Web Server 동작확인
 시작메뉴->모든 프로그램(p)->
Apache Tomcat6.0->
Moniter Tomcat->
윈도우작업표시줄->
트레이(Tray:시계표시부분)->
Moniter(빨간깃발 원안에 세모표시)->
오른쪽단추->Start Service->
인터넷익스플로러->
주소표시줄->
http://localhost:8080/->
열린창에서 좌측상단에 tomcat로고 보이면 정상동작->
화면 좌측메뉴->
Administration->
Tomcat Manager 클릭->
아이디=admin,패스워드=1234->
Manager 창 확인

####주의사항: 자바환경변수가 잘못 설치되면 톰캣이 정상작동하지 않음#####


4. Eclipse WPT Server 설치 및 동작 확인


1. eclipse의 주메뉴에서 Window -> Preferences 선택

2. Preferences창의 좌측 트리메뉴에서 Server -> Runtime Environments 선택

3. Server Runtime Environments창에서 Add 선택

4. new Server Runtime Environment 창의 트리메뉴에서 Apache -> Apache Tomcat v6.0 선택하고 Next 버튼 선택

5. Tomcat installation directory의 항목에 Browser 버튼을 선택한 후 설치된 CATALINA_HOME을 찾아서 지정한다.
예 : C:\Program Files\Apache Software Foundation\Tomcat 6.0

6. Finish 버튼을 선택하여 서버설정을 완료한다.

7. Server Runtime Environments창에서 OK버튼을 선택해서 빠져나온다.

8. eclipse의 뷰 중에서 Servers을 선택한다.

9. Servers 뷰의 내용창에서 마우스 오른쪽 버튼을 클릭해서 팝업메뉴의 New -> Server 를 선택한다.

10. New Server 창에서 설정내용을 확인 한 후 Finish를 선택한다.
 -> 이 과정이 끝나면 Servers뷰의 내용창에 tomcat 서버가 설정된 것이 보인다.

11. Project Explorer 뷰 내용창에 Servers 프로젝트가 추가된 것을 확인한다.

12. Project Explorer 뷰 내용창의 여백 부분을 마우스오른쪽버튼으로 클릭하고 팝업메뉴를 띄워 New -> Dynamic Web Project 를 선택한다.

13. New Dynamic Web Project 창에서 Project Name 항목에 새로운 프로젝트의 이름을 기록한다.     
   예:Test
   주의 : 만일 내용창에 Test라는 프로젝트가 보이지 않으면 마우스 오른쪽 버튼을 클릭해서 팝업메뉴에서 ReFresh를 선택하면 보인다.

14. Project Explorer 뷰 내용창의 프로젝트 목록중에서 새로 작성한 Test라는 프로젝트를 선택한다.

15. Test프로젝트의 하위 폴더인 WebContent에서 오른쪽 버튼을 클릭해서 팝업메뉴를 띄우고 New -> JSP른 선택한다.
 주의 : Project Explorer가 아닌 Explorer(Package,Navigator)에서는 New -> Other를 선택한다. 그리고 New 창의 트리메뉴에서 Web -> JSP를 선택한다.

16. New JavaServer Page 창에의 File name 항목에 새로운 JSP파일의 이름을 기록한다.
예 : test.jsp
주의 : 이때 확장자를 기록하지 않아도 된다.

17. edit 뷰 창의 test.jsp 내용창 안에 내용을 기록한다.
예 :
     <body>
        WTP server 테스트입니다.    <-- 이부분을 입력한다.
     <body>

18. eclipse의 주메뉴에서 File -> Save를 선택한다.

19. edit 뷰 창에서 마우스 오른쪽 버튼을 클릭해서 팝업메뉴를 띄우고 Run As -> Run on Server를 선택한다.

20. Run on Server창에서 Finish를 선택한다.
이과정까지 끝나면 브라우저가 에디트뷰에 하나 추가되면서 결과가 보인다.
결과 예 : WTP server 테스트입니다.

Posted by 1010
05.JSP2009. 2. 18. 17:37
반응형

www.servlets.com 사이트 에 접속한다. 


 

빨간 네모 박스가 쳐져 있는 부분을 클릭한다.

 

 

스크롤을 아래로 약간 내려 보면 DownLoad 부분이 나오는데 거기에서

Cos 로 시작되는 파일을 다운 받는다.

다운받은 압축 파일의 압축을 풀고

cos-05Nov2002/lib 안에 cos.jar 아카이브 파일을

자바 폴더와 톰켓 폴더에 각각 넣어주도록 한다.

 

C:/Java/jdk1.6.0_06/jre/lib/ext

C:/Java/jre1.6.0_06/lib/ext

C:/Tomcat5.5/common/lib

 

 

jsp 파일을 코딩시 폼양식에 enctype="multipart/form-data" 를 넣어주도록 한다.

ex ) <form name="form" method="post" enctype="multipart/form-data">

 

tip! enctype을 JavaScript 에서 제어하고 싶을시에는 아래와 같이 코딩해준다.

ex) 폼이름.encoding = "multipart/form-data"; 

    form1.encoding="multipart/form-data";

 

※ 주의 : enctype 을 지정해 주지 않으면 파일 업로드가 되지 않으며 톰캣의 내장객체 request 객체를 사용할 수 없다.

         정확히는 enctype 을 multipart/form-data 로 설정해 주었다면 톰갯의 내장객체 request 객체를 사용할 수 없다.

 

 1) MultipartRequest 를 사용하기 위해서는 com.oreilly.servlet 패키지를 import! 해야 한다.

   ex) <%@ page import! = "com.oreilly.servlet.*" %>

 

 2) MultipartRequest 는 객체를 생성하자 마자 파일을 업로드 시킨다.

   ex) MultipartRequest multi = new MultipartRequest(request, "파일 저장 경로(String)", 파일크기(int), "인코딩");

       // 이순간 업로드가 발생된다.

 

 3) MultipartRequest 를 사용 하게 되면 톰캣의 request 객체의 getParameter 메서드를 이용하여

   값을 전달 받지 못한다. 따라서 MultipartRequest를 사용하게 되면 값을 전달 받기 위해서는 MultipartRequest 객체의

   getParameter 메서드를 이용하여 값을 전달 받아야 한다.

   ex) String name = multi.getParameter("name");

 

 4) 파일을 저장할 경로는 직접 써주기 보다는 톰캣의 내장 객체인 application 객체의 getRealPath() 메서드를 사용하자.

    String savePath = application.getRealPath("파일을 저장할 폴더");

    ex) String savePath = application.getRealPath("/product");

        MultipartRequest multi = new MultipartRequest(request, savePath);

 

 5) 파일 이름을 받아올때는 MultipartRequest 의 getFileSystemName 메서드를 사용한다.

    String fileName = multi.getFilesystemName("파라미터 name");

    ex) String fileName = multi.getFilesystemName("fileName");

 

 

 출처 : http://blog.naver.com/lbiryu/30033838465

Posted by 1010
05.JSP2009. 2. 18. 17:36
반응형

<%@ page contentType="text/html; charset=euc-kr"%>
<
%@page import!="java.util.*" %>

<%
request.setCharacterEncoding("euc-kr");

String url = "";
    Enumeration e = request.getParameterNames();  
    while(e.hasMoreElements()){
     String name = (String)e.nextElement();
      if(request.getParameter(name)!=null){
        url += name + "=" + request.getParameter(name) + "&";
      }else{
        url += name + "=" + "" + "&";
      }
    }
out.println(url);   
 %>

Posted by 1010
05.JSP2009. 2. 18. 17:35
반응형

출처 : http://blog.daum.net/badog/4457979

// downloadFile.jsp

 

<%@ page language="java" contentType="text/html; charset=euc-kr" pageEncoding="EUC-KR" %><%@ page import!="java.io.*"%><%
request.setCharacterEncoding("euc-kr");

String filename = new String((request.getParameter("fileName")).getBytes ("8859_1"),"EUC_KR");
String  filePath = "C:/test";

InputStream in= null;
OutputStream os = null;
File file= null;
File viewFile = null;
boolean skip= false;
String client= "";

try{
  String fname1 = "";
  String fname2 = "";
  String fname  = "";
  fname  = filename;
  fname1 = new String(fname.getBytes("8859_1"),"euc-kr");

 try{
    file = new File(filePath, fname);
    viewFile = new File(filePath, fname1);
//   out.print("file : " + file);
    in= new FileInputStream(file);
 }catch(FileNotFoundException fe) {
     skip= true;
  }


  fname2   = new String(fname1.getBytes("euc-kr"),"8859_1");
  response.reset();
//  client = request.getHeader("User-Agent");
//  response.setContentType("application/x-msdownload;");
//  response.setHeader("Content-Description", "JSP Generated Data");

 if(!skip){
    if(client.indexOf("MSIE 5.5") != -1){
      response.setHeader("Content-Type", "doesn/matter; charset=euc-kr");
      response.setHeader("Content-Disposition", "filename="+new String(fname.getBytes("euc-kr"),"8859_1"));
    }else{
     response.setHeader("Content-Type", "application/octet-stream; charset=euc-kr");
      response.setHeader("Content-Disposition", "attachment; filename="+new String(fname.getBytes("euc-kr"),"8859_1"));
    }
    response.setHeader("Content-Transfer-Encoding", "binary;");
    response.setHeader ("Content-Length", ""+file.length());
    response.setHeader("Pragma", "no-cache;");
    response.setHeader("Expires", "-1;");

    os = response.getOutputStream();
    byte b[] = new byte[10240];
    int leng = 0;
   
    while( (leng = in.read(b)) > 0 ){
      os.write(b,0,leng);
    }
 }else{
    out.println("<script>");
    out.println("alert!('파일 다운로드중 애러가 발생하였습니다.')");
    out.println("</script>");
     return;
 }
}catch(Exception e) {
  System.out.println(e);
}finally{
  if(os != null) try{os.close();}catch(Exception ex){System.out.println(ex);};
 if(in != null)  try{in.close();}catch(Exception ex){System.out.println(ex);};
}%>



<a href="downloadFile.jsp?fileName=<%=file %>">다운로드</a>



어디서 구해온 소스인데 이거 때문에 진짜 고생했다.

파일은 다운로드 되는데 getOutputStream 애러가 계속 나는 것이였다.

알고보니 이놈은 스페이스나 줄바꿈 뭐 이런게 들어가면 안되는 것이다.

<%...%><%...%> 요런식으로 다 붙여야 한다.

그리고 다운로드 취소시에 소켓 애러가 나는데 그건 무시하자. 그건 문도 안열었는데 닫으라고 하니까 나는거다.

Posted by 1010
05.JSP2009. 1. 30. 20:07
반응형
 

InputStream과 OutputStream을 사용하는 경우 파일사이즈가 크면 java.lang.OutOfMemoryError이 발생하는 경우가 생겨, BufferedInputStream과 BufferedOutputStream을 사용하여 문제를 해결해 보았다.


JSP 다운로드 프로그램:


 try {
  String path = WEBConstants.SYSTEM_DOCROOT;
  File file = new File(path + filePath);


  response.reset() ;
  response.setContentType("application/x-octetstream");

  response.setHeader("Accept-Ranges", "bytes");
  response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(), "UTF-8") +"\"" );
  response.setHeader("Content-Length", ""+file.length() );

  BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
  BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());

  int read = 0;
  while((read = in.read()) != -1) {
   os.write(read);
  }
 
  in.close();
  os.close();
 } catch(Exception e) {
  e.printStackTrace();
  out.println("<script language=javascript>");
  out.println("alert('Does not file !');");
  out.println("history.go(-1)");
  out.println("</script>");
 }

Posted by 1010
05.JSP2009. 1. 30. 19:55
반응형

http://www.j2eestudy.co.kr/ 에서 아키 (Archi)라는 분이 작성하신글입니다. 유용하게 쓰일 일이 있을것 같아서 퍼왔습니다.


-------------------------------------------------------------------


안녕하세요.

JSP File Brows입니다. 제가 만든건 아니구요.:-)


저작권은 첨부파일 내에 포함되어 있습니다.
윈도우탐색기(?) 기능과 비슷하구요. 설치가 간편하니까 시간있으신 분들은 한번 사용해 보세요.(추천!)

[설치 방법]
첨부파일 압축을 풀면 아래와 같은 파일이 있습니다.
Browser.jsp
example-css.css

웹서버 루트 아래 특정 디렉토리에 복사하시고 "http://localhost/Browser.jsp" 이런식으로 접근하시면 됩니다.

저는 톰켓에서 테스트해봤는데 잘 되었습니다.

선택된 파일 압축하는 기능도 있네요. ;-)
한글 지원은 안 되나 보네요.

잘 사용하시면 유용한 툴이 될 것 같네요.

 
   
Posted by 1010
05.JSP2009. 1. 29. 17:01
반응형
  웹개발언어>>JSP



  웹개발언어>>JSP>>Mail관련

      JavaMail 설치
      JavaMail 메일링 리스트
      JavaMail 기본 설치
      JavaMail 기본설치 -사용예제
      JavaMail 파일첨부메일


  웹개발언어>>JSP>>기타

      Jakarta 프로젝트의 Regexp(정규식) 패키지 사용하기
      J2EE(Java 2 Enterprise Edition)환경 소개
      오라이온 서버(Orion Server)설치 및 J2EE 애플리케이션의 배치
      CVS 사용
      XT를 이용한 XML/XSL 사용
      jsp에서 log()이용하기
      JspSmartUpload 설치
      JspSmartUpload FAQ
      Servlet 한글출력
      package 선언된 java 컴파일하기
      동적이미지 생성
      리눅스와 JAVA


  웹개발언어>>JSP>>Beans

      Beans 사용하여 회원제 사이트를 만들자
      JSP에서 Beans 사용하기
      useBean
      session bean
      beans 활용
      bean 한글처리


  웹개발언어>>JSP>>기본강좌

      클래스변수와 환경변수
      자바 기반의 웹 개발, Servlet과 JSP
      JSP 맛보기
      웹인증(Form study)
      jsp 에러잡기
      File Upload
      한글처리
      include 집중분석
      jsp tag library기초강좌


  웹개발언어>>JSP>>DB관련

      JDBC를 익히자
      Database 접속을 Pool로 관리하자
      JNDI로 jdbc 사용하기
      Mysql 설치
      MySQL 인증설정
      MySQL 테이블 생성
      MySQL 자료입력
      MySQL 자료조회
      MS Access ODBC연결
      procedure 사용하기
      CallableStatement 사용하기
Posted by 1010
05.JSP2009. 1. 23. 15:58
반응형


JavaTM EE (J2EE) Programming (with Passion!)




Message to potential attendees

The next and 15th session will start from Feb. 1st, 2009.  Just like other online courses I teach, this course is offered online only.   For those of you who are not sure what it's like to take this course online, please see What it's like to take Sang Shin's online courses.  Just to set the expectation correctly, there is no real-time webcasting. 

How to register for this course

In order to register for this course, all you have to do is sending a blank email to the following email alias. 

Basically, when you send a blank email to the above, you are subscribing our class forum. This forum can be used for posting questions/answers.  Please use this forum for all class related communication (technical or non-technical). 

If you have any further questions on this course, please see the course FAQ (Frequently Asked Questions).



Topics and Schedule


Note that only the topics with the dates assigned will be covered in this course. (You need to submit homeworks only on the topics that have dates.)  It is my plan to provide presentation slides and hands-on labs for the topics that do not have dates whenever I find time.


  1. Introduction
  2. Web Core Technologies: Servlet and JSP
  3. JDBC, SQL,
    • SQL (1 hour lecture + 1 hour lab) - (March 12th, 2009: Week #6)  - there is no homework
    • JDBC (1 hour lecture + 1 hour lab) - (March 12th, 2009: Week #6) (homework #9)
  4. Web-tier Security
  5. Struts
  6. Struts 2
    • Struts 2 Basics (2 hour lecture + 1 hour lab) - (April 25th, 2009: Week #10) (homework #13)
    • Struts 2 and Ajax ()
    • Struts 2 and Tiles
    • Struts 2 and view technologies
  7. JavaServer Faces (JSF)
    • JSF basics I
    • JSF basics II
    • Validation
    • Conversion 
    • Data tables
    • Sample apps
    • Tiles 
    • Using JSF-enabled IDE
    • Building JSF components
    • Related frameworks
    • JSF and Portal/Portlets
    • Testing and Debugging tools
  1. Other Web-tier Frameworks
  2. EJB 2.x
  3. Java EE 5, EJB 3.0, Java Persistence API (JPA)
  4. Design patterns, Best practices, Performance tuning, etc
  5. Hibernate
  6. Spring framework
    • Spring framework basics
    • Spring framework and persistence
    • Spring framework Web-tier technologies
    • Spring AOP
    • Spring and Java EE
    • Misc.
  7. Portlets and Portal
  8. GlassFish
If you submitted all homeworks - the deadline for the homework submission is Dec. 11th, 2009 -, please send an email to the homework alias (j2eehomeworks@sun.com) with the following information in order to get a certificate and listed in the Graduates of this course by Dec. 14th, 2009. The subject of the email should be J2EECourse-2009-Fall.
  • <First-name Last-name>, <Nationality or Country of Origin>, <One paragraph you want to say about this course (optional)>
  • Sang Shin, Korea, This is a great course ...




Introduction




Introduction of this course

1. Presentation slides (0.5 hour)

Java EE Overview

The objective of this session is to give you a big picture of Java EE architecture and platform and get yourself prepared for the rest of the course.  You don't have to understand everything that is described in the presentation below.  If you get reasonably good idea on what Java EE is, that should be good enough to proceed.  Please browse through the Resources below.

There is no homework in the week #1.

1. Presentation slides (1 hour)

                                                                                                                              return to topics





Web Core Technologies: Servlets, JSP, and JSTL





Web Application Structure

In this session, you will learn how a typical Web application is built.  You will also learn the internal structure of Web application as well as web.xml file.

1. Presentation slides (1 hour)

2. Lab (1 hour) and homework - The hands-on lab is updated with NetBeans 6.1.
  • 4001_webappstructure.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/webappstructure/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
  • Homework (This is the same homework you will find in the hands-on lab zip file)
  • Change log

                                                                                                                   return to topics

Servlet Basics


You are getting into a very important topic, Servlet.  I expect many of you who get exposed to the Servlet for the first time might feel overwhelmed by the amount of things you feel you have to absorb. Given that the Servlet technology is the most-used functionality of J2EE platform, there are in fact lots of things to learn. 

1. Presentation slides (2 hours)

2. Lab and homework (1 hour) 
3. Resources
                                                                                                                              return to topics

JSP Basics


I assume by now, most of you are relatively comfortable with building and deploying Servlet based Web applications.  In this session, you will learn basic concept of JSP (JavaServer Pages) which is as equally important Web-tier technology as Servlet.  You will also learn how to build a simple JSP pages using JavaBeans.

1. Presentation slides (2 hours)

2. Lab and homework (2 hours)
3. Resources
                                                                                                                              return to topics

Using NetBeans for Developing Web Applications


In this session, you are going to do a lab during which you exercise various features of NetBeans IDE. 

1. Lab and homework (1 hour)
2. Resources
                                                                                                                     return to topics

Servlet Advanced


By now, you have reasonably good idea on how you can use basic features of Servlets and JSP to build Web applications.  In this session, you are going to learn advanced features of Sevlets, mainly filters and life-cycle events.

1. Presentation slides - ServletAdvanced (1 hour)

2. Presentation slides - Servlet 2.4 Enhancements
3. Lab and homework (1 hour)
4. Resources

                                                                                                                              return to topics

Session Tracking


Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

1. Presentation slides (1 hour)

2. Lab and homework (1 hour)
3. Resources
                                                                                                                              return to topics

Expression Language


A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property.

1. Presentation slides


2. Lab and homework (0.5 hour)
3. Resources

                                                                                                                              return to topics

JSP 1.2 Custom Tags - We are not covering this topic in this course


Since the introduction of JSP 2.0 style tag files, the JSP 1.2 style development of custom tags should be avoided whenever possible meaning if you can develop your custom tags using tag files, you should use tag files.  Because of that reason, we are skipping this topic in this course. 

1. Presentation slides (2 hours)


2. Lab
3. Resources


                                                                                                                   return to topics

JSP 2.0 Custom Tags


In this session, you are going learn how to build and use simple tag handler and tag file features of JSP 2.0.

1. Presentation slides (1 hour)

2. Lab and homework(1 hour) 
3. Resources
                                                                                                                              return to topics

JSTL


The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP applications. Instead of mixing tags from numerous vendors in your JSP applications, JSTL allows you to employ a single, standard set of tags. This standardization allows you to deploy your applications on any JSP container supporting JSTL and makes it more likely that the implementation of the tags is optimized.

1. Presentation slides (2 hours)

2. Labs (2 hours)
3. Resources
                                                                                                                              return to topics

Building BookStore Sample Application


In this session, you will build the "Duke's Bookstore" sample application, which is reasonably sophisticated application using different Web-tier technologies, first by using Servlets only, second by using JSP pages only, third by using JSP pages and custom tags, fourth by using JSP pages and JSTL in native format, fifth by using JSPpages and JSTL in XML format

1. Labs (2 hours)

Applets


1. Presentation slides (2 hours)

  • PDF: 1 slide per page
  • StarOffice file
2. Labs (2 hours)
  • 4015_jstlexamples.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jstlexamples/index.html to proceed) - work in progress
  • Online lab document (This is the same document you will find in the hands-on lab zip file
  • Homework
  • Change log
3. Resources
                                                                                                                              return to topics








JDBC, SQL





SQL

SQL is a standard computer language for accessing and manipulating relational databases.  Even though Java persistence technologies such as EJB 3.0 Java Persistence API (JPA) or Hibernate could insulate developers from having to know the detailes of SQL, it is still important to know the intricacies of SQL in order to be able to write highly performant Java EE applications which involves persisting data to the relational database.

1. Presentation slides (1 hour)


2. Lab (1 hour)

Since the SQL tutorial from w3cschools.com seems to be the best tutorial, I have decided to use the material as the hands-on lab for the topic of SQL.  There is no homework on this topic.
3. Resources
4. Configuration paramater values for databases
  • Java DB (Derby)
    • jdbc:derby://localhost:1527/mydatabase (URL)
    • org.apache.derby.jdbc.ClientDriver (Driver class)
    • app (Username)
    • app (Password)
  • MySQL
    • jdbc:mysql://localhost:3306/test (URL)
    • com.mysql.jdbc.Driver (Driver class)
    • MySQL Connector/J  (Driver name)
    • no username
    • no password
    • org.hibernate.dialect.MySQLDialect
  • HSQL
    • jdbc:hsqldb:file:messagedb
    • org.hsqldb.jdbcDriver
    • sa
    • no password
    • org.hibernate.dialect.HSQLDialect
                                                                                                                             return to topics

JDBC

JDBC is standard Java API for accessing amdn manipulating relational database through SQL.  Even though Java persistence technologies such as EJB 3.0 Java Persistence API (JPA) or Hibernate could provide higher layer abstraction than JDBC, JDBC is still one of the most popular Java APIs for persisting data to the relational database.

1. Presentation slides (1 hour)


2. Lab (1 hour)
3. Resouces
                                                                                                                              return to topics





Web-tier Security




                                                                                                                  

Security Basics

Security is one of the most important areas of distributed computing. 


1. Presentation slides (1 hour)

                                                                                                                              return to topics

Web Application Security

1. Presentation slides (1 hour)

2. Lab (1 hour)
3. Resouces
                                                                                                                              return to topics

SSL

1. Presentation slides (1 hour)

2. Resources
                                                                                                                              return to topics

Web Application Security Threats and Counter-Measures

1. Presentation slides (1 hour)


2. Labs (1 hour)
  • 4010_websecthreats.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/websecthreats/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources
                                                                                                                              return to topics




Struts





MVC (Model-View-Controller) Framework

1. Presentation slides (1 hour)

                                                                                                                              return to topics

Struts Basics


In its short existence, Struts has established itself as a popular web application framework that is based on MVC (Model-View-Controller) architecture.  Even though new generation of Web application frameworks such as JavaServer Faces (JSF) and Tapestry are providing more advanced features, Struts is still being used widely in the field.

1. Presentation slides (1 hour)

2. Lab (2 hours)
3. Resources
                                                                                                                              return to topics

Step by Step Guide for Building a Simple Struts Application


1. Presentation slides (1 hour)

                                                                                                                              return to topics

Struts Sample Applications


1. Lab (2 hours)  - the contents will be updated in the future
  • 4207_strutsexamples.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutsexamples/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                              return to topics

Struts Tags


1. Presentation slides (1 hour)

2. Labs (2 hours)  - the contents will be updated in the future
  • 4209_strutstags.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutsttags/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                              return to topics

Struts Advanced


1. Presentation slides (1 hour)

2. Labs (2 hours) - they are not ready yet!
  • 4209_strutsadv.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutsadv/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                              return to topics

Struts Validation Framework

1. Presentation slides (1 hour)


2. Lab (1 hour) - the contents will be updated in the future
  • 4210_strutsvalidator.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutsvalidation/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                              return to topics

Tiles Framework

1. Presentation slides (1 hour)


2. Lab (1 hour)  - the contents will be updated in the future
3. Resources
                                                                                                                              return to topics

Struts Testing, Debugging, Logging, and Performance

1. Presentation slides (1 hour)


2. Lab (1 hour)
  • 4220_strutstestcase.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutstestcase/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources
                                                                                                                              return to topics

Struts Best Practices

1. Presentation slides (1 hour)

2. Best practices

                                                                                                                              return to topics

Struts and Databases

1. Presentation slides (1 hour)


2. Lab (1 hour)
  • 4222_strutsdatabase.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/strutsdatabase/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources
                                                                                                                              return to topics


Struts Security

1. Presentation slides (1 hour)




                                                                                                                              return to topics




JavaServer Faces (JSF)





Building "Hello World" JSF applications


This is to build and run a simplest possible JSF application step by step and make sure the software is working correctly.

1. Lab  (1 hour)
  • 4101_jsfhelloworld.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfhelloworld/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                    return to topics

Step by step for building "Guess a Number" JSF application

You are going to build a simple "Hello World" sample JavaServer Faces (JSF) application exercising the basic features of a typical MVC-based Web application framework of JSF architecture such as request dispatching, navigation, event handling, and so on.  These features will be more clearly explanined in the following presentation - JSF Basics - but the goal is to build an application first and see how it works.


1. Presentation slides

2. Lab  1 - Do Exercise 1 & 2! (1 hour)

                                                                                                                    return to topics


JSF basics

The basic concepts of JSF architecture and features will be discussed.

1. Presentation slides (1.5 hour)

2. Resources

                                                                                                                    return to topics


JSF Component Model

1. Presentation slides (1.5 hour)

2. Lab (1 hour)

In JSF framework, a component tree gets constructed whenever a page (that contains JSF UI components are used) is accessed.  Since this component tree is a fundamental piece of JSF architecture, it is important to understand the concept of it.  This lab lets you access and display this component tree.
3. Resources


JSF tags

One popular markup language that your application will support is obviously HTML.  In this session, you will learn various JSF-based tags for the HTML browser client.


1. Presentation slides (1 hour)

2. Lab 1 (0.5 hour)
  • Review Examples of JSF HTML tags from JSF tags list from horstmann.com
3. Lab 2
4. Resources

                                                                                                                    return to topics


Managed Beans


1. Presentation slides (1 hour)

2. Lab 1 - Do the exercise 3 (1 hour)
  • 4104_jsfguessnumber.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfguessnumber/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics


Navigation

1. Presentation slides (1 hour)

2. Lab 1 - Do the exercise 4 (1 hour)
  • 4104_jsfguessnumber.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfguessnumber/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Lab 2
  • 4129_jsfnavigation.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfnavigation/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
4. Resources

                                                                                                                    return to topics


Event model

1. Presentation slides (1.5 hour)  - todo: add differences between action and actionListerner in JSF 1.2

2. Lab (1.5 hour)
3. Resources


                                                                                                                    return to topics

Life-cycle and PhaseListener

1. Presentation slides (1.5 hour)

2. Lab 

3. Resources

                                                                                                                    return to topics

Immediate Attribute

1. Presentation slides (0.5 hour)

2. Lab 

3. Resources

                                                                                                                    return to topics

Styling with CSS

1. Presentation slides (1.5 hour)

2. Lab

3. Resources

                                                                                                                    return to topics

Validation

1. Presentation slides (1.5 hour) - todo: make sure all validation strategies are covered

2. Lab 1 - Do the exercise 5! (20 minutes)
3. Lab 2
3. Resources

                                                                                                                    return to topics


Client-side Vadliation

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice file
2. Lab

3. Resources

                                                                                                                    return to topics

Converter

1. Presentation slides (1.5 hour) - todo: list all built-in converters

2. Lab
  • 4125_jsfconverter.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfconverter/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics


Data Table

1. Presentation slides (1.5 hour)

2. Lab
  • 4123_jsfdatatable.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfdatatable/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics

JSF and Persistence (JPA)

1. Presentation slides (1.5 hour)

2. Lab
  • 4133_jsfjpa.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfjpa/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics

Walk-through of CarStore Sample Application

1. Presentation slides (1.5 hour)

2. Lab 
  • 4111_jsfcarstore.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfcarstore/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                    return to topics


Walk-through of BookStore6 Sample Application


Java EE 5 tutorial comes with sample JSF application called bookstore6 in the form of NetBeans project.

1. Lab 
  • 4119_jsfbookstore.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfbookstore/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                    return to topics


Building Some JSF Sample Applications


1. Lab
  • 4102_jsfsimpleapps.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfsimpleapps/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                    return to topics

Tiles

1. Presentation slides (1.5 hour) - todo: How tiles are integrated with JSF

2. Lab 
  • 4124_jsftiles.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsftiles/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                 return to topics

NetBeans Visual Web Pack Basics

1. Presentation slides (1.5 hour)

2. Lab 
3. Resources

                                                                                                                 return to topics

NetBeans Visual Web Pack Advanced


1. Lab 
  • 4136_jsfvisualjsf.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfvisualjsf/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
2. Resources

                                                                                                                 return to topics


Building a JSF Component

1. Presentation slides (1.5 hour)

2. Presentation slides - this is JavaOne 2007 presentation by Kito Man

3. Lab 1
  • 4113_jsfcomponentbuild.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfcomponentbuild/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

4. Lab  2
  • 4430_jsfcustom.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfcustom/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)


                                                                                                                    return to topics



RenderKit

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice file
2. Lab  
  • 4109_jsfrenderkit.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfrenderkit/index.html to proceed) Note: You should do this lab whil
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

Shale Dialog

1. Presentation slides (1.5 hour)

2. Lab
  • 4131_jsfshale.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfshale/index.html to proceed) Note: You should do this lab whil
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Lab 2
4. Resources


                                                                                                                              return to topics

Facelets

1. Presentation slides  (originally by Çagatay Çivici, modified slightly by Sang Shin)

2. Lab 1 (1.5 hour)
  • 4106_jsffacelets.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsffacelets/index.html to proceed) Note: You should do this lab whil
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Lab 2 (1 hour)
  • 4107_jsffaceletscdstore.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsffaceletscdstore/index.html to proceed) Note: You should do this lab whil
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
4. Lab 4 (1 hour) - Optional
5. Resources
                                                                                                                              return to topics

Spring Web Flow and JSF

1. Presentation slides (1 hour)


2. Presentation slides (1.5 hour) - This is JavaOne 2007 presentation
3. Lab  
4. Resources

                                                                                                                    return to topics

Spring framework and JSF integration

1. Presentation slides (1.5 hour) - This is JavaOne 2007 presentation by Kito Mann and Chris Richardson

2. Lab
4. Resources

                                                                                                                    return to topics



Seam

1. Presentation slides (1.5 hour) - This is JavaOne 2007 presentation by xxx

  • PDF: 1 slide per page
  • Video
2. Lab  
  • core-seam
3. Resources

                                                                                                                    return to topics


JSFTemplating

1. Presentation slides (1.5 hour) - This is JavaOne 2007 presentation by xxx

  • PDF: 1 slide per page
  • Video
2. Lab  
  • core-seam
3. Resources

                                                                                                                    return to topics

Building Useful Components (from Core JSF book)

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • Star Office
2. Lab  1
  • 4115_jsfcomponentbuild2.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfcomponentbuild2/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Lab 2
  • core-popup
  • core-resolver
  • core-error
  • core-applet


Tomahawk JSF Components (from MyFaces Apache project)

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • Video
2. Lab 
  • 4116_jsftomahawk.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsftomahawk/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics

ADF components

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • Video
2. Lab
  • 4117_jsfadf.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfadf/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                    return to topics


Misc. 3rd party JSF components

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab  
3. Resources

                                                                                                                    return to topics



Woodstock components

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab
  • 4118_jsfwoodstock.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfwoodstock/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                    return to topics

Building Woodstock components

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab
  • 4118_jsfwoodstock.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfwoodstock/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                    return to topics

Woodstock components and Ajax

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab
  • 4118_jsfwoodstock.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfwoodstock/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                    return to topics


Building Ajax applications using JSF

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab
  • 4121_jsfajax.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfajax/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                    return to topics

DynaFaces


1. Presentation slide - Introduction to DynaFaces

2. Presentation slide - Using DynaFaces

3. Labs (2 hours)
3. Resources

                                                                                                                    return to topics


Ajax4jsf

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StartOffice
2. Lab 
  • 4122_jsfajax4jsf.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfajax4jsf/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

3. Resources

                                                                                                                    return to topics

JSF and Portlets

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StartOffice
2. Lab 
  • 4122_jsfajax4jsf.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/jsfajax4jsf/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources


                                                                                                                    return to topics

Testing tools

1. Presentation slides (1.5 hour)

  • PDF: 1 slide per page
  • StarOffice
2. Lab  
3. Resources

                                                                                                                    return to topics

Localization

1. Presentation slides (1.5 hour)

2. Lab  
3. Resources

                                                                                                                    return to topics





EJB 2.x (as part of J2EE 1.4)





EJB 2.x Overview

1. Presentation slides (1 hour)

2. Lab and homework (2 hours) - work in progress
  • 4281_j2eeejb2.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/ajaxshale/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                              return to topics

Message Driven Bean (MDB)


                                                                                                                              return to topics

JMS

1. Pre-class reading

2 Presentation slides (1 hour)

3. Lab and homework (2 hours)
  • 4281_j2eejms.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/ajaxshale/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
4. Resources

                                                                                                                              return to topics

Session Bean (EJB 2.x)

1. Presentation slides (1 hour)

                                                                                                                              return to topics

Entity Beans (EJB 2.x)

1. Presentation slides (1 hour)

                                                                                                                              return to topics





Java EE 5 & EJB 3.0 & JPA






Introduction to Java EE 5


Java EE 5 is a major major release in the evolution of Java EE with lots of new features. It has a huge emphasis on the ease of development.  The ease of development features include using annotations instead of deployment descriptors, simplified EJB development, use of dependency injection for accessing resources, Java Persistence API (JPA), and annotation based Web service development.  The goal of this presentation and hands-on lab is to give you overall sense of the Java EE features.

1. Presentation slides  - Java EE 5 Overview (1 hour)

2. Presentation slides - Java EE 5 support in NetBeans 5.5

3. Resources
                                                                                                                    return to topics

EJB 3.0 Enterprise Beans


The new EJB 3.0 API makes software development easier by reducing and simplifying the amount of work required from the developer. In other words, fewer classes and less code. This is possible because more of the work is now performed by the container.

1. Presentation slides (1 hour)

2. Presentation slides 2

This is JavaOne 2006 presentation by Michael Keith and Linda DeMichiel, Peter Walker, and Ron Ten-Hove.  You have to register to Sun Developer Network in order to watche the video.
3. Lab and homework
4.  Resources
                                                                                                                    return to topics

Java Persistence API (JPA) Basics


The Java EE 5 platform introduces the new Java Persistence API, which was developed as part of JSR-220. The Java Persistence API can also be used outside of EJB components, for example, in web applications and application clients, and also outside the Java EE platform, in Java SE applications. 

1. Presentation slides 1 (1 hour)

2. Presentation slides 4

This is JavaOne 2006 presentation by Michael Keith and Linda DeMichiel, Peter Walker, and Ron Ten-Hove.  You have to register to Sun Developer Network in order to watche the video.
3. Lab and homework
4. Resources

                                                                                                                              return to topics

Java Persistence API (JPA) Mapping


1. Presentation slides
2. Lab  (1 hour)

3. Resources

                                                                                                                             return to topics


JPA Query Language


1. Presentation slides
2. Lab  (1 hour)
  • 3412_javaee5jpajpql.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/javaee5jpajpql/index.html to proceed) 
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                             return to topics

JPA Advanced


1. Presentation slides
2. Lab  (1 hour)
  • 3412_javaee5jpajpql.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/javaee5jpajpql/index.html to proceed) 
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                             return to topics

Java Persistence API (JPA) Transaction


1. Presentation slides
2. Presentation slides  2

This is JavaOne 2007 presentation by Michael Keith.  You have to register to Sun Developer Network in order to watche the video.
3. Presentation slides 3

This is JavaOne 2007 presentation by Rima Patel and Marina Vatkina.  You have to register to Sun Developer Network in order to watche the video.
         4. Lab  (1 hour)

                                                                                                                   return to topics





Design Patterns, Best Practices, and Performance Tuning





Java EE Design Patterns


1. Presentation slides (1 hour)


                                                                                                                              return to topics



Performance Tuning


1. Presentation slides (1 hour): Servlet Performance

2. Lab  (1 hour) using NetBeans Enterprise Pack
  • 5115_netbeansprofiler.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/javaswing/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)

                                                                                                                              return to topics

UML


1. Presentation slides - Object-oriented Concepts

2. Presentation slides  - OO Analysis

3. Presentation slides -  OO Design

4. Presentation slides - UML

5. Lab  (1 hour) using NetBeans Enterprise Pack

  • 8105_nbeuml.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/nbeuml/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
                                                                                                                            return to topics




Other Web-tier Frameworks




Shale

1. Presentation slides (1 hour)

2. Lab and homework (2 hours) - work in progress
  • 4261_webshale.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/webshale/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resources

                                                                                                                              return to topics



Echo2


1. Presentation slides

  • PDF: 1 slide per page
  • StarOffice file
2. Lab 2 (2 hours) - work in progress
  • 4282_ajaxecho2.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/ajaxecho2/index.html to proceed)
  • Online lab document (This is the same document you will find in the hands-on lab zip file)
3. Resouces
                                                                                                                              return to topics

Tapestry


1. Presentation slides

  • PDF: 1 slide per page
  • StarOffice file
2. Resources

                                                                                                                              return to topics


Wicket


1. Presentation slides

  • PDF: 1 slide per page
  • StarOffice file
2. Resources


                                                                                                                              return to topics

Comparing various Java Web Application frameworks


1. Presentation slides

2. Resources

                                                                                                                              return to topics

 



Hibernate





Hibernate Step By Step


This session takes you through the basics of building a simple HelloWorld Hibernate application.  Even though you are building the simplest possible Hibernate application, you will get an exposure to the relatively complete concept of Hibernate.  You will also learn how to display context sensitive Java document on Hibernate classes.
                                                                                                                              return to topics

Hibernate Basics


In this session, you are going to learn the basic concepts of Hibernate including transaction demarcation, using DAO pattern, generating keys using different schemes, event handling, and session management.
                                                                                                                              return to topics

Hibernate Mapping


In this session, you are going to learn various mapping strategies including cadinalities (one to many relationship, many to many relationship), and how class hierarchy is represented in the database tables through inheritance strategies.
                                                                                                                              return to topics

Hibernate Support in NetBeans IDE 6.5


                                                                                                                              return to topics

Hibernate Query Language


In this session, you are going to learn how to perform query operations using Criteria Query API, Query By Example, HQL, and native SQL.

                                                                                                                              return to topics

Hibernate Transaction and Concurrency



                                                                                                                              return to topics

Hibernate Interceptors & Events - Work in progress




                                                                                                                              return to topics


Hibernate Join Fetch (N+1 Select Problem, Join Fetch, Lazy Fetch)


The fetch mode you choose in using Hibernate will have performance consequences especially if you fall into a trap of N+1 selet problem. In this session, you will learn the basic concepts of the fetch modes and also N+1 select problem and how to avoice it.

                                                                                                                              return to topics

Hibernate Caching


In this session, some of the advanced topics of Hibernate such as caching strategies will be talked about.

                                                                                                                              return to topics

Hibernate Annotation - work in progress


                                                                                                                              return to topics

Hibernate Best Practices - work in progress


                                                                                                                              return to topics






Spring Framework




Refactoring HelloWorld Application using Spring Framework


You are going to learn how to refactor the good old "HelloWorld" application in various ways including the usage of Dependency Injection (DI) scheme of the Spring framework.
                                                                                                                              return to topics

Spring Framework Dependency Injection Basics


Dependency Injection (DI) is the one of the foundation of the Spring framework.  You are going to learn how to use the basic usage of DI in this session.

                                                                                                                              return to topics

Spring Framework Dependency Injection Advanced


                                                                                                                              return to topics

Spring framework and Hibernate


                                                                                                                              return to topics


Spring framework and JPA


                                                                                                                              return to topics


Spring MVC


                                                                                                                              return to topics

Spring Validation, Data-binding, BeanWrapper, and Property Editor


  • Presentation
    • PDF: 1 slide per page
    • StarOffice 8 file
  • Lab
    • 4918_springmvc.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/springmvc/index.html to proceed)
    • Online lab document (This is the same document you will find in the hands-on lab zip file)
    • Homework
    • Change log
  • Resources
                                                                                                                              return to topics

Spring Web Flow


Spring Web Flow is a next generation Java web application framework that allows developers to model user actions as high-level modules called flows that are runnable in any environment.  The framework delivers improved productivity and testability while providing a strong solution to enforcing navigation rules and managing application state. 
                                                                                                                              return to topics

Spring Integration with Struts


                                                                                                                              return to topics

Spring Integration with JavaServer Faces (JSF)


                                                                                                                              return to topics

Spring AOP Basics


                                                                                                                              return to topics


Spring framework and J2EE (EJB and JMS)


                                                                                                                              return to topics

Spring framework and Web Services


                                                                                                                              return to topics

Spring framework and Transaction


                                                                                                                              return to topics

Spring and Testing


                                                                                                                              return to topics

Spring framework sample applications - PetClinic


  • Presentation
    • PDF: 1 slide per page
    • StarOffice 8 file
  • Lab
                                                                                                                              return to topics


Advanced Spring Framework


                                                                                                                              return to topics

Acegi Security with Spring framework


                                                                                                                              return to topics





Portlets and Portals




Portlet Basics -



                                                                                                                              return to topics






Struts 2




Struts 2 Basics


                                                                                                                              return to topics

Struts 2 and Other View Technologies


  • Presentation
    • PDF: 1 slide per page
    • StarOffice 8 file
  • Lab
    • 4221_struts2basics.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/struts2basics/index.html to proceed)
    • Online lab document (This is the same document you will find in the hands-on lab zip file)
    • Homework
    • Change log
  • Resources
                                                                                                                              return to topics

Struts 2 and Ajax


  • Presentation
    • PDF: 1 slide per page
    • StarOffice 8 file
  • Lab
    • 4221_struts2basics.zip (Unzip it in a directory of your choice and read lab document from <unzip-directory>/struts2basics/index.html to proceed)
    • Online lab document (This is the same document you will find in the hands-on lab zip file)
    • Homework
    • Change log
  • Resources
                                                                                                                              return to topics

Sun Provisioning Server (SPS)


                                                                                                                              return to topics






GlassFish




GlassFish Overview


1. Presentation slides (1 hour)

2. Presentation slides 2

This is from JavaOne 2006 presentation.  You have to register to Sun Developer Network in order to watche the video.

3. Labs
  • Building GlassFish using Netbeans tutorial from netbeans.org

                                                                                                                              return to topics


GlassFish V3



                                                                                                                              return to topics

SailFin Project



Posted by 1010
05.JSP2009. 1. 23. 15:10
반응형

먼저 다음 페이지 이동 특성들을 미리 알아볼 필요가 있습니다

JSP에서는 페이지 이동시 다음 4가지 정도의 방법이 있습니다


JavaScript를 이용

window.open, location.href, location.replace 등을 이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

      <script>location.href = "admin.jsp"; </script>

<% } else { %>

      <script>alert('권한이 없어요!'); window.history.back(); </script>

<% } %>

         

특징적인부분은 브라우져의 주소창이 변경되며

(이말은 즉슨 클라이언트가 다시 admin.jsp를 서버에 요청한다는 말입니다)

login_process.jsp 에서 jsp가 다 실행되고 브라우져에 out put된 html 및 javascript들만으로

실행된 코드들이라는 것입니다


response.sendRedirect를 이용

login_process.jsp

<% if (a == null) {

          response.sendRedirect("admin.jsp");

     } else {

          response.sendRedirect("login.jsp");

     }


     a = "test 입니다";

     System.out.println(a);

%>


이 코드에서 a가 출력될까요 안될까요?

출력 됩니다.

sendRedirect가 되더라도 밑에 jsp 코드들은 모두 실행 된다는 말입니다

response.sendRedirect는 기본적으로 모든 로직들을 다 처리한 후 코드 맨 마지막 부분에

사용하는 것이 올바른 방법입니다

만약 그렇지 못한 경우는 response.sendRedirect 다음 바로 return; 이라는 코드를 집어 넣어야 합니다


response.sendRedirect은 HTTP 헤더정보를 변경하여 redirect시키기 때문에 역시 브라우져의 주소창이 변경되며 sendRedirect가 실행되기전 html이나 javascript로 out put되는 코드들은 모두 실행되지 않습니다.


forward 이용

jsp 태그의 <jsp:forward> 나 servlet의 RequestDispatcher.forward 를 이용할수 있습니다


login_process.jsp

<% if (a == null) { %>

          <jsp:forward page="admin.jsp"/>

<% } else { %>

          <jsp:forward page="login.jsp"/>

<% }


     a = "test 입니다";

     System.out.println(a);

%>


그럼 위의 코드의 경우 a가 출력 될까요 안될까요?

정답은 출력 안됩니다. 바로 forward 되어 버립니다.

클라이언트로 응답주지 않고 바로 서버측에서 admin.jsp로 이동하기 때문에

주소창이 바뀌지 않고 그로인해 브라우져에 출력되는 응답속도 또한 사용자가 보기에는

응답이 빠른 장점이 있습니다


하지만 forward 이후 JSP 코드들이 실행되지 않는것 사실이지만 만약 finally절이 있는경우

finally절은 실행 됨으로 확실히 알아둡시다.


meta 태그 이용

마지막으로 meta 태그를 이용할 수도 있습니다.


<META http-equiv=refresh content="0;url=admin.jsp">


즉 요약하자면..

페이지 이동 방법이 여러가지가 있습니다.

그 특성들을 잘 알고 올바르게 사용하여야 합니다.

Posted by 1010
05.JSP2009. 1. 22. 17:32
반응형

새로운 JSTL1.1 태그 라이브러리 지정자

JSTL1.1은 JSTL을 JSP2.0에 통합하기 위한 마이너 스펙 릴리즈이다. 눈에 띄는 변화는 JSTL1.0의 두개로 분리되었던 라이브러리가 EL과 JAVA표현식 모두를 사용할 수 있는 한가지 라이브러리로 통합된 것이다.
JSTL의 라이브러리들은 다음과 같은 지정자를 사용한다.

Library URI Prefix
Core http://java.sun.com/jsp/jstl/core C
XML precessiog http://java.sun.com/jsp/jstl/xml x
l18N formatting http://java.sun.com/jsp/jstl/fmt fmt
Database access http://java.sun.com/jsp/jstl/sql sql
Function http://java.sun.com/jsp/jstl/function fn

EF Function

함수명 함수설명
fn:contains(string, sbustring) string이 substring을 포함하면 return True
fn:containsIgnoreCase(string, sbustring) 대소문자 관계없이 string이 substring을 포함하면 return True
fn:endsWith(string, suffix) string이 suffix로 끝나면 return True
fn:escapeXml(string) stting에 XML과 HTML에서 특별한 의미를 가진 문자들이 있으면, XML엔티티 코드로 바꿔준뒤 문자열 반환
fn:indexOf(string, sbustring) string에서 substring이 처음으로 나타나는 인덱스 반환
fn:join(array, separator) array요소들을 separator를 구분자로 하여 연결해서 반환
fn:length(item) item이 배열이나 컬렉션이면 요소의 객수를 문자열이면 문자의 객수를 반환
fn:replace(string, before, after) string내에 있는 before 문자열을 after 문자열로 모두 변경해서 반환
fn:split(string, separator) string내의 문자열 separetor에 따라 나누어서 배열로 구성해서 반환
fn:startsWith(string, prefix) string이 prefix로 시작하면 return True
fn:substring(string, begin, end) string에서 begin인덱스에서 시작해서 end인덱스에 끝나는 부분의 문자열 반환
fn:substringAfter(string, sbustring) string에서 substring이 나타나는 이후의 문자열 반환
fn:substringBefore(string, sbustring) string에서 substring이 나타나는 이전의 문자열 반환
fn:toLowerCase(string) string을 모두 소문자로 바꿔 리턴
fn:toUpperCase(string) string을 모두 대문자로 바꿔 리턴
fn:trim(string) string앞뒤의 공백을 모두 제거하여 반환

함수테스트 JSP 소스

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 


<!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>JSP Page</title>
    </head>
    <body>

    <h1>EL Function(JSTL1.1)</h1>

    <c:set var="name" value="Oracle dbms 오라클클럽"/>
    <c:set var="name" value="${fn:trim(name)}"/><br/>
    <c:out value="name: ${name}"/><br/><br/>

    <c:out value="length(name): ${fn:length(name)}"/><br/>
    <c:out value="toUpperCase(name): ${fn:toUpperCase(name)}"/><br/>
    <c:out value="toLowerCase(name): ${fn:toLowerCase(name)}"/><br/>
    <c:out value="substring(name,3,6): ${fn:substring(name,3,6)}"/><br/>
    <c:out value="substringBefore(name,'dbms'): ${fn:substringBefore(name, 'dbms')}"/><br/>
    <c:out value="substringAfter(name,'dbms'): ${fn:substringAfter(name, 'dbms')}"/><br/>
    <c:out value="replace(name, '오라클클럽', 'Korea'): ${fn:replace(name, '오라클클럽', 'Korea')}"/><br/>
    <c:out value="indexOf(name, 'dbms'): ${fn:indexOf(name,'dbms')}"/><br/>
    <c:out value="contains(name, 'Oracle'): ${fn:contains(name, 'Oracle')}"/><br/>
    <c:out value="containsIgnoreCase(name, 'opracle'): ${fn:containsIgnoreCase(name, 'oracle')}"/><br/>
    <c:out value="startsWith(name, 'Oracle'): ${fn:startsWith(name, 'Oracle')}"/><br/>
    <c:out value="startsWith(name, 'dbms'): ${fn:startsWith(name, 'dbms')}"/><br/>
    <c:out value="endsWith(name, '오라클클럽'): ${fn:endsWith(name, '오라클클럽')}"/><br/><br/>
    <c:remove var="name"/>

    <c:out value="=================================================================="/><br/><br/>

    <c:set var="db" value="ORACLE, DB2, MSSQL, MYSQL, SYSBASE"/>
    <c:set var="db_arr" value="${fn:split(db,',')}"/>
    <c:forEach var="x" items="${db_arr}">
        <c:out value="${x}"/><br/>
    </c:forEach>
    <c:out value="${fn:join(db_arr, ',')}"/><br/>

   </body>
</html>

문서에 대하여

Posted by 1010
05.JSP2009. 1. 22. 15:21
반응형

1. 개요

  • JSP에서는 사용자가 태그를 정의해서 사용하는 것이 가능(Custom Tag)
  • Custom Tag중 자주 사용하는 것을 표준화 시켜 놓은 것을 JSTL
  • 작업을 수행하는 코드들을 태그로 간략화

2. JSTL을 사용하기위한 환경 설정

  1) http://jakarta.apache.org → downloads → Taglibs → standard 1.1 Taglib → 1.1.2.zip을 클릭하여 다운로드
  2) 압축을 풀어 jstl.jar, standard.jar 두 개의 파일을 톰캣홈\webapps\study\WEB-INF\lib폴더에 복사


3. JSTL 1.1 라이브러리


라이브러리

URI

Prefix

(접두어)

예시

Core

http://java.sun.com/jsp/jstl/core

c

<c:tagname...

XML processing

http://java.sun.com/jsp/jstl/xml

x

<x:tagname..>

I18N capable formatting

http://java.sun.com/jsp/jstl/fmt

fmt

<fmt:tagname..>

Database access(SQL)

http://java.sun.com/jsp/jstl/sql

sql

<sql:tagname..>

Functions(함수)

http://java.sun.com/jsp/jstl/functions

fn

fn:functionName(....)

4. JSTL 1.1 라이브러리

1) JSTL Core

  • 변수 선언, 삭제 등 변수와 관련된 작업
  • if문, for문 등과 같은 제어문, 그리고 URL 처리등에 사용
  1. <%@ taglib %> 디렉티브

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

p649


    *** 태그

(1) <c:set>
  • JSP의 setAttribute와 같은 역할
  • 변수 설정

  1. <c:set var="varName" value="value" target="targetObjectName" property="propertyName" scope="{page|request|session|application}"/>
  2.   var : 변수명
      value : 변수 값
      target : 자바빈 객체명,Map 객체명
      property : property 명
      scope : 공유범위

      예1) <c:set var="abc" value=${20}>  변수 abc에 값 20을 설정

      예2) <c:set value="20" target="kkk" property="age"}

             객체 kkk의 property  age의 값에 20을 설정


(2) <c:out>
  • JSP의 표현식을 대체
  • 화면에 해당 변수값을 출력

  1. <c:out var="varName" default="defaultValue" escapeXml="{true|false}"/>
            var : 변수명
            default : 기본값
            escapeXml : true로 설정시(기본값) < > & ‘ “ 문자들을 각각 &lt;&gt;&amp;&#039;&#034;로 출력

    예1) <c:out value="${abc}"/> 변수 abc 값을 출력


(3) <c:remove>태그
  • JSP의 removeAttribute()와 같은 역할을 한다.
  1. <c:remove var="varName" scope="{page|request|session|application}"/>
          var: 변수명
          scope : 변수의 공유 범위

예1) <c:remove var="abc"/> 변수abc의 값을 제거

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
     <title>JSTL core 예제 - set, out, remove</title>
    </head>
    <body>
  2.  browser변수값 설정
      <c:set var="browser" value="${header['User-Agent']}"/><br>
      <c:out value="${browser}"/><p>
     browser변수값 제거 후
      <c:remove var="browser"/>
      <c:out value="${browser}"/>
    </body>
    </html>

(실습1) 수량과 단가 기억장소에 data를 기억한 후 금액을 출력하는 프로그램 작성
    금액 = 수량 * 단가



(실습2) 이름과 국어,영어, 수학 점수를 폼에서 입력 받아서
EL과 JSTL을 이용하여 다음과 같이 출력


xxx님의 총점은 xxx이고 평균은 xxx입니다.


(4) <c:catch>
  • body위치에서 실행되는 코드의 예외를 잡아내는 역할
  1. <c:catch var="errMag"/>

        var : 에러가 발생하면 변수에 에러메세지가 들어간다


(5) <c:if>
  • 조건문
  1. <c:if test="condition" var="varName" scope="{page|request|session|application}"/>

       test : 조건 판별식
       var : 변수명
       scope : 변수의 공유범위


     예)

  1. <c:if test="${country=='korea'}">
        This customer is based in korea.
    </c:if>

country 변수값이 'korea'이면 밑의 문장 출력


(6) <c:choose>(<c:when>,<c:otherwise>)태그
  • switch문과 비슷, 조건에서 문자열 비교가 가능
  1. <c:choose>
      <c:when test="조건>body 내용</c:when>
      <c:otherwise>body의 내용</c:otherwise>
    </c:choose>

 예)

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <title>JSTL core 예제 - if, choose, when, otherwise</title>
    </head>
    <body>
    <c:set var="country" value="${'Korea'}"/>
    <c:if test="${country != null}">
      국가명: <c:out value="${country}"/>
    </c:if>
    <p>
    <c:choose>
      <c:when test="${country == 'Korea'}">
         <c:out value="${country}"/>의 겨울은 춥다.
      </c:when>
      <c:when test="${country == 'Canada'}">
         <c:out value="${country}"/>의 겨울은 너무 춥다.
      </c:when>
      <c:otherwise>
         그외의 나라들의 겨울은 알 수 없다.
      </c:otherwise>
    </c:choose>
    </body>
    </html>

(실습1) <c:if> 사용
변수에 수를 기억시키고
 기억된값이 0보다 크면 ‘양수입니다’
                 0이면 ‘0입니다’
                 0보다 작으면 ‘음수입니다’ 출력


(실습2) <c:choose>이용
변수에 이름과 점수를 기억시킨 후 점수에 따라 수우미양가 출력
  (예: 90점 이상 100점 이하이면 수)


(7) <c:forEach>
  • 객체 전체에 걸쳐 반복 실행할 때 사용
  1. <c:forEach items="items" begin="begin" end="end" step="step" var="varName" varStatus="varStatus"/>

      items : 반복할 객체명
      begin : 시작값
      end : 마지막 값
      step : 증가값
      var : 변수명
      varStatus : 변수 상태(index값이나 count값 출력)


예1) 0,2,4,6,8 출력

  1. <%@ page contentType="text/html;charset=euc-kr"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <c:forEach var="i" begin="0" end="9" step="2">
    ${i}<br>
    </c:forEach>

예2) 1에서 100까지 숫자 중에서 짝수 만 출력

  1. <%@ page contentType="text/html;charset=euc-kr"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <c:forEach var="k" begin="1" end="100">
       <c:if test="${k % 3 == 0}">
         ${k }<br>
       </c:if>
    </c:forEach>

 ** 객체에서 반복하여 값을 출력

  1. <c:forEach var="customer" items = "${customers}">
      Customer : <c:out value="${customer}"/>
    </c:forEach>

*** 예

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
      <title>JSTL core 예제 - forEach</title>
    </head>
    <body>
    <h3>Header 정보:</h3>
    <c:forEach var="head" items="${headerValues}" varStatus="status">
      param: <c:out value="${head.key}"/>
      <c:out value="${status.index}"/>  // index 값 출력
      <c:out value="${status.count}"/>  // 요소의 수를 출력
      <br>
      values:
       <c:forEach var="val" items="${head.value}">
         <c:out value="${val}"/>
       </c:forEach>
       <p>
    </c:forEach>
    </body>
    </html>

(8) <c:forTokens>
  • 자바의 StringTokenizer클래스를 사용하는 것
  1. <c:forTokens items="condition" delims="delimiter" begin="begin" end="end" step="step" var="varName" varStatus="varStatus"/>

    items : 객체명
    delims : 구분자
    begin : 시작값
    end : 마지막 값
    step : 증가값
    var : 변수명
    varStatus : 변수 상태


 *** 예

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
      <title>JSTL core 예제 - forTokens</title>
    </head>
    <body>
      <c:forTokens var="car" items="Sprinter Trueno AE86,
  2. RX-7 Savanna FC3S,
  3. Lancer Evolution III,
  4. RX-7 Efini FD3S" delims=",">
  5.    자동차 이름: <c:out value="${car}"/><br>
      </c:forTokens>
    </body>
    </html>

(9) <c:import>
  • 자원 import

  1. <c:import url="url" var="varName" scope="{page|request|session|application}" varReader="varReader" charEncoding="charEncoding"/>

       url : 읽어올 url
       var : 변수명
       scope : 변수의 공유 범위
       varReader : 리소스의 내용을 Reader 객체로 읽어올 때 사용
       charEncoding : 읽어온 데이터의 캐릭터 셋지정


    예)

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <c:import url="/ch07/date.jsp" var="url" />
    <html>
    <head><title>JSTL core 예제 - import</title></head>
    <body>
      ${url}
    </body>
    </html>

**date.jsp

  1. <%@ page contentType="text/html; charset=euc-kr" %>
    <%@ page import="java.util.*, java.text.*" %>
    <%@ page errorPage="err.jsp"%>
    <html>
      <body>
       <%
          Date date = new Date();
          SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
          String strdate = simpleDate.format(date);
       %>
       보통의 JSP 페이지의 형태입니다.<br>
       오늘 날짜는 <%= strdate%> 입니다.
      </body>
    </html>

(10) <c:redirect>
  • response.Redirect()를 대체하는 태그
  1. <c:redirect url="url"/>

     url : 이동할 URL


(11) <c:url>
  • 쿼리 파라미터로부터 URL 생성
  1. <c:url var="varName" value="value" scope="{page|request|session|application}"/>

   예1)

  1. <c:url value="/customers/register" var="registrationURL">
      <c:param name="name" value="${param.name}"/>
      <c:param name="country" value="${param.country}"/>
    </c:url>

 /customers/register?name=xxxx&country=xxxx의 값이 변수 registrationURL에 기억


2) JSTL XML

  • XML을 처리해 주기 위한 것
  • XML 출력, 흐름 제어, XML 변환등의 작업
  •  디렉티브 작성
  1. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/js시/xml" %>
  • 태그 : p665

3) JSTL fmt

  • JSTL 국제화, 지역화 태그로 다국어 문서를 처리할 때 유용
  • 날짜와 숫자 형식을 다룰 때 사용
  • 디렉티브 작성
  1. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  • 태그 p667

(1) <fmt:setLocale>태그
  • 다국어 지원페이지를 만들 때 사용
  • ResourceBundle로 불러오는 *.properties 파일들과 연계하여 사용

  1. <fmt:setLocale value="locale" variant="variant" [scope="{page|request|session|application}"]/>

       value : 두 글자로 된 언어 코드를 반드시 지정
                 한글의 경우 ko_kr
       variant : 브라우저 스펙 기술
       scope : 변수의 공유 범우;


   예)

  1. <fmt:setLocale value="ko" />

(2)<fmt:requestEncoding>
  • request.setCharcterEncoding()

  1. <fmt:requestEncoding value="charsetName"/>

        value : 인코딩 값

     예)

  1. <fmt:requestEncoding value="euc-kr"/>
    <%@ page contentType="text/html; charset=EUC-KR"
        pageEncoding="EUC-KR"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
    <fmt:requestEncoding value="euc-kr"/>
    <html>
    <head>
    <title>Insert title here</title>
    </head>
    <body>
    파라미터 :<c:out value="${param.id}"/>
    <form method="post" action="jstlEx6.jsp">
       <input type="text" name=id>
       <input type="submit" value="확인">
    </form>  
    </body>
    </html>

(3) <fmt:bundle>
  •   properties 확장자를 이용하여 자원 파일을 읽어오는 역할
  1. <fmt:bundle basename="basename" prefix="prefix">
    body의 내용
    </fmt>

          basename : properties 파일명
             WEB-INF/classes에 보통위치(패키지 형식의 이름 가질 수 있음)
             bundle 폴더안에 testBundle.properties의 경우 : bundle.testBundle
             로케일이 ko일 경우 : testBundle_ko.properties 파일을 읽어온다
             prefix 속성 : key이름


        ☞ properties의 내용을 한글로 입력할 수 없으므로 유니코드로 변환하여 입력

            (변환 프로그램 : native2ascii.exe) - 자바홈\bin


(4)<fmt:message>
  • 번들 태그에서 정한 값을 가져온다

  1. <fmt:message key="messageKey" bundle="resourceBundle" var="varName"
    scope="{page|request|session|application}" />

         key : 읽어올 메시지의 key 값 기술
         bundle : setBundle 태그를 이용하여 로딩한 번들을 읽어올 때 사용
         var : 메시지를 저장할 변수명
         scope : 변수 공유범위 지정


      예)

  1. <fmt:message key="message" var="msg"/>

         message에 해당하는 값을 .properties 파일로부터 읽어와 msg 변수에 저장

     (예제)

① classes 폴더에 bundle 폴더 생성

         testBundle_ko.properties 파일 생성
         name=\uc0ad\ub791\ud574\uc694
         message=JSTL \ub108\ubb34 \uc88b\uc544


         testBundle.properties 파일 생성

         name=I love you.
         message=JSTL very good


② jstlEx7.jsp
  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"  %>
    <fmt:bundle basename="bundle.testBundle">
    <html>
    <head><title>JSTL fmt 예제 - bundle , message</title></head>
    <body>
    <fmt:message key="name"/>
    <p>
    <fmt:message key="message" var="msg"/>
    <c:out value="${msg}"/>
    </fmt:bundle>
    </body>
    </html>

(5) <fmt:setBundle>
  • 페이지 전체에서 사용할 수 있는 번들을 지정
  1. <fmt:setBundle basename="basename" var="varName" scope="{page|request|session|application}" />

         basename : properties 파일명
         var : 변수명
         scope : 변수 공유 범위


(6) <fmt:formatNumber>
  • 숫자 형식을 지정

  1. <fmt:formatNumber value="numericValue" type="{number|currency|percent}"
    pattern="customPattern" currencyCode="currencyCode" currencySymbol="currencySymbol" groupingUsed="{true|false}" maxIntegerDigits="maxIntegerDigits" minIntegerDigits="minIntegerDigits" maxFractionDigits="maxFractionDigits" minFrationDigits="minFractionDigits" var="varName" scope="{page|request|session|application}" />

        value : Number로 형식화될 수치
        type : 숫자, 통화,퍼센트
        pattern : 사용자가 지정한 패턴 형식 지정
        currencyCode : ISO 4217 통화 코드 지정
        currencySymbol : 통화기호 지정
        groupingUsed : 출력에 그룹 분리 기호를 포함할지 여부 지정
        maxIntegerDigits : 출력에서 integer 최대 자릿수 지정
        minIntegerDigits : 출력에서 integer 최소 자릿수 지정
        maxFractionDigits : 출력에서 소숫점 이하 최대 자릿수 지정
        minFractionDigits : 출력에서 소숫점 이하 최소 자릿수 지정
        var : 출력 결과 문자열을 담는 scope에 해당하는 변수명 지정
        scope : 변수의 공유범위 지정


(7) <fmt:parseNumber>
  • 문자열에서 수치로 파싱한다.
  1. <fmt:parseNumber value="numericValue" type="{number|currency|percent}" pattern="customPattern" parseLocale="parseLocale" integerOnly="{true|false}" var="varName" scope="{page|request|session|application}" />

      value : 수치지정
      type : 숫자, 통화,퍼센트
      pattern : 사용자가 지정한 패턴 형식 지정
      parseLocale : Locale 지정
      integerOnly : 주어진 값에서 integer 부분만 파싱할 지 여부 지정
      var : 변수명 지정
      scope : 변수 공유범위 지정


(8) <fmt:formatDate>

       + 날짜 형식을 표현할 때 사용


  1. <fmt:formatDate vaue="date" type="{time|date|both}" dateStyle="{default|short|medium|long|full}" timeStyle="{default|short|medium|long|full}" pattern="customPattern" timeZone="timeZone" var="varName" scope="{page|request|session|application}"/>

        value : Data와 time 지정
        type : 형식 지정
        dateStyle : 날짜 style 지정
        timeStyle : 시간 style 지정
        pattern : 사용자가 지정한 패턴 형식 지정
        timeZone : java.util.TimeZone 형식으로 된 시간에 나타날 타임 존 지정
        var : 변수명
        scope : 변수 공유범위


(9) <fmt:parseDate>
  • 문자열에서 날짜로 파싱할 때 사용
  1. <fmt:parseDate value="dateString" type="{time|date|both}" dateStyle="{default|short|medium|long|full}" timeStyle="{default|short|medium|long|full}" pattern="customPattern" timeZone="timeZone" parseLocale="parseLocale" var="varName" scope="{page|request|session|application}"/>

        value : Data와 time 지정
        type : 형식 지정
        dateStyle : 날짜 style 지정
        timeStyle : 시간 style 지정
        pattern : 사용자가 지정한 패턴 형식 지정
        timeZone : java.util.TimeZone 형식으로 된 시간에 나타날 타임 존 지정
        var : 변수명
        scope : 변수 공유범위


   예)

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head><title>JSTL fmt 예제 - formatNumber, formatDate</title></head>
    <body>
    number  : <fmt:formatNumber value="12345.678" type="number"/><br>
    currency: <fmt:formatNumber value="12345.678" type="currency" currencySymbol="₩"/><br>
    percent : <fmt:formatNumber value="12345.678" type="percent"/><br>
    pattern=".0" :<fmt:formatNumber value="12345.678" pattern=".0"/> <p>
    <c:set var="now" value="<%= new java.util.Date() %>" />
    <c:out value="${now}"/><br>
    date : <fmt:formatDate value="${now}" type="date" /> <br>
    time : <fmt:formatDate value="${now}" type="time" /> <br>
    both : <fmt:formatDate value="${now}" type="both" />
    </body>
    </html>

  1. number : 12,345.678
    currency: ₩12,345.68
    percent : 1,234,568%
    pattern=".0" :12345.7
    Mon Dec 29 10:03:27 KST 2008
    date : Dec 29, 2008
    time : 10:03:27 AM
    both : Dec 29, 2008 10:03:27 AM
(10) <fmt:setTimeZone>,<fmt:timezone>

    + 시간대 설정


  1. <fmt:setTimeZone value="timeZone" var="varName"
    scope="{page|request|session|application}"/>

      - value : 설정한 시간대 지정
      - var : 변수
      - scope : 변수 공유범위


   예)

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head><title>JSTL fmt 예제 - timeZone</title></head>
    <body>
    <c:set var="now" value="<%= new java.util.Date() %>" />
    Korea   KST  : <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/><br>
    UK   GMT  : <fmt:timeZone value="GMT">
                      <fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
                   </fmt:timeZone>
    </body>
    </html>

4) JSTL sql

  • DataSource를 이용해서 SQL를 처리하는 작업 등에 사용
  1. <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

태그

     transaction  : 트랜젝션 구현
     query : executeQuery()와 같은 기능
     update " executeUpdate()와 같은 기능
     param : java.sql.PreparedStatement.setString()의 역할
     dateParam : java.sql.PreparedStatement.setTimestamp() 역할
     setDataSource : DataSource 지정


(1)<sql:setDataSource>
  • DataSource 지정
  1. <sql:setDataSource {dataSource="dataSource"  |url="jdbcUrl" driver="driverClassName" user="userName" password="password" } var="varName" scope="{page|request|session|application}"/>

     url : JDBC url
     dataSource : 컨텍스트에 JNDI설정 시 리소스 네임
     driver : JDBC driver
     user : 사용자
     password : 패스워드
     var : 변수
     scope : 변수의 공용범위


 예) 표준 드라이버 사용

  1. <sql:setDataSource url="jdbc:oracle:thin:@localhost:1521:orcl" driver="oracle.jdbc.driver.OracleDriver" user="kkk" password="1234" var="ds" scope="application" />

 예) 기존의 dataSource를 불러와 사용하는 경우

  1. <sql:setDataSource dataSource="jdbc/myoracle" var="ds" scope="application" />

  dataSource : server.xml에서 정의한 <Resource> 태그의 name 속성의 값이 들어간다.


  예) 컨텍스트에 JNDI가 설정되어 있는 겨우

  1. <sql:query var="rs" dataSource="jdbc/myoracle">

(2)  <sql:query>
  • sql 태그의 속성 또는 body에 정의된 SQL  쿼리 문장을 실

① 속성에 sql 쿼리 문장을 기술한 경우
  1. <sql:query sql="sqlQuery" var="varName" scope="{page|request|session|application}" dataSource="dataSource" maxRows="maxRows" startRow="startRow" />

② 속성에 sql 쿼리문장을 기술하고 쿼리의 파라미터가 body에 있는 경우
  1. <sql:query sql="sqlQuery" var="varName" scope="{page|request|session|application}" dataSource="dataSource" maxRows="maxRows" startRow="startRow" />
    <sql:param>태그들
    </sql:query>

③ body에 sql 쿼리 문장과 파라미터를 기술한 경우
  1. <sql:query  var="varName" scope="{page|request|session|application}" dataSource="dataSource" maxRows="maxRows" startRow="startRow" />
    SQL 쿼리 문장
    <sql:param>태그들
    </sql:query>

   sql : sql 쿼리 문장
   var : 쿼리의 결과 저장
   scope : 변수 공용범위
   dataSource : JNDI의 리소스 네임 또는 DriverManger를 위한 파라미터
   maxRows : 쿼리 결과에 포함될 최대 행의 수
   startRow : 쿼리 결과에 포함될 시작 행 번호


  예제)

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <html>
    <head><title>JSTL sql 예제 - query</title></head>
    <body>
    <sql:query var="rs"  dataSource="jdbc/myoracle">
        select * from member
    </sql:query>
    <table border="1">
      <tr><%--필드명  출력--%>
        <c:forEach var="columnName" items="${rs.columnNames}">
          <th><c:out value="${columnName}"/></th>
        </c:forEach>
      </tr>
      <c:forEach var="row" items="${rs.rowsByIndex}"><%-- 레코드의 수 만큼 반복한다.[][] --%>
      <tr>
        <c:forEach var="column" items="${row}" varStatus="i"><%-- 레코드의 필드수 만큼 반복한다.[] --%>
       <td>
           <c:if test="${column!=null}"> <%--해당 필드값이 null이 아니면--%>
                <c:out value="${column}"/>
           </c:if> <%--해당 필드값이 null이면--%>
           <c:if test="${column==null}">
                &nbsp;
           </c:if>
        </td>
        </c:forEach>
      </tr>
       </c:forEach>
    </table>
    </body>
    </html>

(3)<sql:dateParam>
  • 날짜 형식
  • java.sql.PreparedStatement.setTimestamp() 역할
  1. <sql:dateParam value="value" type="{timestamp|time|date}"}/>

         value : 파라미터 값
         type : 형식 설정


(4) <sql:param>
  • 문자열 형식
  • java.sql.PreparedStatement.setString()의 역할
  1.  <sql:param value="value"/>

(5) <sql:update>
  • sql 태그의 속성 또는 body에 정의된 sql 쿼리 문장을 실행
  •  executeUpdate()와 같은 기능
① 속성에 sql 쿼리 문장을 넣는 경우
  1. <sql:update sql="sqlUpdate" dataSource="dataSource" var="varName" scope="{page|request|session|application}"/>

② 속성에 쿼리 문장을 기술하고 쿼리의 파라미터가 body에 있는겨우
  1. <sql:update sql="sqlUpdate" dataSource="dataSource" var="varName" scope="{page|request|session|application}">
    <sql:param>태그들
    </sql:update>

③body에 sql 쿼리 문장과 파라미터들을 기술하는 경우
  1. <sql:update  dataSource="dataSource" var="varName" scope="{page|request|session|application}">
    sql 쿼리 문장
    <sql:param>태그들
    </sql:update>

    sql : sql 문장
    var : 쿼리 결과를 저장
    scope : 변수의 공유 범위
    dataSource : JNDI의 리소스 네임 또는 DriverManager를 위한 파라미터 네임


  예제)update

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <html>
    <head><title>JSTL sql 예제 - update, param</title></head>
    <body>
    <sql:update dataSource="jdbc/myoracle">
        update member set passwd=? where id= ?
        <sql:param value="${3456}"/>
        <sql:param value="${'abc'}"/>    
    </sql:update>
    <sql:query var="rs"  dataSource="jdbc/myoracle">
        select * from member
    </sql:query>
    <table border="1">
      <tr><%--필드명  출력--%>
        <c:forEach var="columnName" items="${rs.columnNames}">
          <th><c:out value="${columnName}"/></th>
        </c:forEach>
      </tr>
      <c:forEach var="row" items="${rs.rowsByIndex}"><%-- 레코드의 수 만큼 반복한다. --%>
      <tr>
        <c:forEach var="column" items="${row}" varStatus="i"><%-- 레코드의 필드수 만큼 반복한다. --%>
       <td>
           <c:if test="${column!=null}"> <%--해당 필드값이 null이 아니면--%>
                <c:out value="${column}"/>
           </c:if> <%--해당 필드값이 null이면--%>
           <c:if test="${column==null}">
                &nbsp;
           </c:if>
        </td>
        </c:forEach>
      </tr>
       </c:forEach>
    </table>
    </body>
    </html>

(6) <sql:transaction>
  • 트랜잭션을 구할 때 사용
  1. <sql:transaction dataSource="dataSource" isolation="isolationLevel">
    <sql:query> 태그
    <sql:update>태그
    .....
    </sql:transaction>

dataSource : JNDI의 리소스 네임 또는 DriverManager를 위한 파라미터 네임
   isolation : java.sql.Connection의 setTransactionIsolation()메소드 사용
                 "read_committed","read_uncommitted","repeatable_read","serializable" 중 하나를 사용


 (실습)

id,비밀번호,이름,등록일
폼에서 데이터 입력 후
jstl을 이용하여 DB에 데이터 입력 ,비밀번호 ‘3456’으로 변경하여 출력하는 프로그램 작성





5) JSTL functions

  • JSTL에서 제공하는 각종 함수를 사용해서 문자열이나 콜렉션들을 처리
  1. <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/js시/functions" %>
  • 태그(p692)

 (1)예

  1. <%@ page contentType = "text/html; charset=euc-kr" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <html>
    <body>
      <c:set var="name" value="  Jsp 세계  "/>
      <c:set var="name" value="${fn:trim(name)}"/>
      <br/><c:out value="name: ${name}"/><br/><br/>
      <c:out value="length(name): ${fn:length(name)}"/><br/>
    </body>
    </html>

Posted by 1010
05.JSP2009. 1. 20. 19:02
반응형


<form action=\"http://phpschool.com\" onSubmit=\"this.submit.disabled=true\">
<input type=\"text\" name=\"test\">
<input name=\"submit\" type=\"submit\" value=\"전송\">
</form>
이렇게 해야겠네요 : )
Jun// type=image일때는 조금 다르게 동작하는거같습니다
그래도 disabled 속성은 있으니
<input type=\"image\" onClick=\"this.form.submit();this.disabled=true\" value=\"전송\">

====================================================================
IE6에선 확인할수 없지만.

일단 IE7에선 아래 처럼 적용.
<input type="submit" value=" 저장 " onClick="this.form.submit();this.disabled=true"/>
Posted by 1010