問題:JavaBean的一個寫文件方法,獨立調試正常。但移到Struts下,通過Action調用時,
拋出異常。
原因:文件路徑問題
解決方法:
1.修改原來JavaBean里帶前綴路徑的文件---"resources/users.properties"
為"users.properties"
2.將struts框架下的源文件users.properties,直接移到src下
3.重新編譯,部署
4.運行這個注冊組件成功后,可以到$服務器主目錄$/bin下,查看這個已經寫過的
users.properties文件
以上問題,曾嘗試將resources/user.properite改為絕對路徑"d:/users.properties",
或改為相對路徑"/resources/properties",或直接向JavaBean中傳入路徑參數path,
path=request.getRealPath("")(或request.getContextPath)等,均沒有調試成功。
故記錄下來,希望其它網友遇到時,不必再做這樣的重復勞動。
附:
1.Action中調用方法:
UserDirectory.getInstance().setUser(userName,password1);
2.JavaBean的縮略代碼:
UserDirectory.java
import java.io.IOException;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;
public class UserDirectory {
private static final String UserDirectoryFile = "users.properties";
private static final String UserDirectoryHeader = "${user}=${password}";
public static UserDirectory getInstance() throws UserDirectoryException {
if (null == userDirectory) {
userDirectory = new UserDirectory();
}
return userDirectory;
}
public void setUser(String userId, String password) throws
UserDirectoryException {
if ( (null == userId) || (null == password)) {
throw new UserDirectoryException();
}try {
p.put(fixId(userId), password);
p.store(new FileOutputStream(UserDirectoryFile),UserDirectoryHeader);
}catch (IOException e) {
throw new UserDirectoryException();
}
}
}
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.
字符串與基本數據類型的轉換間的轉換必須使用JSP中的對象函數
Boolean.getBoolean(String)
Byte.parseByte(String)
Short.parseShort(String)
Integer.parseInt(String)
Long.parseLong(String)
Float.parseDouble(String)
Double.parseDouble(String)
String.valueOF(數據)
Array
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 |
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]);
1、Message.java
public class Message {
public static void main(String[] args) {
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
System.out.println("!");
}
}
test:
java Message -g cruel world
import java.util.*;
import javax.swing.*;
public class FirstSample {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog
("How many numbers do you need to draw?");
int k = Integer.parseInt(input);
input = JOptionPane.showInputDialog
("What is the highest number you can draw?");
int n = Integer.parseInt(input);
// fill an array with numbers 1 2 3 . . . n
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
{ numbers[i] = i + 1;
System.out.println(numbers[i]);
}
// draw k numbers and put them into a second array
int[] result = new int[k];
for (int i = 0; i < result.length; i++)
{
// make a random index between 0 and n - 1
int r = (int)(Math.random() * n);
// pick the element at the random location
result[i] = numbers[r];
// move the last element into the random location
numbers[r] = numbers[n - 1];
n--;
}
// print the sorted array
Arrays.sort(result);
System.out.println
("Bet the following combination. It'll make you rich!");
for (int i = 0; i < result.length; i++)
System.out.println(result[i]);
System.exit(0);
}
}
The include Directive
The following is the syntax for the include directive:
<%@ include file="relativeURL" %>
As you can see the directive accepts a single file attribute that is used to indicate the resource whose content is to be included in the declaring JSP. The file attribute is interpreted as a relative URL; if it starts with a slash it's interpreted as relative to the context of the web application (namely a context-relative path), otherwise it's interpreted as relative to the path of the JSP that contains the include directive (namely a page relative path). The included file may contain either static content, such as HTML or XML, or another JSP page.
For example:
<%@ include file="/copyright.html"%>
Let's consider a real-world example of such a templating mechanism that utilizes the include directive to provide a consistent page layout for a web application.
Consider the following two JSP pages:
Header.jsp
<html>
<head><title>A Very Simple Example</title></head>
<body style="font-family:verdana,arial;font-size:10pt;">
<table width="100%" height="100%">
<tr bgcolor="#99CCCC">
<td align="right" height="15%">Welcome to this example...</td>
</tr>
<tr>
<td height="75%">
Footer.jsp
</td>
</tr>
<tr bgcolor=" #99CC99">
<td align="center" height="10%">Copyright ACompany.com 2003</td>
</tr>
</table>
</body>
</html>
As you can see, Header.jsp declares the starting elements of an HTML table that is to be 100 percent of the size of the page and has two rows, whereas Footer.jsp simply declares the closing elements for the table. Used separately, either JSP will result in partial HTML code that will look very strange to a user but when they're combined using the include directive it's easy to create consistent pages as part of a web application.
Let's see just how simple this basic template mechanism is to use:
Content.jsp
<%@ include file='./Header.jsp'%>
<p align="center">The Content Goes Here...!!!</p>
<%@ include file='./Footer.jsp'%>
2、
date.jsp
<html>
<body>
<h2>Greetings!</h2>
<P>The current time is <%=new java.util.Date()%> precisely
</body>
</html>
3、
dateBean.jsp
<html>
<head><title>Professional JSP, 3rd Edition</title></head>
<body style="font-family:verdana;font-size:10pt;">
<jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
<h2>Today's date is <%= date.getDate() %></h2>
</body>
</html>
或:
dateBean_getProperty.jsp
<html>
<head><title>Professional JSP, 3rd Edition</title></head>
<body style="font-family:verdana;font-size:10pt;">
<jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
<h2>Today's date is <jsp:getProperty name="date" property="date"/></h2>
</body>
</html>
dateBean_setProperty.jsp
<html>
<head><title>Professional JSP, 3rd Edition</title></head>
<body style="font-family:verdana;font-size:10pt;">
<jsp:useBean id="date" class="com.apress.projsp20.ch01.DateFormatBean"/>
<jsp:setProperty name="date" property="format"
value="EEE, d MMM yyyy HH:mm:ss z"/>
<h2>Today's date is <jsp:getProperty name="date" property="date"/></h2>
</body>
</html>
其中DateFormatBean.java:
package com.apress.projsp20.ch01;
import java.util.Date;
import java.text.*;
public class DateFormatBean {
private DateFormat dateFormat;
private Date date;
public DateFormatBean() {
dateFormat = DateFormat.getInstance();
date = new Date();
}
public String getDate() {
return dateFormat.format(date);
}
public void setDate(Date date) {
this.date = date;
}
public void setFormat(String format) {
this.dateFormat = new SimpleDateFormat(format);
}
}
例:SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DBPhoneLookupReuse.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
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();
}
}
1、NTLM can be done with JCIFS and without HTTP. Only a few lines of code are required in the code of your servlet:
InetAddress ip = InetAddress.getByName(”192.168.0.1.”); // ip address of your windows controller
UniAddress myDomain = new UniAddress(ip);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(”MYDOMAIN”, “mylogin”, “mypasword”);
SmbSession.logon(myDomain, auth);
If an exception is triggered, the controller didn’t like the login and the password
2、Http方式下web.xml中filter的配置:
<?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>
//import java.text.*;
//import java.util.*;
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);
}