锘??xml version="1.0" encoding="utf-8" standalone="yes"?> char charAt(int index) returns the character at the specified location. int compareTo(String other) returns a negative value if the string comes before other in dictionary order, a positive value if the string comes after other in dictionary order, or 0 if the strings are equal. boolean endsWith(String suffix) returns true if the string ends with suffix. boolean equals(Object other) returns true if the string equals other. boolean equalsIgnoreCase(String other) returns true if the string equals other, except for upper/lowercase distinction. int indexOf(String str) int indexOf(String str, int fromIndex) return the start of the first substring equal to str, starting at index 0 or at fromIndex. int lastIndexOf(String str) int lastIndexOf(String str, int fromIndex) return the start of the last substring equal to str, starting at the end of the string or at fromIndex. int length() returns the length of the string. String replace(char oldChar, char newChar) returns a new string that is obtained by replacing all characters oldChar in the string with newChar. boolean startsWith(String prefix) returns true if the string begins with prefix. String substring(int beginIndex) String substring(int beginIndex, int endIndex) return a new string consisting of all characters from beginIndex until the end of the string or until endIndex (exclusive). String toLowerCase() returns a new string containing all characters in the original string, with uppercase characters converted to lower case. String toUpperCase() returns a new string containing all characters in the original string, with lowercase characters converted to upper case. String trim() returns a new string by eliminating all leading and trailing spaces in the original string. 瀛楃涓蹭笌鍩烘湰鏁版嵁綾誨瀷鐨勮漿鎹㈤棿鐨勮漿鎹㈠繀欏諱嬌鐢↗SP涓殑瀵硅薄鍑芥暟 static void arraycopy(Object from, int fromIndex, Object to, int toIndex, int count)
Parameters: from an array of any type (Chapter 5 explains why this is a parameter of type Object) fromIndex the starting index from which to copy elements to an array of the same type as from toIndex the starting index to which to copy elements count the number of elements to copy
1銆乯ava宸ュ叿鍖?a >http://java.sun.com/j2se/1.4/install-windows.html
2銆佽緗墽琛岀幆澧冿紙windows 2000)
PATH=c:\jdk\bin;
3銆佸畨瑁呭簱婧愭枃浠跺拰鏂囨。
jar xvf src.jar
jar xvf j2sdkversion-doc.zip
絎竴涓猨ava渚嬪瓙
eg:Weclome.java
public class Welcome
{
public static void main(String[] args)
{
String[] greeting=new String[3];
greeting[0]="Welcome to Core Java";
greeting[1]="by Car Horstman";
greeting[2]="and Gary Cornell";
for ( int i=0;i<greeting.length;i++)
System.out.println(greeting[i]);
}
}
]]>
java.util.Enumeration e = mySmartUpload.getRequest().getParameterNames();
]]>
Boolean.getBoolean(String)
Byte.parseByte(String)
Short.parseShort(String)
Integer.parseInt(String)
Long.parseLong(String)
Float.parseDouble(String)
Double.parseDouble(String)
String.valueOF(鏁版嵁)
Array
copies elements from the first array to the second array.
static void sort(Xxx[] a)
Parameters: |
a |
an array of type int, long, short, char, byte, boolean, float or double |
sorts the array, using a tuned QuickSort algorithm.
static int binarySearch(Xxx[] a, Xxx v)
Parameters: |
a |
a sorted array of type int, long, short, char, byte, boolean, float or double |
v |
a value of the same type as the elements of a |
uses the BinarySearch algorithm to search for the value v. If it is found, its index is returned. Otherwise, a negative value r is returned; -r - 1 is the spot at which v should be inserted to keep a sorted.
static void fill(Xxx[] a, Xxx v)
Parameters: |
a |
an array of type int, long, short, char, byte, boolean, float or double |
v |
a value of the same type as the elements of a |
sets all elements of the array to v.
static boolean equals(Xxx[] a, Object other)
Parameters: |
a |
an array of type int, long, short, char, byte, boolean, float or double |
other |
an object |
returns true if other is an array of the same type, if it has the same length, and if the elements in corresponding indexes match.
eg:
int[] smallPrimes = {2, 3, 5, 7, 11, 13};
int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 3);
for (int i = 0; i < luckyNumbers.length; i++)
System.out.println(i + ": " + luckyNumbers[i]);
public class DBPhoneLookupReuse extends HttpServlet {
private Connection con = null;
public void init() throws ServletException {
try {
// Load (and therefore register) the Sybase driver
Class.forName("com.jnetdirect.jsql.JSQLDriver");
con = DriverManager.getConnection(
"jdbc:JSQLConnect://127.0.0.1/database=JAAS", "sa", "db_password");
}
catch (ClassNotFoundException e) {
throw new UnavailableException("Couldn't load database driver");
}
catch (SQLException e) {
throw new UnavailableException("Couldn't get db connection");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><HEAD><TITLE>Phonebook</TITLE></HEAD>");
out.println("<BODY>");
HtmlSQLResult result =
new HtmlSQLResult("SELECT UserName,Password FROM Users", con);
// Display the resulting output
out.println("<H2>Users:</H2>");
out.println(result);
out.println("</BODY></HTML>");
}
public void destroy() {
// Clean up.
try {
if (con != null) con.close();
}
catch (SQLException ignored) { }
}
}
HtmlSQLResult.java
import java.sql.*;
public class HtmlSQLResult {
private String sql;
private Connection con;
public HtmlSQLResult(String sql, Connection con) {
this.sql = sql;
this.con = con;
}
public String toString() { // can be called at most once
StringBuffer out = new StringBuffer();
// Uncomment the following line to display the SQL command at start of table
// out.append("Results of SQL Statement: " + sql + "<P>\n");
try {
Statement stmt = con.createStatement();
if (stmt.execute(sql)) {
// There's a ResultSet to be had
ResultSet rs = stmt.getResultSet();
out.append("<TABLE>\n");
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
// Title the table with the result set's column labels
out.append("<TR>");
for (int i = 1; i <= numcols; i++)
out.append("<TH>" + rsmd.getColumnLabel(i));
out.append("</TR>\n");
while(rs.next()) {
out.append("<TR>"); // start a new row
for(int i = 1; i <= numcols; i++) {
out.append("<TD>"); // start a new data element
Object obj = rs.getObject(i);
if (obj != null)
out.append(obj.toString());
else
out.append(" ");
}
out.append("</TR>\n");
}
// End the table
out.append("</TABLE>\n");
}
else {
// There's a count to be had
out.append("<B>Records Affected:</B> " + stmt.getUpdateCount());
}
}
catch (SQLException e) {
out.append("</TABLE><H1>ERROR:</H1> " + e.getMessage());
}
return out.toString();
}
}
InetAddress ip = InetAddress.getByName(鈥?92.168.0.1.鈥?; // ip address of your windows controller
UniAddress myDomain = new UniAddress(ip);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(鈥滿YDOMAIN鈥? 鈥渕ylogin鈥? 鈥渕ypasword鈥?;
SmbSession.logon(myDomain, auth);
If an exception is triggered, the controller didn鈥檛 like the login and the password
2銆丠ttp鏂瑰紡涓媤eb.xml涓璮ilter鐨勯厤緗?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "<web-app>
<display-name>WEB APP</display-name>
<description>WEB APP description</description>
<servlet>
<servlet-name>ShowRequestHeaders</servlet-name>
<servlet-class>coreservlets.ShowRequestHeaders</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowRequestHeaders</servlet-name>
<url-pattern>/ShowRequestHeaders</url-pattern>
</servlet-mapping>
<filter>
<filter-name>NtlmHttpFilter</filter-name>
<filter-class>jcifs.http.NtlmHttpFilter</filter-class>
<init-param>
<param-name>jcifs.http.domainController</param-name>
<param-value>192.168.10.1</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>NtlmHttpFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
public static String addDate(String day,int x)
{
SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd");
Date date = null;
try
{
date = format.parse(day);
}
catch (ParseException ex)
{
ex.printStackTrace();
}
if (date==null) return "";
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,x);
date=cal.getTime();
System.out.println("3 days after(or before) is "+format.format(date));
cal=null;
return format.format(date);
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet for testing the use of packages
* and utilities from the same package.
* <P>
* Taken from Core Servlets and JavaServer Pages 2nd Edition
* from Prentice Hall and Sun Microsystems Press,
* http://www.coreservlets.com/.
* © 2003 Marty Hall; may be freely used or adapted.
*/
public class HelloServlet3 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Hello (3)";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>" + title + "</H1>\n" +
"</BODY></HTML>");
}
}
package coreservlets;
import javax.servlet.*;
import javax.servlet.http.*;
/** Some simple timesavers. Note that most are static methods.
* <P>
* Taken from Core Servlets and JavaServer Pages 2nd Edition
* from Prentice Hall and Sun Microsystems Press,
* http://www.coreservlets.com/.
* © 2003 Marty Hall; may be freely used or adapted.
*/
public class ServletUtilities {
public static final String DOCTYPE =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">";
public static String headWithTitle(String title) {
return(DOCTYPE + "\n" +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
}
/** Read a parameter with the specified name, convert it
* to an int, and return it. Return the designated default
* value if the parameter doesn't exist or if it is an
* illegal integer format.
*/
public static int getIntParameter(HttpServletRequest request,
String paramName,
int defaultValue) {
String paramString = request.getParameter(paramName);
int paramValue;
try {
paramValue = Integer.parseInt(paramString);
} catch(NumberFormatException nfe) { // null or bad format
paramValue = defaultValue;
}
return(paramValue);
}
public static double getDoubleParameter
(HttpServletRequest request,
String paramName,
double defaultValue) {
String paramString = request.getParameter(paramName);
double paramValue;
try {
paramValue = Double.parseDouble(paramString);
} catch(NumberFormatException nfe) { // null or bad format
paramValue = defaultValue;
}
return(paramValue);
}
/** Replaces characters that have special HTML meanings
* with their corresponding HTML character entities.
*/
// Note that Javadoc is not used for the more detailed
// documentation due to the difficulty of making the
// special chars readable in both plain text and HTML.
//
// Given a string, this method replaces all occurrences of
// '<' with '<', all occurrences of '>' with
// '>', and (to handle cases that occur inside attribute
// values), all occurrences of double quotes with
// '"' and all occurrences of '&' with '&'.
// Without such filtering, an arbitrary string
// could not safely be inserted in a Web page.
public static String filter(String input) {
if (!hasSpecialChars(input)) {
return(input);
}
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i<input.length(); i++) {
c = input.charAt(i);
switch(c) {
case '<': filtered.append("<"); break;
case '>': filtered.append(">"); break;
case '"': filtered.append("""); break;
case '&': filtered.append("&"); break;
default: filtered.append(c);
}
}
return(filtered.toString());
}
private static boolean hasSpecialChars(String input) {
boolean flag = false;
if ((input != null) && (input.length() > 0)) {
char c;
for(int i=0; i<input.length(); i++) {
c = input.charAt(i);
switch(c) {
case '<': flag = true; break;
case '>': flag = true; break;
case '"': flag = true; break;
case '&': flag = true; break;
}
}
}
return(flag);
}
}
涓嬮潰鏄帴鍙o紝闇瑕佹敮鎸佸畾鏃跺櫒鍔熻兘鐨勭被瑕佸疄鐜拌繖涓帴鍙o細
TimerClient.java
package com.ly.util;
/**
* TimerClient Interface
*
* @version 1.0, 8 October 1995
*
*/
public interface TimerClient
{
void timerEvent(int id);
}
涓嬮潰鏄畾鏃跺櫒鐨勫疄鐜幫紝鍖呮嫭涓変釜綾伙細TimerCtl,TimerTask,TimerTasks銆傚叾涓璗imerTask鐢ㄦ潵鎻忚堪瀹氭椂鍣ㄤ俊鎭俆imerTasks鏄竴涓猅imerTask鐨勫垪琛紝榪欐牱鎴戜滑灝卞彲浠ュ悓鏃跺湪涓涓簲鐢ㄤ腑瀹夋彃澶氫釜瀹氭椂鍣ㄣ俆imerCtl鏄畾鏃跺櫒鎺у埗綾伙紝鏄釜綰跨▼錛屼笉鍋滃湴媯鏌imerTasks涓槸鍚︽湁TimerTask鍒版湡錛岃鏄湁TimerTask鍒拌揪鎸囧畾鐨勬椂闂達紝鍒欏洖璋僒imerTask鎸囧畾鐨凾imerClient鐨則imerEvent鎺ュ彛銆?/P>
TimerCtl.java
package com.ly.util;
import java.util.Vector;
import java.util.Enumeration;
//import com.borland.jb.util.Diagnostic;
/**
* Timer Component
*
* Note:
* - The successful operation of this timer requires clients to execute simple, short
* code snippets when called back by the engine. Otherwise the queue's delivery
* mechanism will be held up
*
* Further work:
* - When Thread.Interrupt is implemented we can switch from the busy wait model to
* the calculated wait model. Without the interrupt the thread waits for the
* calculated interval before waking up. This is a problem if another shorter
* request arrives. For now we'll assume the minimum resolution of the timer is
* 100ms.
*
* @version 1.0, 2 October 1995
*
*/
public class TimerCtl
{
static TimerTasks timerTasks;
public TimerCtl() {
}
/*
* Start a timer running
*/
public static void startTimer(TimerClient client, int eventId, long delay, boolean repeat) {
// create the timer if necessary
if (timerTasks == null) {
timerTasks = new TimerTasks();
timerTasks.start();
}
//Diagnostic.out.println("TIMER: startTimer"+eventId);
// add the new task to the queue
timerTasks.add(client, eventId, delay, repeat);
}
/*
* Stop a timer
*/
public static void stopTimer(TimerClient client, int eventId) {
//Diagnostic.out.println("TIMER: stopTimer"+eventId);
if(timerTasks != null)
timerTasks.end(client, eventId);
}
}
class TimerTasks extends Thread
{
Vector tasks = new Vector();
boolean suspended = false;
boolean sleeping = false;
/**
* Thread task runner
*/
public void run() {
// Loop forever
while (true) {
long sleepTime = 0;
// Ensure that the tasks class is protected
synchronized (tasks) {
//Diagnostic.out.println("TIMER: Tick");
// Scan the job list for any jobs which may fire.
// Mark one-shot jobs for deletion
// Calculate the maximum time we can sleep for
sleepTime = scan();
// Delete DeletePending jobs. DeletePending jobs result from one-shots which have
// been sent, and repeat jobs which have been cancelled. Jobs may have been
// cancelled during the Scan process.
purge();
}
// Suspend timer if necessary
if (tasks.size() == 0) {
//Diagnostic.out.println("TIMER: Suspend");
try {
synchronized(this) {
suspended = true;
wait();
}
}
catch (InterruptedException e) {
}
}
else {
//Diagnostic.out.println("TIMER: Suggested Sleeping for "+sleepTime);
if (sleepTime >= 0) {
try {
sleeping = true;
sleep(sleepTime);
sleeping = false;
}
catch (InterruptedException i) {
//Diagnostic.out.println("TIMER: Caught me napping");
}
}
}
}
}
/**
* Add a new task
*/
public void add(TimerClient client, int eventId, long delay, boolean repeat) {
TimerTask t = new TimerTask(client, eventId, delay, repeat);
synchronized (tasks) {
tasks.addElement((Object)t);
}
// Want instant response - wake the thread if it's napping
// unfortunately the interrupt() method is not working
// if (sleeping)
// interrupt();
if (suspended) {
synchronized(this) {
notify();
//Diagnostic.out.println("TIMER: Resume");
suspended = false;
}
}
}
/**
* Find the job and mark it for deletion
*/
public void end(TimerClient client, int eventId) {
synchronized (tasks) {
for (int i = 0; i < tasks.size(); i++) {
TimerTask t = (TimerTask)tasks.elementAt(i);
//if (!t.deletePending && t.client == client && t.eventId == eventId)
if (t.deletePending == false && t.client == client && t.eventId == eventId) {
// JPBS - if we don't reset 'repeat', deletePending will be set again
t.repeat = false;
t.deletePending = true;
break;
}
}
}
}
/**
* Clear out all the dead wood
*/
void purge() {
for (int i = 0; i < tasks.size(); i++) {
TimerTask t = (TimerTask)tasks.elementAt(i);
if (t.deletePending) {
//Diagnostic.out.println("TIMER: purged");
tasks.removeElementAt(i);
i--;
}
}
}
long scan() {
// The value added to the current time determines the MAX time until
// the next scan
// This is 100 now since thread.interrupt() is not implemented
long nextTime = System.currentTimeMillis() + 100;
for (int i = 0; i < tasks.size(); i++) {
TimerTask t = (TimerTask)tasks.elementAt(i);
// if not already deletePending, test (and possibly send the event)
// as a result, the job may be flagged for deletion.
// May also be a non-repeating job and so require self deletion
if (!t.deletePending)
t.test();
// if the task didn't get deleted - see what it contributes to the time
if (!t.deletePending)
nextTime = Math.min(nextTime, t.timeNext);
//Diagnostic.out.println("TIMER: Scanning "+t.eventId+" "+(t.deletePending == true ? "DEL" : ""));
}
return nextTime - System.currentTimeMillis();
}
}
class TimerTask
{
TimerClient client;
int eventId;
long timePrev;
long timeDelay;
long timeNext;
boolean repeat;
boolean deletePending;
public TimerTask(TimerClient client, int eventId, long timeDelay, boolean repeat) {
this.client = client;
this.eventId = eventId;
this.timeDelay = timeDelay;
this.repeat = repeat;
// schedule the next click - now + delay
timeNext = System.currentTimeMillis() + timeDelay;
deletePending = false;
//Diagnostic.out.println("TIMER: Adding New Task");
}
public void test() {
if (System.currentTimeMillis() >= timeNext) {
//Diagnostic.out.println("TIMER: fire");
// Fire the event
client.timerEvent(eventId);
// Update the next time
timeNext = System.currentTimeMillis() + timeDelay;
deletePending = !repeat;
}
}
}
銆
涓嬮潰鏄竴涓嬌鐢ㄤ緥瀛?
TimerTest.java
package com.ly.util;
import java.io.*;
import java.util.*;
import com.ly.util.*;
/**
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company: http://dozb.blogchina.com
* @author dozb
* @version 1.0
*/
public class TimerTest implements TimerClient{
public TimerTest()
{
starttime();
}
public void timerEvent(int id)
{
System.out.println("timerEvent...");
}
public void starttime()
{
TimerCtl.startTimer(this,1,5*1000,true);
}
public void stoptime()
{
TimerCtl.stopTimer(this,1);
}
public static void main(String[] args)
{
new TimerTest();
try
{
Thread.sleep(200000);
}catch(Exception e)
{
}
}
}
閫氳繃榪欑鏂瑰紡錛屽彲浠ラ珮鏁堝湴浣跨敤socket閫氳錛屽湪寮傛socket鐗堟湰娌℃湁鍙戝竷浠ュ墠錛屼笉澶辨槸涓縐嶈В鍐抽棶棰樼殑鏂規硶銆?)