- http://gitref.org/ Good and short intro got GIT.
- http://hoth.entp.com/output/
git_for_designers.html Alternate intro if you find 1. above too not clear enough. - http://eagain.net/articles/
git-for-computer-scientists/ More advanced intro. - http://progit.org/book/ch1-3.
html GIT Basics - http://blip.tv/scott-chacon/
c1-init-4113470. You can follow this video to create a GIT repository locally as a sandbox to learning GIT in a safe environment. - http://blip.tv/scott-chacon/
c2-normal-workflow-4113486 - http://blip.tv/scott-chacon/
c3-add-interactive-4113507 - http://blip.tv/scott-chacon/
c4-git-log-4113548 - http://blip.tv/scott-chacon/
c5-git-browsing-4113562 - http://blip.tv/scott-chacon/
c6-branch-merge-4113582 - http://blip.tv/scott-chacon/
c7-rebase-4113602 - http://blip.tv/scott-chacon/
c8-dist-workflow-4113615
Enhancing your expertise in Java, Kubernetes, Spring Boot, AWS, BTC, and ETH can significantly elevate your career prospects in the ever-evolving tech industry. Welcome to my blog, where I share insights and resources to help you master these key technologies and stay ahead of the curve. Enhance your tech skills with insights on Java, Kubernetes, Spring Boot, AWS, BTC, and ETH. Master advanced topics and stay updated with practical tips and tutorials!
Wednesday, November 02, 2011
Link for learn GIT
Monday, October 17, 2011
XSS Summary
1. Stripes will HTML escape all input tag values. This behavior bypass PopulationStrategy.
2. LocalizableError *fieldValue* will be escaped.
3. SimpleError will *not* be escaped.
4. SimpleMessage and LocalizableMessage will *not* be escaped.
For JSTL: -
1.
2. ${..} will *not* escape
3. ${fn:escapeXml(...)} will call escapeXml function to escape the content.
Therefore: -
1. Always use
2. If you must use ${somevalue}, use ${fn:escapeXml(somevalue)}
3. All args that contain user input String value passed to MessageDisplay or ValidationErrors must be SafeHtmlUtil.HTMLEntityEncode(arg[n]).
XSS Prevention
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
Sunday, October 09, 2011
Centos install java + mysql + tomcat6
yum list mysql
yum --enablerepo=remi,remi-test install mysql mysql-server
service mysqld start
/etc/init.d/mysqld start
mysql -u root -p
mysql
mysqladmin
mysqladmin -u root password cyber123
mysql
mysql -u root -p
yum install tomcat6 tomcat6-webapps tomcat6-admin-webapps
yum install yum-priorities
rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
cd /etc/yum.repos.d/
wget http://jpackage.org/jpackage50.repo
yum install tomcat6 tomcat6-webapps tomcat6-admin-webapps
service tomcat6 start
Setting Up A Static IP Address Using The Command Line
Log on as root, change directory to /etc/sysconfig/networking/devices and list all available devices.
# cd /etc/sysconfig/networking/devices
# ls
Find the configuration file corresponding to the NIC for which you want to set a static IP and edit it.
# vi ifcfg-eth0
I prefer using “joe” as a text editor rather than “vi”. You can install “joe” by issuing “yum install joe”. To invoke joe’s help menu, type “CTRL+K, H” from within the application.
Now set the parameters below according to your settings (those in bold characters only):
DEVICE=eth0
BOOTPROTO=none
HWADDR=00:0C:29:DE:94:8B
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes
NETMASK=255.255.255.0
IPADDR=192.168.0.100
GATEWAY=192.168.0.1
Save the configuration file and exit the text editor.
To set the nameservers, change directory to /etc and edit resolv.conf.
# cd /etc
# vi resolv.conf
The file format should be like this:
search your-dns-search-path
nameserver dns1-ip-address
nameserver dns2-ip-address
nameserver dns3-ip-address
Now save the configuration file and exit the text editor. To apply changes, we need to bring the network interface down and back up.
# ifdown eth0
# ifup eth0
If you intend to do that remotely, reboot the server instead as you would be disconnected from your server after issuing the “ifdown” command.
Thursday, April 29, 2010
LOAD JSP during startup.
HomeJsp /home.jsp 1
Use Decimal(19,0) for BIGINTEGER
DB2/390 does not have a BIGINT data type. It only has a 32 bit integer. Has anyone tried to map a 64 bit integer in an entity bean to a DB2/390 data type? I'm thinking it's going to be a DECIMAL but I'm not sure. I want to get some opinions before I start experimenting.
answer:Use Decimal(19,0), this was recommended to me by an IBM DB2 AIX to Z/OS migration expert.
reference
Wednesday, April 21, 2010
The top 10 (more or less) J2EE best practices
Apply automated unit tests and test harnesses at every layer.
Develop to the specifications, not the application server.
Plan for using J2EE security from Day One.
Build what you know.
Always use Session Facades whenever you use EJB components.
Use stateless session beans instead of stateful session beans.
Use container-managed transactions.
Prefer JSPs as your first choice of presentation technology.
When using HttpSessions, store only as much state as you need for the current business transaction and no more.
In WebSphere, turn on dynamic caching and use the WebSphere servlet caching mechanism.
Prefer CMP Entity beans as a first-pass solution for O/R mapping due to the programmer productivity benefits.
http://www.ibm.com/developerworks/websphere/techjournal/0405_brown/0405_brown.html#author2
Tuesday, April 20, 2010
Session TIme out in Websphere
The list below shows the precedence from which the final HTTP Session time-out is derived.
1. Server Level Lowest level
2. Enterprise Application Overrides the Server Level if Override is selected
3. Web Application Overrides the Server and Enterprise Application settings if Override is selected
4. Application Level (web.xml) Overrides Server, Enterprise Application, and Web Application settings
5. Application Code Overrides all other settings
In conclusion, we can load session timeout from local db and overide using application code.
For more info, refer IBM support
Monday, April 12, 2010
Show full process name / path / string in Solaris using args
ps -ef | grep javain Solaris cant see all parameter pass to java. /bin/ps(default) will crop your process name.
Example
sit:ps -ef | grep java wasadmin 4170 14515 0 09:43:34 ? 1:45 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=44691 -D wasadmin 14567 1839 0 Mar 24 ? 83:40 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=39108 -X wasadmin 14466 1839 0 Mar 24 ? 104:34 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=38668 -X wasadmin 14515 1839 0 Mar 24 ? 85:00 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=38859 -X wasadmin 28302 1839 0 Mar 25 ? 96:09 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=58191 -X wasadmin 5806 1839 0 Mar 25 ? 200:20 /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=63240 -X wasa
Use defaut
/bin/argsby pass in the processID into it.
example
sit:pargs 3054 3054: /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java -Dwas.status.socket=4 4421 -D argv[0]: /opt/IBM/WebSphere/AppServer/java/bin/sparcv9/java argv[1]: -Dwas.status.socket=44421 argv[2]: -Declipse.security argv[3]: -Dosgi.install.area=/opt/IBM/WebSphere/AppServer argv[4]:
reference
http://www.davidyahalom.com/index.php/show-full-process-name-path-string-in-solaris-using-ps/
Friday, April 09, 2010
Jquery, disable input button
(function($) {
//disable download attachment when on change search criteria
$('.report-form-container :input').change(function() {
$(':input[name^=report_redirect:]').attr('disabled', true);
});
//enable download attachment when search button click.
$(':input[name^=search:]').click(function() {
$(':input[name^=report_redirect:]').attr('disabled', false);
});
Wednesday, August 19, 2009
Prevent XSS
Use
Monday, March 16, 2009
The IMPORT command isn't SQL;
The IMPORT command isn't SQL; it's a "CLP command" (which is why it
doesn't appear under the SQL reference in the InfoCenter, but in a
separate section along with other commands like CREATE DATABASE, LOAD,
etc.)
Before DB2 9, you could only execute CLP commands from the CLP (the db2
command line executable), with the exception of one or two commands.
Starting with DB2 9, you can execute many (but not all) CLP commands
via the ADMIN_CMD() [1] stored procedure, including IMPORT [2], EXPORT
[3] and LOAD [4].
However, one important thing to be aware of with ADMIN_CMD(). The
procedure runs the command *on the server*. Hence, for IMPORT, the
input data file must reside on the server (see [2]).
There's probably some "proper" JDBC method for calling stored
procedures, or I suspect you could just do:
statement.execute("CALL SYSPROC.ADMIN_CMD('IMPORT FROM
''C:/staff.xml.xsd'' OF DEL METHOD P(1) MESSAGES ''C:/messages.txt''
INSERT INTO STAFF_AS_XML (STAFF_AS_XML_COL)')");
[1]
http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.l
uw.sql.rtn.doc/doc/r0012547.html
[2]
http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.l
uw.sql.rtn.doc/doc/r0023575.html
[3]
http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.l
uw.sql.rtn.doc/doc/r0023573.html
[4]
http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/topic/com.ibm.db2.l
uw.sql.rtn.doc/doc/r0023577.html
Cheers,
Tuesday, March 03, 2009
db2 how to
Start an instance
As an instance owner on the host running db2, issue the following command
$ db2start
Stopping the instance
$ db2stop
Connect to the database as instance owner
$ db2
as a user of the database:
$source ~instance/sqllib/db2cshrc (csh users)
$ . ~instance/sqllib/db2profile (sh users)
$ db2 connect to databasename
Create a table
$ db2-> create table employee
(ID SMALLINT NOT NULL,
NAME VARCHAR(9),
DEPT SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB CHAR(5) CHECK (JOB IN ('Sales', 'Mgr', 'Clerk')),
HIREDATE DATE,
SALARY DECIMAL(7,2),
COMM DECIMAL(7,2),
PRIMARY KEY (ID),
CONSTRAINT YEARSAL CHECK (YEAR(HIREDATE) > 1986 OR SALARY > 40500) )
A simple version:
db2-> create table employee ( Empno smallint, Name varchar(30))
Create a schema
If a user has SYSADM or DBADM authority, then the user can create a schema with any valid name. When a database is created, IMPLICIT_SCHEMA authority is granted to PUBLIC (that is, to all users). The following example creates a schema for an individual user with the authorization ID 'joe'
CREATE SCHEMA joeschma AUTHORIZATION joe
Create an alias
The following SQL statement creates an alias WORKERS for the EMPLOYEE table:
CREATE ALIAS WORKERS FOR EMPLOYEE
You do not require special authority to create an alias, unless the alias is in a schema other than the one owned by your current authorization ID, in which case DBADM authority is required.
Create an Index:
The physical storage of rows in a base table is not ordered. When a row is inserted, it is placed in the most convenient storage location that can accommodate it. When searching for rows of a table that meet a particular selection condition and the table has no indexes, the entire table is scanned. An index optimizes data retrieval without performing a lengthy sequential search. The following SQL statement creates a
non-unique index called LNAME from the LASTNAME column on the EMPLOYEE table, sorted in ascending order:
CREATE INDEX LNAME ON EMPLOYEE (LASTNAME ASC)
The following SQL statement creates a unique index on the phone number column:
CREATE UNIQUE INDEX PH ON EMPLOYEE (PHONENO DESC)
Drop a database:
Db2 drop database sample
Alter tablespace
Adding a Container to a DMS Table Space You can increase the size of a DMS table space (that is, one created with the MANAGED BY DATABASE clause) by adding one or more containers to the table
space. The following example illustrates how to add two new device containers (each with 40 000 pages) to a table space on a UNIX-based system:
ALTER TABLESPACE RESOURCE
ADD (DEVICE '/dev/rhd9' 10000,
DEVICE '/dev/rhd10' 10000)
The following SQL statement drops the table space ACCOUNTING:
DROP TABLESPACE ACCOUNTING
You can reuse the containers in an empty table space by dropping the table space but you must COMMIT the DROP TABLESPACE command, or have had AUTOCOMMIT on, before attempting to reuse the containers. The following SQL statement creates a new temporary table space called TEMPSPACE2:
CREATE TEMPORARY TABLESPACE TEMPSPACE2 MANAGED BY SYSTEM USING ('d')
Once TEMPSPACE2 is created, you can then drop the original temporary table space TEMPSPACE1 with the command: DROP TABLESPACE TEMPSPACE1
Add Columns to an Existing Table
When a new column is added to an existing table, only the table description in the system catalog is modified, so access time to the table is not affected immediately. Existing records are not physically altered
until they are modified using an UPDATE statement. When retrieving an existing row from the table, a null or default value is provided for the new column, depending on how the new column was defined. Columns that are added after a table is created cannot be defined as NOT NULL: they must be defined as either NOT NULL WITH DEFAULT or as nullable. Columns can be added with an SQL statement. The following statement uses the ALTER TABLE statement to add three columns to the EMPLOYEE table:
ALTER TABLE EMPLOYEE
ADD MIDINIT CHAR(1) NOT NULL WITH DEFAULT
ADD HIREDATE DATE
ADD WORKDEPT CHAR(3)
GrantPermissions by Users
The following example grants SELECT privileges on the EMPLOYEE table to the user HERON:
GRANT SELECT ON EMPLOYEE TO USER HERON
The following example grants SELECT privileges on the EMPLOYEE table to the group HERON:
GRANT SELECT ON EMPLOYEE TO GROUP HERON
GRANT SELECT,UPDATE ON TABLE STAFF TO GROUP PERSONNL
If a privilege has been granted to both a user and a group with the same name, you must specify the GROUP or USER keyword when revoking the privilege. The following example revokes the SELECT privilege on the EMPLOYEE table from the user HERON:
REVOKE SELECT ON EMPLOYEE FROM USER HERON
To Check what permissions you have within the database
SELECT * FROM SYSCAT.DBAUTH WHERE GRANTEE = USER AND GRANTEETYPE = 'U'
SELECT * FROM SYSCAT.COLAUTH WHERE GRANTOR = USER
At a minimum, you should consider restricting access to the SYSCAT.DBAUTH, SYSCAT.TABAUTH, SYSCAT.PACKAGEAUTH, SYSCAT.INDEXAUTH, SYSCAT.COLAUTH, and SYSCAT.SCHEMAAUTH catalog views. This would prevent information on user privileges, which could be used to target an authorization name for break-in, becoming available to everyone with access to the database. The following statement makes the view available to every authorization name:
GRANT SELECT ON TABLE MYSELECTS TO PUBLIC
And finally, remember to revoke SELECT privilege on the base table:
REVOKE SELECT ON TABLE SYSCAT.TABAUTH FROM PUBLIC
Delete Records from a table
db2-> delete from employee where empno = '001'
db2-> delete from employee
The first example will delete only the records with emplno field = 001 The second example deletes all the records
Import Command
Requires one of the following options: sysadm, dbadm, control privileges on each participating table or view, insert or select privilege, example:
db2->import from testfile of del insert into workemployee
where testfile contains the following information 1090,Emp1086,96613.57,55,Secretary,8,1983-8-14
or your alternative is from the command line:
db2 " import from 'testfile' of del insert into workemployee"
db2 < test.sql where test.sql contains the following line:
db2 import from test file of del insert into workemployee
Load Command:
Requires the following auithority: sysadm, dbadm, or load authority on the database:
example: db2 "load from 'testfile' of del insert into workemployee"
You may have to specify the full path of testfile in single quotes
Authorization Level:
One of the following:
sysadm
dbadm
load authority on the database and
INSERT privilege on the table when the load utility is invoked in INSERT mode, TERMINATE mode
(to terminate a previous load insert operation), or RESTART mode (to restart a previous load insert
operation)
INSERT and DELETE privilege on the table when the load utility is invoked in REPLACE mode,
TERMINATE mode (to terminate a previous load replace operation), or RESTART mode (to restart a
previous load replace operation)
INSERT privilege on the exception table, if such a table is used as part of the load operation.
Caveat:
If you are performing a load operation and you CTRL-C out of it, the tablespace is left in a load pending state. The only way to get out of it is to reload the data with a terminate statement
First to view tablestate:
Db2 list tablespaces show detail will display the tablespace is in a load pending state.
Db2tbst
Here is the original query
Db2 "load from '/usr/seela/a.del' of del insert into A";
If you break out of the load illegally (ctrl-c), the tablespace is left load pending.
To correct:
Db2 "load form '/usr/seela/a.del' of del terminate into A";
This will return the table to it's original state and roll back the entries that you started loading.
If you try to reset the tablespace with quiesce, it will not work . It's an integrety issue
DB2BATCH- command
Reads SQL statements from either a flat file or standard input, dynamically prepares and describes the statements and returns an answer set: Authorization: sysadmin .and Required Connection -None..eg
db2batch -d databasename -f filename -a userid/passwd -r outfile
DB2expln - DB2 SQL Explain Tool
Describes the access plan selection for static SQL statements in packages that are stored in the DB2 common server systems catalog. Given the database name, package name ,package creator abd section
number the tool interprets and describes the information in these catalogs.
DB2exfmt - Explain Table Format Tool
DB2icrt - Create an instance
DB2idrop - Dropan instance
DB2ilist - List instances
DB2imigr - Migrate instances
DB2iupdt - Update instances
Db2licm - Installs licenses file for product ;
db2licm -a db2entr.lic
DB2look - DB2 Statistics Extraction Tool
Generates the updates statements required to make the catalog statistics of a test database match those of a production. It is advantageous to have a test system contain asubset of your production system's data.
This tool queries the system catalogs of a database and outputs a tablespace n table index, and column information about each table in that database Authorization: Select privelege on system catalogs Required
Connection - None. Syntax
db2look -d databasename -u creator -t Tname -s -g -a -p -o
Fname -e -m -c -r -h
where -s : generate a postscript file, -g a graph , -a for all users in the database, -t limits output to a particular tablename, -p plain text format , -m runs program in mimic mode, examples:
db2look -d db2res -o output will write stats for tables created in db
db2res in latex format
db2look -p -a -d db2res -o output - will write stats in plain text format
DB2 -list tablespaces show detail
displays the following information as an example:
Tablespaces for Current Database
Tablespace ID = 0
Name = SYSCATSPACE
Type = System managed space
Contents = Any data
State = 0x0000
Detailed explanation:
Normal
Total pages = 2925
Useable pages = 2925
Used pages = 2925
Free pages = Not applicable
High water mark (pages) = Not applicable
Page size (bytes) = 4096
Extent size (pages) = 32
Prefetch size (pages) = 32
Number of containers = 1
db2tbst - Get tablespace state.
Authorization - none , Required connection none, syntax db2tbst tabpespace-state:The state value is part of the output of list tablespaces example
db2tbst 0X0000 returns state normal
db2tbst 2 where 2 indicates tablespace id 2 will also work
DB2dbdft - environment variable
Defining this environment variable with the database you want to connect to automatically connects you to the database . example setenv db2dbdft sample will allow you to connect to sample by default.
CLP - Command Line Processor Invocation:
db2 starts the command line processor. The clp is used to execute database utilities, sql statements and online help. It offers a variety of command options and can be started in :
1. interactive mode : db2->
2. command mode where each command is prefixed by db2
3. batch mode which uses the -f file input option
Update the configuration in the database :
Db2 =>update db cfg for sample using maxappls 60
MAXFILOP = 64 2 - 9150
db2 => update db cfg for sample using maxappls 160
db2 => update db cfg for sample using AVG_APPLS 4
db2 =>update db cfg for sample using MAXFILOP 256
can see updated parameters from client
tcpip ..... not started up properly Check the DB2COMM variable if it it is set
db2set DB2COMM
How to terminate the database if processes are still attached:
db2 force applications all
db2stop
db2start
db2 connect to dbname (locally)
How to trace logs withing the db2diag.log file:
Connections to db fails:
Move the db2diag.log from the sqllib/db2dump directory to some other working directory ( mv db2diag.log
db2 update dbm cfg using diaglevel 4
db2stop
db2start
db2trc on -l 8000000 -e 10
db2 connect to dbname (locally)
db2trc dump 01876.trc
db2trc flw 01876.trc 01876.flw
db2trc fmt 01876.trc 01876.fmt
db2trc off
Import data from ascii file to database
db2 " import from inp.data of del insert into test"
db2 "load from '/cs/home/tech1/seela/inp.data' of del insert into seela.seela"
db2 < test.sql
Revoke permissions from the database from public:
db2 => create database GO3421
DB20000I The CREATE DATABASE command completed successfully.
Now I want to revoke connect, createtab bindadd on database from public
On server: db2 => revoke connect , createtab, bindadd on database from public
Now on client, as techstu, I tried to connect to go3421
db2 => connect to go3421
SQL1060N User "TECHSTU " does not have the CONNECT privilege. SQLSTATE=08004
Now I have to grant connect privilege to group ugrad
On server:
db2 => grant connect, createtab on database to group ugrad
DB20000I The SQL command completed successfully.
Tested on client I can connect successfully.
Now on the client, I can connect as a student, list tables but not select. I
can still describe tables
To prevent this:
On server
revoke select on table syscat.columns from public
Now on client, I cannot describe but also on my tables.
db2 => revoke select on table syscat.columns from public
DB20000I The SQL command completed successfully.
db2 => grant select on table syscat.columns to group ugrad
On server:
db2 => revoke select on table syscat.indexes from public
DB20000I The SQL command completed successfully.
select * from syscat.dbauth will display all the privileges for
dbadm authority:
DBADMAUTH CREATETABAUTH BINDADDAUTH CONNECTAUTH
NOFENCEAUTH IMPLSCHEMAAUTH LOAD AUTH
select
TABNAME,DELETEAUTH,INSERTAUTH,SELECTAUTH from
syscat.tabauth
grant connect, createtab
grant connect, createtab on database to user techstu
to group ugrad
Instance Level Authority
db2 get dbm cfg
db2 get admin cfg
db2 get db cfg
CLP using filename on the command line
Db2 -f filename.clp
The -f option directs the clp to accept input from file.
Db2 +c -v +t infile .. The option can be prefixed by a + sign or turned on by a letter with a -sign
+c is turned off, -v turned on and -f turned on
c is for commit, v for verbose and f for filename
-t termination character is set to semicolon
Thursday, January 22, 2009
Getting db snapshot
=====================
db2 "get snapshot for db on IBSDB"> dbsnapshot.out
Getting dbm snapshot
=====================
db2 "get snapshot for dbm" > dbmsnapshot.out
Getting dynamic SQL snapshot
===========================
db2 "get snapshot for dynamic sql on IBSDB" > dynamicsql.out
Getting application snapshot
============================
db2 "get snapshot for applications on IBSDB" > applications.out
Getting lock snapshot
====================
db2 "get snapshot for locks on IBSDB" > locks.out
Kill application that lock db
===============================
force application(lock_id)
Wednesday, December 03, 2008
Hans's Top Ten JSP Tips
JavaServer Pages (JSP) is the latest tool for Java-based Web application
development. A JSP page contains regular markup code plus special JSP
elements. When the page is requested, the static markup code and the
dynamic content produced by the JSP elements are combined to form the
complete response to the request.
It's impossible to tell you everything you need to know to use JSP
effectively in a short article like this (that's why I wrote
JavaServer Pages).
Instead, this article focuses on the frequently asked questions that I've
heard from people who have just started to play around with JSP.
- Choosing the Right Include Mechanism
A JSP page can include page fragments from other files to form the complete
response. You can use this, for instance, to keep header, footer, and
navigation bar content in separate files and include them in all other
pages. There are two include mechanisms: the include directive and
the include action. It's not always obvious which one to use,
though.
The include directive, <%@ include file="filename.inc" %>,
includes the content of the specified file during the translation
phase--when the page is converted to a servlet. The main page and the
included file are simply merged. This means that scripting variables
declared in one file (using scripting elements or an action element like
<jsp:useBean>) are visible in all files and must have unique
names. Some containers detect changes in files included with the directive,
but the specification doesn't require it. Therefore, changes you make to
the included file in a running system may not be reflected immediately; you
may have to update the main JSP page, or remove the class file generated
for the main page in order to see the change.
The include action,
<jsp:include page="pagename.jsp" flush="true" />,
includes the response generated by executing the specified page (a
JSP page or a servlet) during the request processing phase--when the page
is requested by a user. As opposed to the include directive, the page name
can be specified as a so-called request-time attribute value, so
which page to include can be decided when the main page is requested. Since
it's the response generated by the page that is included, not the
content of the page itself, scripting variables declared in one file are
not available to the other files. To share an object between the pages you
must instead place it in one of the following JSP scopes: request, session
or application scope. If you change a page included with the include
action, the change always takes effect immediately.
My rule of thumb for when to use the different mechanisms is this:- Use the include directive if the file changes rarely. It's the
fastest mechanism. If your container doesn't automatically detect changes,
you can force the changes to take effect by deleting the main page class
file. - Use the include action only for content that changes often, and
if which page to include cannot be decided until the main page is requested.
- Use the include directive if the file changes rarely. It's the
- Dealing with Buffer Flushing Issues
An HTTP response message contains both headers and a body. The headers tell
the browser things like what type of data the body contains (HTML text, an
image), the size of the body, if the body can be cached, and so on. Headers
are also used to set cookies and to tell the browser to automatically get
another page (a redirect). All response headers must be sent to the browser
before the body is sent.
To allow parts of the body to be produced (from static template text as
well as content generated dynamically by JSP elements) before headers are
set, the body is buffered. Instead of sending the response to the browser
as soon as something is written to the response body, the JSP container
writes all static markup code and all dynamic content generated by JSP
elements to the buffer. At some point, such as when the buffer is full or
the end of the page is reached, the container sends all headers that have
been set followed by the buffered body content. In servlet speak, this is
called committing the response. After the response has been
committed, you can't set headers, such as for cookies or a redirection
instruction. Another thing you can't do is forward the request to another
page.
In most cases, this is not a problem. The default buffer size is 8KB, more
than enough for a typical page, and you can increase it with the
buffer attribute of the page directive. But if you use
the include action in a page, you may be in for a surprise. Due to
limitations in the way the servlet features used by
<jsp:include> are specified, the buffer is always flushed
before the target page is invoked. This means that you can't set headers or
use <jsp:forward> after a <jsp:include> action.
An unfortunate side-effect of this automatic flushing is that runtime
errors triggered by JSP elements after a <jsp:include> action
may not be reported correctly, since many JSP containers use the forward
mechanism to display the error page. If you see an error message like
"response already committed" in a page with <jsp:include>
elements, I suggest that you use the include directive instead (at least
until you have isolated the problem). - Passing Data Between Pages Processing the Same Request
Quite often, more than one JSP page is used to process a single request.
One example is when you use the include action to include a
common navigation bar in all pages. Another example is when you use one
page for request processing (e.g., input validation and database access) and
then use the forward action, <jsp:forward page="pagename.jsp"
/>, to let another page generate the response. There are two ways to
pass data from one page to another: using request parameters or request
attributes.
First of all, the page invoked using a <jsp:include> or
<jsp:forward> action has access to all HTTP request parameters
that were sent to the first page. In addition, you can specify new request
parameters using nested <jsp:param> actions:
<jsp:forward page="login.jsp">
<jsp:param name="errMsg"
value="The name or password is not valid" />
</jsp:forward>
The target page has access to the all request parameters the same way, no
matter if they are original or additional parameters.
Request parameters can only hold string values. If you need to pass an
object, say a UserInfoBean with various user information
properties, you need to pass it as a request attribute instead (or as a
session or application scope bean, but let's ignore that for now). A
request attribute is the same thing as a request scope object, so the first
page can create the object and set all its properties with the
<jsp:useBean> and <jsp:setProperty> actions:
<jsp:useBean id="userInfo" scope="request"
class="com.mycompany.UserInfoBean">
<jsp:setProperty name="userInfo" property="*" />
</jsp:useBean>
...
<jsp:forward page="nextpage.jsp" />
In order to use the bean in a page invoked through <jsp:forward>
or <jsp:include>, you must use the <jsp:useBean>
action in the invoked page as well. This is so that the bean created by the
first page can be located and associated with the specified id. It can then
be used by scripting code or other actions, such as
<jsp:getProperty>, in the new page:
<jsp:useBean id="userInfo" scope="request"
class="com.mycompany.UserInfoBean" />
<jsp:getProperty name="userInfo" property="firstName" /> - Choosing Between Forward and Redirect
If you want to pass the control from one page to another, you can either
forward to the other page, as described above, or redirect to
the new page (using the sendRedirect() method of the implicit
response object).
There's an important difference between a forward and a redirect. When you
forward, the target page is invoked by the JSP container through an
internal method call; the new page continues to process the same request
and the browser is not aware of the fact that more than one page is
involved. A redirect, on the other hand, means that the first page tells
the browser to make a new request to the target page. The URL shown in the
browser therefore changes to the URL of the new page when you redirect, but
stays unchanged when you use forward. A redirect is slower than a forward
because the browser has to make a new request. Another difference is that
request scope objects are no longer available after a redirect because it
results in a new request. If you need to pass data to the page you redirect
to, you have to use a query string and pass them as request parameters (or
save the data as session or application scope objects).
So how do you decide if you should use forward or redirect? I look at it
like this: Forwarding is always faster, so that's the first choice. But
since the URL in the browser refers to the start page even after the
forward, I ask myself what happens if the user reloads the page (or just
resizes the window; this often reloads the page automatically). If the
start page is a page that updates some information, such as adding an item
to the shopping cart or inserting information in a database, I don't want
it to be invoked again on a reload. To show the result of the processing,
I therefore redirect to a page with a confirmation message, instead of
using forward. - Choosing Between Beans and Custom Actions
In JSP 1.0, JavaBeans were the only type of components that you could use
to encapsulate the Java code and invoke using standard JSP action elements,
such as <jsp:getProperty> and <jsp:setProperty>.
JSP 1.1 adds custom action elements to the component toolbox. A
Java class, called a tag handler, implements a custom action's
behavior. In its most simple form, it's just a JavaBeans class with
property access methods corresponding to the custom action elements plus
a few extra methods used by the container to invoke the tag handler (so it
can do its job). Tag handlers that need to process the element's body or
create objects assigned to scripting variables requires a bit more effort
to develop, but it's still not rocket science. It is, however, too much to
describe in detail here. My book contains two chapters with all the
details about how to develop custom action tag handlers.
As is often the case in software development, it's hard to say exactly
when a bean or a custom action is the preferred component type. My rule of
thumb is that a bean is a great carrier of information and a custom
action is great for processing information. Custom actions can use
beans as input and output. For instance, you can use a bean to capture
form input, with the <jsp:setProperty> action, and then a
custom action to save the properties of the bean in a database. The
reverse is also a good example; get information from a database using a
custom action that makes it available to the page as a bean. - Using Packages for Bean Classes
When you develop a bean to be used in a JSP page, I recommend that you
make it part of a named package. A Java class that does not use a
package statement ends up in the so-called unnamed package.
The servlet class generated from the JSP page is, however, typically
assigned to a named package. If you try to refer to a class in the unnamed
package from a class in a named package, Java cannot find the class
unless you use an import statement to import it. In a JSP page that means
you must use both a page directive to import the class, and the
<jsp:useBean> action to make it available:
<%@ page import="UserInfoBean" %>
<jsp:useBean id="userInfo" class="UserInfoBean" />
If the bean is part of a named packed, the <jsp:useBean>
action is all you need:
<jsp:useBean id="userInfo"
class="com.mycompany.UserInfoBean" /> - Mixing Scripting Variables and Scope Variables
My general advice is that you avoid embedding Java code in your JSP pages.
Code in scripting elements can easily lead to hard to find syntax errors
and too much code in the pages makes the Web application hard to maintain.
One specific area of confusion when you use both Java code scriptlets and
JSP action elements is how scripting variables and objects created by an
action element in a JSP scope interact. Or rather, don't interact.
Consider this example:
<jsp:useBean id="userInfo"
class="com.mycompany.UserInfoBean" >
<jsp:setProperty name="userInfo" property="firstName" />
</jsp:useBean>
<%
userInfo = new com.mycompany.UserInfoBean();
%>
<jsp:getProperty name="userInfo" property="firstName" />
Here a UserInfoBean instance is created by the
<jsp:useBean> action in the page scope (default) and its
firstName property is set to the value passed as a request
parameter with the same name. The <jsp:useBean> also makes the
bean available as a scripting variable with the same name as the scope
variable (userInfo in this example). Next, a scriptlet creates a
new instance of the UserInfoBean class and assigns it to the
userInfo scripting variable. Finally, the
<jsp:getProperty> action retrieves the value of the bean's
firstName property. But which instance of the UserInfoBean
does <jsp:getProperty> use? The answer is the instance
available in the page scope. The <jsp:getProperty> action, or
any action element for that matter, cannot access scripting variables,
only objects placed in one of the standard JSP scopes: page, request,
session and application. If you must use scripting elements to create
objects that you then want to let actions access, you must also place them
in the appropriate scope:
...
<%
userInfo = new com.mycompany.UserInfoBean();
pageContext.setAttribute("userInfo", userInfo);
%>
<jsp:getProperty name="userInfo"
property="firstName" />
In this modified example, the setAttribute() method is used to
replace the page scope object created by <jsp:useBean> with
the instance created by the scriptlet. Hence, the
<jsp:getProperty> action finds the new instance. - Setting Properties to Non-String Data Type Values
Bean properties, as you probably know, are represented by accessor
methods: a setter method for a writeable property and a getter method for
a readable property. The data type of the property is the data type of the
setter method's single argument and the getter methods return type.
The <jsp:setProperty> action is often used to set a bean's
property to the values of request parameters. Request parameters are sent
as strings, so what happens if the bean's properties are of other types
than String? The JSP container is nice enough to convert
String values to the most commonly used Java data types, as
described in the following table:
Property TypeConversion Method
boolean or
BooleanBoolean.valueOf(String)
byte or ByteByte.valueOf(String)
char or
CharacterString.charAt(int)
double or
DoubleDouble.valueOf(String)
int or
IntegerInteger.valueOf(String)
float or
FloatFloat.valueOf(String)
long or LongLong.valueOf(String)
If your property is of a type not listed in the table, you need to take
care of the conversion yourself. The most author-friendly way is to use a
String property, even for properties that logically should be of a
different type, such as a date or a RGB color value, and let the bean
convert it internally. But if you really want to use a data type other
than String or the ones listed above, the page author can use a
request-time attribute value that evaluates to the correct data type to
set the property value:
<jsp:setProperty name="userInfo" property="empDate"
value='<%= new
java.util.Date(request.getParameter("empDate")) %>' />
Note that this example uses a deprecated Date constructor and is
very error-prone (it fails if the empDate parameter is missing or
doesn't hold a valid date string). I use it only to illustrate how you can
set an attribute of a data type that has no JSP-supported conversion rule,
such as the Date class used here.
The rules described here for bean properties set by
<jsp:setProperty> also applies to custom action attributes. - Accessing a Database
One of the most frequently asked questions on Sun Microsystem's JSP-INTEREST
mailing list is how to access a database from a JSP page. I'm sorry, but a
complete description is out of scope for this article. I can give you some
guidelines, though.
JSP is Java, so as in all Java programs, you'd use JDBC to access a database.
You can read more about the JDBC API here.
I recommend that you do not put the database access code directly
in the JSP page. Instead, create a bean or a custom action that does all
the hard work. My book contains a set of custom actions for database
access that you can use, and there are many other examples available on
the Net (see Tip 10 of this article). For a complex application,
you may actually want to use a servlet for all database access and let it
forward the request to a JSP page that only deals with rendering the
result. This model is often referred to as the Model-View-Controller (MVC)
model, or Model 2 (a term used in a prerelease of the JSP specification).
I show examples of this alternative in my book as well. You can also
learn more about the MVC model from the Apache Struts project.
Database access is typically very expensive in terms of server resources.
You should use a connection pool (covered in the book and frequently
discussed on the JSP-INTEREST list) to share database connections
efficiently between all requests. Another resource saver is to cache the
results of database queries as much as possible. In many cases, the
database information rarely changes. For instance, product catalog
information may change only when products are added or deleted, or when
the prices change. For this type of information you can get the data once
and save it as an application scope object that all users can access. In
the rare event that the information changes, just replace the application
scope object with a new version. Another caching strategy for data that
changes infrequently is to cache it as a session scope object. The user
will then see the data as it looks when the session starts, but changes
made during the session are not visible. If you use the session cache
strategy, you must also consider if the amount of memory used for the
cache (one copy per session) is worth the gain in reduced number of
database accesses. Typically it is worth it, but make sure your server has
enough memory to handle the peaks.
If you decide to use a cache, don't use the JDBC ResultSet object
itself as the cache object. A ResultSet is tightly linked to a
specific connection and therefore conflicts with the connection pooling.
Instead, copy the data from the ResultSet into an application
specific bean, a Vector of Vector's, or something
similar. - Finding Out More
I hope you have found something in this article that helps you develop
your JSP based application. But there's a lot more you should know to use
this powerful technology as efficiently as possible. I recommend, of
course, that you read my book,
JavaServer Pages
(O'Reilly).
There's also plenty of information on the Internet. The best place to
start Sun's JSP
page. There you find the JSP specification, articles and tutorials written
by Sun employees, and lots of references to other JSP-related sites and
products.
What is the difference between request.getParameter() and request.getAttribute() ?
http://www.jguru.com/faq/view.jsp?EID=1307699
Ok so when you click the submit button on this HTML page the form will be posted to testJSP.jsp
Code:
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
request.getParameter("testParam") will get the value from the posted form (named testForm) of the input box named testParam which is "Hello Param". It will then print it out, so you should see "Hello Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
Now for request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.
Code:
// Your servlet code
public class SomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/** Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("http://www.website.com/yourResource"); //You could give a relative URL, I'm just using absolute for a clear example.
Object object = new Object(); // You can use any type of object you like here, Strings, Custom objects, in fact any object.
request.setAttribute("ObjectName", object);
rd.forward(request, response);
}
}
Now when you call rd.forward() the request will be forwarded to the resource specified ie: in this case "http://www.website.com/yourResource"
Now in this case yourResource is a Servlet, here is the code
Code:
public class YourResourceServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/** Handles the HTTP POST method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
/** Processes requests for both HTTP GET and POST methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve the object stored in the request.
Object myDispatchedObject = request.getAttribute("ObjectName");
}
}
Now you have the object that you passed from resource to resource on the server side.
Using JavaBean Classes in JSP
jsp:setproperty name="b" property="author" value="Someone"
Line 11: author =
jsp:expression>b.getAuthor()jsp:expression
jsp:setproperty/jsp:usebean>
http://www.herongyang.com/jsp/usebean.html
Monday, December 01, 2008
Parse Int problems with leading 0's
Parse Int problems with leading 0's
Trying to convert
ie:
var test = '08';
var value = parseInt(test);
I wan't 08 I currently get it to work like this, but there must be a better way.
if (test.charAt(0) == '0') test= test.charAt(1);
value = parseInt(test);
answer=
There is an optional parameter that allows you to specify base ten. If there are leading zeros for some unknown reason to me parseInt will treat the number as an octal number (base 8) just do it like this:
var test = '08';
var value = parseInt(test,10);
...That one pissed me off forever until I found out what was going on.
Glad to help :)
Tuesday, October 14, 2008
combine 3 record into 1 record by stored in different field
original
GameID CODESTATUS COUNT
====== ========== =======
GAMEA A 5
GAMEA T 10
GAMEA R 15
TO
GAMEID A_STATUS T_STATUS R_STATUS
======== ======== ========= ==========
GAMEA 5 10 15
===================================================
select gameid, count(gameid) as count, sum(aCount) as Available,sum(tCount) As Taken,sum(rCount) as Reserved from (
select gameid, codestatus,
case when codestatus='A' then 1 else 0 end as aCount,
case when codestatus='T' then 1 else 0 end as tCount,
case when codestatus='R' then 1 else 0 end as rCount
from tibsadmin.gamename_code
) as a group by (gameid)
Monday, October 06, 2008
WINDOW.OPEN using POST instead of GET
f.action = "
f.onsubmit = "return true;";
f.target ="preview";
var theHeight = 550;
var theWidth = 480;
var theTop=(screen.height/2)-(theHeight/2);
var theLeft=(screen.width/2)-(theWidth/2);
var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",scrollbars=yes";
window.open('','preview',features);
}