◎system.in,system.out是标准的系统输入输出,是通过键盘敲击反映在msdos中,可以通过一下方法来
重新导向,使得以后的系统输入输出都反映在文件,或socket中都可以,具体的操作方法:
例子:
package com.j2eeapp.ch17;
import java.io.*;
import java.lang.Exception;
public class TestOutput
{
public static void redirect(InputStream in,PrintStream out)
{
System.setIn(in);
System.setOut(out);
System.setErr(out);
}
public static void main(String []args) throws FileNotFoundException,IOException
{
BufferedInputStream in=new BufferedInputStream(
new FileInputStream("TestOutput.java")
);
PrintStream out=new PrintStream(
new BufferedOutputStream(
new FileOutputStream("test.out")
)
);
System.out.println("It will print all the thing to console and input from keyboard before export");
redirect(in,out);
System.out.println("After export,both input and output all from file ");
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in)
);
String s;
while((s=br.readLine())!=null)
{
System.out.println(s);
}
out.close();
}
}
◎一个实现command模式的例子,充分体现了接口一致性的概念,比如说一个工具A有打印的命令,另外一个工具
B也有打印的命令,但是两者所执行的操作都是打印,其具体实现不一样,那就完全可以将其抽象出来进行使用
使其具有一致性。
例子:
package com.j2eeapp.ch13;
import java.awt.*;
import java.awt.event.*;
interface Command
{
public void execute();
}
public class SampleGUI extends Frame implements ActionListener
{
private Label label=new Label();
private HelloCommand helloCommand;
private TimeCommand timeCommand;
public SampleGUI()
{
super("a command test");
timeCommand=new TimeCommand("show time",label);
helloCommand=new HelloCommand("show hello",label);
setLayout(new FlowLayout());
add(label);
add(timeCommand);
add(helloCommand);
timeCommand.addActionListener(this);
helloCommand.addActionListener(this);
setSize(300,100);
show();
}
public void actionPerformed(ActionEvent e)
{
Command command=(Command)e.getSource();
command.execute();
}
public static void main(String args[])
{
new SampleGUI();
}
}
class HelloCommand extends Button implements Command
{
private Label label;
public HelloCommand(String name,Label label)
{
super(name);
this.label=label;
}
public void execute()
{
label.setText("Hello");
}
}
class TimeCommand extends Button implements Command
{
private Label label;
public TimeCommand(String name,Label label)
{
super(name);
this.label=label;
}
public void execute()
{
label.setText(new java.util.Date().toString());
}
}
◎command模式的一个实例制作一个shell程序,shell中有很多的命令,然后很多的命令也可以在其他程序
中进行使用比如另外一个shell,那么定义一个command接口,该shell就可以实现该接口的方法,然后进行
统一性的操作。
例子:
//该程序可以通过在msdos下敲打notepad或explorer来执行相应的程序,相应的类都实现了command接口的
//execute()
***********Command.java**********
package com.j2eeapp.ch17;
import java.util.*;
interface Command
{
public void execute(Vector v) throws java.io.IOException;
}
***********Command.java**********
***********notepad.java**********
package com.j2eeapp.ch17;
import java.util.*;
import java.io.*;
import com.j2eeapp.ch17.Command;
public class notepad implements Command
{
public void execute(Vector v)throws java.io.IOException
{
Runtime.getRuntime().exec("notepad");
System.out.println("***************");
Iterator i=v.iterator();
System.out.println(v.size());
while(i.hasNext())
{
System.out.println((String)i.next());
}
System.out.println("***************");
}
}
***********notepad.java**********
***********JShell.java**********
package com.j2eeapp.ch17;
import java.util.*;
import java.io.*;
public class JShell
{
private static Hashtable COMMAND_TABLE=new Hashtable();
private static String PROMPT="$";
private static boolean RUNNING=true;
private static void execute(Command c,Vector v)
{
if(c==null)
{
System.out.println("command vaild ,it only Notepad and Explorer invaild");
return;
}
try
{
c.execute(v);
}
catch(Exception ce)
{
System.out.println(ce.getMessage());
}
}
private static void execute(String s,Vector v)
{
execute(loadCommand(s),v);
}
public static Command loadCommand(String commandName)
{
Command theCommand=null;
if(COMMAND_TABLE.containsKey(commandName))
{
theCommand=(Command)COMMAND_TABLE.get(commandName);
return theCommand;
}
try
{
Class commandInterface=Class.forName("com.j2eeapp.ch17.Command");
Class commandClass=Class.forName("com.j2eeapp.ch17."+commandName);
if(!(commandInterface.isAssignableFrom(commandClass)))
{
System.out.println("["+commandName+"]:Not a Command");
}
else
{
theCommand=(Command)commandClass.newInstance();
COMMAND_TABLE.put(commandName,theCommand);
return theCommand;
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println("["+commandName+"]:Have't find this Command");
}
catch(IllegalAccessException iae)
{
System.out.println("["+commandName+"]:Illegal Access");
}
catch(InstantiationException ie)
{
System.out.println("["+commandName+"]:Command cannot be instantiated");
}
finally
{
return theCommand;
}
}
private static void readInput()
{
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in)
);
try
{
while(RUNNING)
{
System.out.println(PROMPT+"%");
StringTokenizer tokenizer=new StringTokenizer(br.readLine());
Vector remainingArgs=new Vector();
String commandToken="";
if(tokenizer.hasMoreTokens())
{
commandToken=tokenizer.nextToken();
while(tokenizer.hasMoreTokens())
{
remainingArgs.addElement(tokenizer.nextToken());
}
}
if(!commandToken.equals(""))
{
execute(commandToken,remainingArgs);
}
}
}
catch(java.io.IOException ioe)
{
System.out.println("it found I/O exception when read inputstream");
}
}
public static void main(String args[])
{
System.out.println("*************JShell*************");
System.out.println("*** by huangzh ***");
System.out.println("*************JShell*************");
System.out.println("you can execute windows shell command in JSehll");
JShell.readInput();
System.out.println("exiting....");
}
}
***********JShell.java**********
***********explorer.java**********
package com.j2eeapp.ch17;
import java.util.*;
import java.io.*;
import com.j2eeapp.ch17.Command;
public class explorer implements Command
{
public void execute(Vector v)throws java.io.IOException
{
Runtime.getRuntime().exec("explorer");
/*
System.out.println("***************");
Iterator i=v.iterator();
System.out.println(v.size());
while(i.hasNext())
{
System.out.println((String)i.next());
}
System.out.println("***************");
*/
}
}
***********explorer.java**********
◎轻量级组件会被重量级的组件所覆盖,swing的组件就有可能被awt的组件所覆盖
◎一个简单的swing例子:
package com.j2eeapp.ch17;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SwingGUI
{
JFrame topLevel;
JPanel jPanel;
Container contentPane;
JLabel jLabel;
JTextField jTextField;
JList jList;
JComboBox jcomboBox;
JToggleButton togBtn;
JCheckBox chkbox;
JTextArea textArea;
JPasswordField pswd;
JProgressBar prog;
JSlider slider;
JSeparator separator;
JTable table;
JTree tree;
JScrollPane sp;
JDialog dialog;
JMenuBar mnuBar;
JMenu mnuFile;
JMenuItem mnuItem;
JPopupMenu popup;
JToolBar tb;
Object listData[]={new String("First selection"),new String("Second selection"),
new String("Thrid selection")
};
public static void main(String args[])
{
SwingGUI swingGUI=new SwingGUI();
swingGUI.go();
}
public void go()
{
topLevel=new JFrame("Swing GUI");
jPanel=new JPanel();
jTextField=new JTextField(20);
jList=new JList(listData);
jcomboBox=new JComboBox(listData);
jLabel=new JLabel("test");
togBtn=new JToggleButton("tgo",true);
chkbox=new JCheckBox("checked",true);
textArea=new JTextArea("textarea",5,5);
pswd=new JPasswordField(8);
prog=new JProgressBar(JProgressBar.HORIZONTAL);
slider=new JSlider();
separator=new JSeparator(JSeparator.VERTICAL);
table=new JTable(5,5);
sp=new JScrollPane();
dialog=new JDialog(topLevel,"dialog",true);
mnuBar=new JMenuBar();
mnuFile=new JMenu("File");
tb=new JToolBar();
tree=new JTree(listData);
popup=new JPopupMenu();
sp.getViewport().add(textArea);
tb.add(new JButton("New"));
tb.add(new JMenuItem("Save"));
mnuFile.add(new JMenuItem("Open"));
mnuFile.add(new JMenuItem("Save"));
mnuFile.add(new JMenuItem("Exit"));
mnuBar.add(mnuFile);
popup.add(new JMenuItem("Copy"));
popup.add(new JMenuItem("Paste"));
contentPane=topLevel.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(jLabel,BorderLayout.SOUTH);
jPanel.setLayout(new FlowLayout());
jPanel.add(jTextField);
jPanel.add(jcomboBox);
jPanel.add(togBtn);
jPanel.add(chkbox);
jPanel.add(pswd);
jPanel.add(prog);
jPanel.add(slider);
jPanel.add(separator);
jPanel.add(table);
jPanel.add(tree);
jPanel.add(jList);
jPanel.add(sp);
contentPane.add(jPanel,BorderLayout.CENTER);
contentPane.add(tb,BorderLayout.NORTH);
topLevel.setJMenuBar(mnuBar);
topLevel.addMouseListener(
new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
popup.show(topLevel,e.getX(),e.getY());
}
}
);
dialog.show();
topLevel.pack();
topLevel.setVisible(true);
}
}
◎使用监听器可以将listener写在类的里面如果有相同类对象需要实现不同的方法,可以在listener中根据
相应的名称,属性等进行判断然后来让各相关对象共同使用该actionlistener
例子:
ActionListener a1=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String action=((JMenuItem)e.getSource()).getText();
if(action=="copy")
copy();
if(action=="paste")
paste();
if(action=="cut")
cut();
}
};
for(int i=0;i<popEdit.length;i++)
{
popEdit[i].addActionListener(a1);
popup.add(popEdit[i]);
}
以上方法就是使得各菜单使用一个actionlistener完成了不同的功能
◎也可以使用内部类来使用listener
例子:
btn.addMouseListener(new ButtonListener());
class ButtonListener extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
tp.setText("");
}
}
◎想将文字复制到剪贴板,可以使用JFrame.gettoolkit->返回一个toolkit
toolkit.getSystemClipboard()->返回一个clipboard
clipboard.setContent()->设置剪贴板的内容
想将文字粘贴到其他地方,比如textfield,textArea等可以使用
JTextArea tp=new JTextArea(10,10);
Transferable clipData=clipbd.getContents(EventTest.this);//从eventTest frame中获得clipboard->返回一个Transferable对象
String clipString=(String)clipData.getTransferData(DataFlavor.stringFlavor)//从Transferable对象根据剪贴板的内容获得相应的对象,需要强转
tp.replaceRange(clipString,tp.getSelectionStart(),tp.getSelectionEnd());//将剪贴板中的内容进行相应的粘贴
◎
◎
◎
◎
◎
◎关于事件监听器的例子,一个关于在textarea中进行剪切,复制,删除等的操作,其中用到了内部类进行
事件监听器的方法,也采用了在类中定义listener两种方法的综合实例:
package com.j2eeapp.ch17;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import java.io.*;
import java.awt.datatransfer.*;
public class EventTest extends JFrame
{
JMenuItem[] popEdit={
new JMenuItem("copy"),
new JMenuItem("paste"),
new JMenuItem("cut")
};
JPopupMenu popup=new JPopupMenu();
JTextArea tp=new JTextArea(10,10);
Clipboard clipbd=getToolkit().getSystemClipboard();
JButton btn=new JButton("Delete All");
public void init()
{
ActionListener a1=new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String action=((JMenuItem)e.getSource()).getText();
if(action=="copy")
copy();
if(action=="paste")
paste();
if(action=="cut")
cut();
}
};
for(int i=0;i<popEdit.length;i++)
{
popEdit[i].addActionListener(a1);
popup.add(popEdit[i]);
}
btn.addMouseListener(new ButtonListener());
PopupListener p1=new PopupListener();
addMouseListener(p1);
tp.addMouseListener(p1);
tp.setSelectedTextColor(Color.red);
Container cp=getContentPane();
cp.add(BorderLayout.SOUTH,new JScrollPane(
tp,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
));
cp.add(btn);
}
public void copy()
{
String selection=tp.getSelectedText();
if(selection==null)
{
return;
}
StringSelection clipString=new StringSelection(selection);
clipbd.setContents(clipString,clipString);
}
public void paste()
{
Transferable clipData=clipbd.getContents(EventTest.this);
try
{
String clipString=(String)clipData.getTransferData(DataFlavor.stringFlavor);
tp.replaceRange(clipString,tp.getSelectionStart(),tp.getSelectionEnd());
}
catch(Exception e)
{
System.err.println("Not String flavor");
}
}
public void cut()
{
String selection=tp.getSelectedText();
if(selection==null)
{
return;
}
StringSelection clipString=new StringSelection(selection);
clipbd.setContents(clipString,clipString);
tp.replaceRange("",tp.getSelectionStart(),tp.getSelectionEnd());
}
class PopupListener extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e)
{
maybeShowPopup(e);
}
public void maybeShowPopup(MouseEvent e)
{
if(e.isPopupTrigger())
{
popup.show(e.getComponent(),e.getX(),e.getY());
}
}
}
class ButtonListener extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
tp.setText("");
}
}
public static void main(String args[])
{
EventTest test=new EventTest();
test.setSize(400,250);
test.init();
test.show();
}
}
◎applet中调用html参数的实例:
***********AppletDemo.java**********
package com.j2eeapp.ch17;
import java.applet.*;
import java.awt.*;
public class AppletDemo extends Applet
{
String img;
public void paint(Graphics g)
{
Image image=getImage(getCodeBase(),img);
g.drawImage(image,0,0,200,200,this);
g.setColor(Color.blue);
g.setFont(new Font("arial",2,24));
g.drawString("Applet Demo",40,170);
g.setFont(new Font("NewsRoman",2,10));
g.setColor(Color.pink);
g.drawString(new java.util.Date().toString(),10,190);
}
public void init()
{
getParam();
}
public void getParam()
{
img=getParameter("image");
}
public void start()
{
}
public void destory()
{
}
}
***********AppletDemo.java**********
***********Applet.html**********
<html>
<head>
<tilte>this is a applet demo</tilte>
</head>
<body>
<center>
==there is insert applet in html files==<br>
<applet code="com.j2eeapp.ch17.AppletDemo.class" width="200" height="200">
<param name=image value="Blue hills.jpg">
</applet>
</center>
</body>
</html>
***********Applet.html**********
◎在tomcat中增加一个webapp的方法:
在tomcat中再增加一个webapp需要修改tomcat的conf目录,为其增加一个context
例子:增加一个j2ee的webapp
<Context path="/j2ee" docBase="j2ee" debug="0" reloadable="true" />
设置realoadable,是在tomcat不重新启动的情况下,修改了jsp文件,则马上可以通过刷新或重新访问
该文件来显示效果
◎在tomcat中使用datasource连接数据库的方法:配置server.xml,web.xml,程序中创建
context->context为javax.name.*中的类
javax.name.Context提供了查找JNDI Resource的接口
Context ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/BookDB");
Connection con=ds.getConnection();
----
con.close();
例子:
配置server.xml
***********server.xml片断**********
Context path="/bookstore" docBase="bookstore" debug="0"
reloadable="true" >
<Resource name="jdbc/BookDB"
auth="Container"
type="javax.sql.DataSource" />
<ResourceParams name="jdbc/BookDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>dbuser</value>
</parameter>
<parameter>
<name>password</name>
<value>1234</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/BookDB?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>
***********server.xml片断**********
配置web.xml
***********web.xml**********
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
'-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'>
<web-app>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
***********web.xml**********
程序中创建
***********DbJsp1.jsp**********
<!--首先导入一些必要的packages-->
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="com.mysql.jdbc.Connection"%>
<!--设置中文输出-->
<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head>
<title>DbJsp1.jsp</title>
</head>
<body>
<%
//以try开始
try
{
java.sql.Connection con;
Statement stmt;
ResultSet rs;
//建立数据库连接
Context ctx = new InitialContext();
DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/BookDB");
con = ds.getConnection();
//创建一个JDBC声明
stmt = con.createStatement();
//增加新记录
stmt.executeUpdate("INSERT INTO books (id,name,title,price) VALUES ('999','Tom','Tomcat Bible',44.5)");
//查询记录
rs = stmt.executeQuery("SELECT id,name,title,price from books");
//输出查询结果
out.println("<table border=1 width=400>");
while (rs.next())
{
String col1 = rs.getString(1);
String col2 = rs.getString(2);
String col3 = rs.getString(3);
float col4 = rs.getFloat(4);
//convert character encoding
col1=new String(col1.getBytes("ISO-8859-1"),"GB2312");
col2=new String(col2.getBytes("ISO-8859-1"),"GB2312");
col3=new String(col3.getBytes("ISO-8859-1"),"GB2312");
//打印所显示的数据
out.println("<tr><td>"+col1+"</td><td>"+col2+"</td><td>"+col3+"</td><td>"+col4+"</td></tr>");
}
out.println("</table>");
//删除新增加的记录
stmt.executeUpdate("DELETE FROM books WHERE id='999'");
//关闭数据库连结
rs.close();
stmt.close();
con.close();
}
//捕获错误信息
catch (Exception e) {out.println(e.getMessage());}
%>
</body>
</html>
***********DbJsp1.jsp**********
◎session在浏览器关闭之后,则所有存储的东西全部消失
一个session的例子:邮件的登陆登出
***********mailcheck.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>
checkmail
</title>
</head>
<body>
<%
String name=null;
name=request.getParameter("username");
if(name!=null)session.setAttribute("username",name);
%>
<a href="maillogin.jsp">登录</a>
<a href="maillogout.jsp">注销</a>
<p>当前用户为:<%=name%> </P>
<P>你的信箱中有100封邮件</P>
</body>
</html>
***********mailcheck.jsp**********
***********maillogin.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>helloapp</title>
</head>
<body bgcolor="#FFFFFF" onLoad="document.loginForm.username.focus()">
<%
String name="";
if(!session.isNew()){
name=(String)session.getAttribute("username");
if(name==null)name="";
}
%>
<p>欢迎光临邮件系统</p>
<p>Session ID:<%=session.getId()%></p>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<form name="loginForm" method="post" action="mailcheck.jsp">
<tr>
<td width="401"><div align="right">User Name: </div></td>
<td width="399"><input type="text" name="username" value=<%=name%>></td>
</tr>
<tr>
<td width="401"><div align="right">Password: </div></td>
<td width="399"><input type="password" name="password"></td>
</tr>
<tr>
<td width="401"> </td>
<td width="399"><br><input type="Submit" name="Submit" value="提交"></td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
***********maillogin.jsp**********
***********maillogout.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>
maillogout
</title>
</head>
<body>
<%
String name=(String)session.getAttribute("username");
session.invalidate(); %>
<%=name%>,再见!
<p>
<p>
<a href="maillogin.jsp">重新登录邮件系统</a>
</body>
</html>
***********maillogout.jsp**********
◎使用encodeURL的方法可以使得当用户在关闭cookie的时候仍然可以跟踪用户的会话
***********maillogin.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>helloapp</title>
</head>
<body bgcolor="#FFFFFF" onLoad="document.loginForm.username.focus()">
<%
String name="";
if(!session.isNew()){
name=(String)session.getAttribute("username");
if(name==null)name="";
}
%>
<p>欢迎光临邮件系统</p>
<p>Session ID:<%=session.getId()%></p>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<form name="loginForm" method="post" action="<%=response.encodeURL("mailcheck.jsp")%>">
<tr>
<td width="401"><div align="right">User Name: </div></td>
<td width="399"><input type="text" name="username" value=<%=name%>></td>
</tr>
<tr>
<td width="401"><div align="right">Password: </div></td>
<td width="399"><input type="password" name="password"></td>
</tr>
<tr>
<td width="401"> </td>
<td width="399"><br><input type="Submit" name="Submit" value="提交"></td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
***********maillogin.jsp**********
***********mailcheck.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>
checkmail
</title>
</head>
<body>
<%
String name=null;
name=request.getParameter("username");
if(name!=null)session.setAttribute("username",name);
%>
<a href="<%=response.encodeURL("maillogin.jsp")%>">登录</a>
<a href="<%=response.encodeURL("maillogout.jsp")%>">注销</a>
<p>当前用户为:<%=name%> </P>
<P>你的信箱中有100封邮件</P>
</body>
</html>
***********mailcheck.jsp**********
***********maillogout.jsp**********
<%@ page contentType="text/html; charset=GB2312" %>
<%@ page session="true" %>
<html>
<head>
<title>maillogout</title>
</head>
<body>
<%
String name=(String)session.getAttribute("username");
session.invalidate();
%>
<%=name%>,再见!
<p>
<p>
<a href="<%=response.encodeURL("maillogin.jsp")%>">重新登录邮件系统</a>
</body>
</html>
***********maillogout.jsp**********
◎当采用session得时候,tomcat会自动将在内存中的session存储到<catalina>/work/appname/目录中
◎tomcat中实现持序化的类为org.apache.catalina.session.PersistentManager
◎要实现持序化需要修改server.xml,添加如下代码:
<Manager className="org.apache.catalina.session.PersistentManager" >
debug=0;
saveOnRestart="true"
maxActiveSessions="-1"
minIdleSwap="-1"
maxIdleSwap="-1"
maxIdleBackup="-1"
<Store className="org.apache.catalina.session.FileStore" directory="mydir" />
</Manager>
Manager元素专门用于配置Session Manager,它的子元素<store>指定了实现持久化Session Store的类和
存放Session文件的目录
◎JDBCStore将httpsession对象保存在一张表中
◎可以将httpsession保存在数据库中
如下实例:步骤为在server.xml中配置Manager,将store标签该为数据库的类,创建数据库与数据表,建立server.xml与
数据表的对应关系,则实现了数据库的持序化:
*****************server.xml片断*****************
<Context path="/mail1" docBase="mail1" debug="0" reloadable="true" >
<Manager className="org.apache.catalina.session.PersistentManager" >
debug=99;
saveOnRestart="true"
maxActiveSessions="-1"
minIdleSwap="-1"
maxIdleSwap="-1"
maxIdleBackup="-1"
<Store className="org.apache.catalina.session.JDBCStore"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/tomcatsessionDB?user=dbuser;password=1234"
sessionTable="tomcat_sessions"
sessionIdCol="session_id"
sessionDataCol="session_data"
sessionValidCol="valid_session"
sessionMaxInactiveCol="max_inactive"
sessionLastAccessedCol="last_access"
sessionAppCol="app_name"
checkInterval="60"
debug="99"
/>
</Manager>
</Context>
*****************server.xml片断*****************
*****************建立数据表*****************
tomcatsessionDB数据库中:
数据表的建立
create table tomcat_sessions (
session_id varchar(100) not null primary key,
valid_session char(1) not null,
max_inactive int not null,
last_access bigint not null,
app_name varchar(255),
session_data mediumblob,
KEY kapp_name(app_name)
);
*****************建立数据表*****************
◎javabean类必须似一个public的类,javabean有一个不带参数的构造方法,
javabean通过getXXX方法来获取属性,通过setXXX方法来设置属性
◎page范围:每次访问该页面都会创建一个javabean
request范围:每次访问该页面都会创建一个javabean,当该bean的有效期在于http的响应给客户端,如果
当前页面包含了其他页面,并将request给其他页面,那么只有这两个页面都关闭,javabean则
被销毁。(javabean对象作为属性保存在HttpRequest对象中,属性名为javaBean的id,属性值为JavaBean对象)
session范围:同一个浏览器访问该页面都在同一个session中,不同浏览器打开同一个jsp,该session不同,所反映出来的值也不同,再
打开相同浏览器则会再原有基础上增加(javabean对象作为属性保存在HttpSession对象中,属性名为javaBean的id,属性值为JavaBean对象)
application范围:不同浏览器之间共享着同一个javabean,再打开的窗口都会再该原有javabean的基础上增加
◎session是存在于browser中的,
◎jsp规范中定义了jstl的规范库
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
{
◎在配置oracle的jdbc到jbuilder时会出现关于network adapter io error的错误
◎DataFlavor类的用处是什么?关于数据格式相关的吗?
◎如果我在jboss下发布一个网页,仅带有一个jsp文件是不是也要带有web-inf目录呢
◎为什么有时我加入到jboss中或者tomcat中的web应用程序总是不能访问,但以前的web应用程序可以,我用war的格式导入的,是否还需要修改server.xml
添加context,我觉得这太麻烦了,有没有简单的解决的方法
◎为什么我用weblogic7.0配jbuilder9自带的数据库Jdatastore的connection pool就配不成功,但是
weblogic8.1配就能成功,我安装飞思书上一摸一样的作就是不行?有谁做过?
◎pagecontext与application即servletcontext有是么不同·
◎如何有效使用cookie,商业化代码查看
◎如何使用隐藏字段进行会话跟踪
◎在mysql无需配置连接池,datasource,只要webapp通过配置server.xml以及web.xml就可以达到通过datasource从
连接池中得到connection的效果?
◎javabean不需要在web.xml中进行描述吗?只需要在jsp文件中进行添加usebean标签,然后添加id,scope,class属性就可以默认指定了吗?
◎使用javabean和使用import一个类进行然后创建有什么区别,是不是就是将scriptlet类似的语句进行了隐藏
◎session是否有时间限制,过了这段时间之后,我在去访问该地址就不会再显示出先前session中所存放的值了,解决的方法是不是只有持久化?
◎一个jsp页面包含了其他页面那么被包含的页面是否就是和当前页面共有同一个request,response
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
*****************************************question************************************
{
◎什么是轻量级组件,什么是重量级组件,他们之间有什么区别?
◎感觉内部类使用监听器,和在类里面重写listener方法,进行各个对象调用不同listener方法没是么
区别?只是一个把实现和调用分离开来而已,不知道还有是么区别,可以进行讨论。
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
◎
}