<%
function sqlcheck(Str,errtype)
if Instr(LCase(Str),"select ") > 0 or Instr(LCase(Str),"insert ") > 0 or Instr(LCase(Str),"delete ") > 0 or Instr(LCase(Str),"delete from ") > 0 or Instr(LCase(Str),"count(") > 0 or Instr(LCase(Str),"drop table") > 0 or Instr(LCase(Str),"update ") > 0 or Instr(LCase(Str),"truncate ") > 0 or Instr(LCase(Str),"asc(") > 0 or Instr(LCase(Str),"mid(") > 0 or Instr(LCase(Str),"char(") > 0 or Instr(LCase(Str),"xp_cmdshell") > 0 or Instr(LCase(Str),"exec master") > 0 or Instr(LCase(Str),"net localgroup administrators") > 0 or Instr(LCase(Str),"and ") > 0 or Instr(LCase(Str),"net user") > 0 or Instr(LCase(Str),"or ") > 0 then
Response.write("<script language=javascript>" & vbcrlf & "window.location.href ='ShowError.asp?errtype=" & errtype & "'" & vbcrlf & "</script>")
Response.End
end if
Str=Replace(Str,"_","") '過濾SQL注入_
Str=Replace(Str,"*","") '過濾SQL注入*
Str=Replace(Str," ","") '過濾SQL注入空格
Str=Replace(Str,chr(34),"") '過濾SQL注入"
Str=Replace(Str,chr(39),"") '過濾SQL注入'
Str=Replace(Str,chr(91),"") '過濾SQL注入[
Str=Replace(Str,chr(93),"") '過濾SQL注入]
Str=Replace(Str,chr(37),"") '過濾SQL注入%
Str=Replace(Str,chr(58),"") '過濾SQL注入:
Str=Replace(Str,chr(59),"") '過濾SQL注入;
Str=Replace(Str,chr(43),"") '過濾SQL注入+
Str=Replace(Str,"{","") '過濾SQL注入{
Str=Replace(Str,"}","") '過濾SQL注入}
sqlcheck=Str '返回經過上面字符替換后的Str
end function
%>
function SafeRequest(ParaName,ParaType)
'--- 傳入參數 ---
'ParaName:參數名稱-字符型
'ParaType:參數類型-數字型(1表示以上參數是數字,0表示以上參數為字符)
Dim ParaValue
ParaValue=Request(ParaName)
If ParaType=1 then
If not isNumeric(ParaValue) then
Response.write "參數" & ParaName & "必須為數字型!"
Response.end
End if
Else
ParaValue=replace(ParaValue,"'","''")
End if
SafeRequest=ParaValue
End function
Function SafeRequest(ParaValue,ParaType)
'--- 傳入參數 ---
'ParaName:參數名稱-字符型
'ParaType:參數類型-數字型(1表示以上參數是數字,0表示以上參數為字符)
'Dim ParaValue
'ParaValue=Request(ParaName)函數里面是不要加引號
If ParaType=1 then
If not isNumeric(ParaValue) then
Response.write " 參數" & ParaName & "必須為數字型!"
Response.end
End if
Else
ParaValue=replace(ParaValue,"'","")
ParaValue=replace(ParaValue,";and 1=1","")
ParaValue=replace(ParaValue,";and 1=2","")
ParaValue=replace(ParaValue,";and user>0","")
ParaValue=replace(ParaValue,">","")
ParaValue=replace(ParaValue,"<","")
ParaValue=replace(ParaValue,"=","")
ParaValue=replace(ParaValue,"count","")
ParaValue=replace(ParaValue,"select","")
ParaValue=replace(ParaValue,"drop","")
ParaValue=replace(ParaValue,"delect","")
ParaValue=replace(ParaValue,"insert","")
ParaValue=replace(ParaValue,"execute","")
ParaValue=replace(ParaValue,"update","")
ParaValue=replace(ParaValue,"mid","")
ParaValue=replace(ParaValue,"exec","")
ParaValue=replace(ParaValue,"master","")
ParaValue=replace(ParaValue,"char","")
ParaValue=replace(ParaValue,"declare","")
ParaValue=replace(ParaValue,"*","")
ParaValue=replace(ParaValue,"%","")
ParaValue=replace(ParaValue,"chr","")
ParaValue=replace(ParaValue,"truncate","")
End if
SafeRequest=ParaValue
End function
'調用方式
DirID=Request("DirID")'///數據目錄名稱參數/無則表示全部數據
DirID=SafeRequest(DirID,1)
Dim SQL_inbreakstr
SQL_inbreakstr = "'|or|and|exec|insert|select|delete|update|drop|count|*|%|chr|mid|master|truncate|char|declare"
SQL_inbreak = split(SQL_inbreakstr,"|")
R_Q=Request.QueryString
R_F=Request.Form
IF R_Q<>"" THEN
For i=0 To Ubound(SQL_inbreak)
IF instr(R_Q,SQL_inbreak(i))>0 THEN
Response.Write "*****"
Response.End
END IF
Next
End IF
IF R_F<>"" THEN '--------定義部份------------------ <% For Fy_Xh=0 To Ubound(Fy_Inf) Response.Write "<Script Language=JavaScript>alert('楓網SQL通用防注入系統提示↓\n\n請不要在參數中包含非法字符嘗試注入!\n\nHTTP://WwW.WrSkY.CoM 系統版本:V2.0(ASP)完美版');</Script>" Next '--------GET部份------------------- For Fy_Xh=0 To Ubound(Fy_Inf) Response.Write "<Script Language=JavaScript>alert('楓網SQL通用防注入系統提示↓\n\n請不要在參數中包含非法字符嘗試注入!\n\nHTTP://WwW.WrSkY.CoM 系統版本:V2.0(ASP)完美版');</Script>"
For i=0 To Ubound(SQL_inbreak)
IF instr(R_F,SQL_inbreak(i))>0 THEN
Response.Write "*****"
Response.End
END IF
Next
END IF
<%
'--------版權說明------------------
'SQL通用防注入程序 V2.0 完美版
'本程序由 火狐-楓知秋 獨立開發
'對本程序有任何疑問請聯系本人
'QQ:613548
Dim Fy_Post,Fy_Get,Fy_In,Fy_Inf,Fy_Xh,Fy_db,Fy_dbstr
'自定義需要過濾的字串,用 "楓" 分隔
Fy_In = "'楓;楓and楓exec楓insert楓select楓delete楓update楓count楓*楓%楓chr楓mid楓master楓truncate楓char楓declare"
'----------------------------------
%>
Fy_Inf = split(Fy_In,"楓")
'--------POST部份------------------
If Request.Form<>"" Then
For Each Fy_Post In Request.Form
If Instr(LCase(Request.Form(Fy_Post)),Fy_Inf(Fy_Xh))<>0 Then
'--------寫入數據庫-------頭--------
Fy_dbstr="DBQ="+server.mappath("SqlIn.mdb")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
Set Fy_db=Server.CreateObject("ADODB.CONNECTION")
Fy_db.open Fy_dbstr
Fy_db.Execute("insert into SqlIn(Sqlin_IP,SqlIn_Web,SqlIn_FS,SqlIn_CS,SqlIn_SJ) values('"&Request.ServerVariables("REMOTE_ADDR")&"','"&Request.ServerVariables("URL")&"','POST','"&Fy_Post&"','"&replace(Request.Form(Fy_Post),"'","''")&"')")
Fy_db.close
Set Fy_db = Nothing
'--------寫入數據庫-------尾--------
Response.Write "非法操作!系統做了如下記錄↓<br>"
Response.Write "操作IP:"&Request.ServerVariables("REMOTE_ADDR")&"<br>"
Response.Write "操作時間:"&Now&"<br>"
Response.Write "操作頁面:"&Request.ServerVariables("URL")&"<br>"
Response.Write "提交方式:POST<br>"
Response.Write "提交參數:"&Fy_Post&"<br>"
Response.Write "提交數據:"&Request.Form(Fy_Post)
Response.End
End If
Next
End If
'----------------------------------
If Request.QueryString<>"" Then
For Each Fy_Get In Request.QueryString
If Instr(LCase(Request.QueryString(Fy_Get)),Fy_Inf(Fy_Xh))<>0 Then
''--------寫入數據庫-------頭--------
Fy_dbstr="DBQ="+server.mappath("SqlIn.mdb")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"
Set Fy_db=Server.CreateObject("ADODB.CONNECTION")
Fy_db.open Fy_dbstr
Fy_db.Execute("insert into SqlIn(Sqlin_IP,SqlIn_Web,SqlIn_FS,SqlIn_CS,SqlIn_SJ) values('"&Request.ServerVariables("REMOTE_ADDR")&"','"&Request.ServerVariables("URL")&"','GET','"&Fy_Get&"','"&replace(Request.QueryString(Fy_Get),"'","''")&"')")
Fy_db.close
Set Fy_db = Nothing
'--------寫入數據庫-------尾--------
Response.Write "非法操作!系統做了如下記錄↓<br>"
Response.Write "操作IP:"&Request.ServerVariables("REMOTE_ADDR")&"<br>"
Response.Write "操作時間:"&Now&"<br>"
Response.Write "操作頁面:"&Request.ServerVariables("URL")&"<br>"
Response.Write "提交方式:GET<br>"
Response.Write "提交參數:"&Fy_Get&"<br>"
Response.Write "提交數據:"&Request.QueryString(Fy_Get)
Response.End
End If
Next
Next
End If
'----------------------------------
%>
可以防止所有得sql注入:
Function SafeRequest(ParaName,ParaType)
'--- 防止SQL注入 ---
'ParaName:參數名稱-字符型
'ParaType:參數類型-數字型(1表示以上參數是數字,0表示以上參數為字符)
Dim ParaValue
ParaValue=Request(ParaName)
If ParaType=1 then
If not isNumeric(ParaValue) then
Response.write "<br><br><br><center><font color=red>參數" & ParaName & "必須為數字型!"
Response.end
End if
Else
ParaValue=replace(ParaValue,"'","''")
End if
SafeRequest=ParaValue
End function
來源:http://www.yesky.com/305/1899305.shtml
|
/*
* Created on 2005-9-27
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package fibernews.action;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import fibernews.framework.db.*;
import fibernews.beans.Employee;
import fibernews.util.function.HandleString;
import fibernews.framework.logging.Logger;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ListEmpAction extends Action {
List list ;
public String process(HttpServletRequest request, HttpServletResponse response) {
Connection conn=DBHelper.getConnection();
Statement st=null;
PreparedStatement pst=null;
ResultSet rs=null ;
String query=HandleString.toChinese(request.getParameter("query"));
if ((query==null)||query.trim().equals("")) query="lmsun";
try{
String sql="select * from employee_email where name like '%"+query+"%' or email like '%"+query+"%'" ;
//st=conn.createStatement();
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
list=new ArrayList();
Employee emp;
while (rs.next()){
emp=new Employee();
emp.setId(rs.getString("id"));
emp.setEmployee_bh(rs.getString("employee_bh"));
emp.setName(rs.getString("name"));
emp.setEmail(rs.getString("email"));
emp.setDepartment1(rs.getString("department1"));
emp.setDepartment2(rs.getString("department2"));
emp.setDepartment3(rs.getString("department3"));
list.add(emp);
}
}
catch (Exception e) {
System.out.println("Error Connecting to catalog DB: " + e.toString());
}
finally {
DBHelper.close(rs,pst,conn);
}
request.setAttribute("empList",list);
return "/intra/query/emailbook.jsp";
}
public static void main(String[] args)
{
ListEmpAction empaction = new ListEmpAction();
System.out.print("End");
}
}
|
|
問題: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);
}