1、<meta refresh=5,url='xxx.xxx.xxx'/>
可以设置页面的自动跳转
2、表单中的图片提交按钮
<input type='image' src='aaa.gif' alt='xxx' name='submit2'/>
3、<embeded>插入多媒体
插入其他的需要加入type属性来指明播放器插件
如:type='auto/x-pn-realaudio-plugin'
4、相对长度单位
em:元素的字体高度
ex: 字母x的高度
px: 像素
%: 百分比
5、DIV标记
如果不使用CSS,和段落标记相同
CSS+DIV 实现结构化的页面布局
传统方式使用表格来控制
相关组件
Commons DBCP
Commons DbUtils
Commons Email
Commons FileUpload
Log4J
FCKEditor
- Eclipse的架构
JDT
PDE
MyEclipse
JBoss IDE
Java --> build path
Java - Compiler
show line number
6、TOMCAT的配置
conf/server.xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
解决get方法传递中文参数的乱码问题。
conf/context.xml
<Context reloadable="true">
自动加载web应用,用于开发阶段。
conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="mwang" password="mwang" roles="admin,manager"/>
</tomcat-users>
7、编写Java Web服务器
直接使用Socket编程
使用Socket+多线程
使用NIO+多线程
使用JDK自带或者第三方的线程池技术对线程进行管理,提高多线程的效率
使用Java Socket的开发框架,例如MINA和Cindy
NIO的非阻塞的socket集合Java的多线程。
使用JDK或第三方线程池技术对线程进行管理,提高多线程的执行效率
使用开源的JavaSocket框架,MINA和Cindy框架
8、Servlet编程
Servlet 结构
Applet
Servlet
MIDlet
javax.servlet.Servlet
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
可以获取初始化参数
可以获取服务器信息
可以获取头信息的枚举,然后取枚举的值
客户通过浏览器可以发送给Web服务器的请求一共有7种
Post,Get,Put,Delete,Options,Head,Trace
常用就是Post和Get
web.xml里面可以配置init-para
request对象可以获得服务器的运行参数
request对象可以获取头信息 getHeaderNames() getHead(String name)
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("中文")
request.getContextPath() 获取servlet的名字 /hello
9、form 表单
request.setCharacterEncoding("utf-8");
request.getParameterValues(name); 取多个值的数值
request.getParameterMap()
写一个特殊字符的转义filter方法, 防止内容以html形式输出
public String htmlFilter(String strValue) {
strValue = strValue.replaceAll("&", "&");
strValue = strValue.replaceAll("<", "<");
strValue = strValue.replaceAll("\n", "<br>");
}
利用javascript进行客户端验证
10、JSValidation验证框架
http://cosoft.org.cn/projects/jsvalidation
见附件
(1) validation-config.xml
两种方式:一种alert,一种div
(2) validation-framework.js
21 行 var ValidationRoot = "/hello/js";
在html文件中引入js,在form里面增加οnsubmit='return doValidate(this)'
message乱码,可以用UltraEdit保存转码成utf-8
11、FCKeditor实现word编辑功能
http://www.fckeditor.net/download
引入fckeditor.js
可以精简fckeditor
TinyMCE
见附件
12、JDBC
ojdbc5.jar JDK1.5
ojdbc6.jar JDK1.6
13、Tomcat配置连接池
修改context.xml
见附件
maxActive是最大激活连接数,这里取值20个,表示同时最多有20个与数据库的连接。
maxIdle是最大空闲连接数,这里取值10个,表示即使没有连接请求时,依然可以保持10空闲的连接,而不被清除,随时处于待命状态。
maxWait是最大等待秒钟数,这里取值-1,表示无限等待,直到超时为止,也可以取值9000,即表示9秒后超时。
Context context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/myds");
conn = ds.getConnection();
14、Commons DbUtils
public class MapListExample {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:oracle:thin:@192.168.1.20:1521:ora9";
String jdbcDriver = "oracle.jdbc.driver.OracleDriver";
String user = "scott";
String password = "tiger";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from guestbook", new MapListHandler());
for (int i = 0; i < results.size(); i++) {
Map map = (Map) results.get(i);
System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:oracle:thin:@192.168.1.20:1521:ora9";
String jdbcDriver = "oracle.jdbc.driver.OracleDriver";
String user = "scott";
String password = "tiger";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from guestbook", new BeanListHandler(Guestbook.class));
for (int i = 0; i < results.size(); i++) {
Guestbook gb = (Guestbook) results.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
String sql = "insert into guestbook (id,name,email,phone,title,content,time) values(gb_seq.nextval,?,?,?,?,?,?)";
String param[] = { StringUtil.filterHtml(name), StringUtil.filterHtml(request.getParameter("email")),
StringUtil.filterHtml(request.getParameter("phone")), StringUtil.filterHtml(title),
request.getParameter("content"), sdf.format(new java.util.Date()) };
try {
Context initContext = new InitialContext();
DataSource ds = (DataSource) initContext.lookup("java:/comp/env/jdbc/oracleds");
QueryRunner qr = new QueryRunner(ds);
result = qr.update(sql, param);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
连接池状态下不用管理连接的释放了。
Cookie编程
Cookie c = new Cookie(...);
reponse.addCookie(c);
Cookie[] cookies = request.getCookies();
修改Cookie, reponse.addCookie(c);
删除Cookie, 修改有效期.
- Cookie的大小数量有限制
- Cookie是文本文件,需加密
- Cookie可以被禁用
Session编程
底层实现
- Cookies
cookiename: JSESSIONID
cookievalue: ABDCEI
- URL重写
在链接后面增加jsessionid
response.encodeURL("/servelt/getUesr");
JSP (Java Server Page)
page指令: contentType
pageEncoding
import
session
isErrorPage
errorPage
声明标记
<%! .....%>
还可以定义jspInit和jspDetory
Scriptlet标记
<% ... %>
表达式标记
<%=...%>
include指令
动作(action)
<jsp:include> 与include指令的区别
<jsp:forward>
相当于:
RequestDispatcher res = request.getRequestDispatcher("/index.jsp");
res.forward(request,response);
JSP内置对象
out,request,response,session,application
config,page,pageContext,exception
定制错误页面
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
<error-page>
<error-code>404</error-code>
<location>/error404.htm</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error500.jsp</location>
</error-page>
</web-app>
taglib指令
<%@ taglib uri=http://xxx.xxx.xxx.xxx/tags prefix="util"%>
Apache Bean utils
(1)
BeanUtils.getProperty 返回字符串
PropertyUtils.getProperty 返回对象
BeanUtils.copyPreperties 浅层拷贝
(2)动态生成对象
org.apache.commons.beanutils.LazyDynaBean
(3)依赖于conn的遍历
ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);
Iterator it = rsdc.iterator();
while (it.hasNext()) {
DynaBean bean = (DynaBean) it.next();
System.out.println(bean.get("id"));
}
(4)不依赖于conn的遍历,耗内存
RowSetDynaClass rsdc = new RowSetDynaClass(rs);
Iterator it = rsdc.getRows().iterator();
while (it.hasNext()) {
DynaBean bean = (DynaBean) it.next();
System.out.println(bean.get("id"));
}
MVC 模式
JSPmodel1 vs JSPmodel2
request.getRequestDispatcher().forward
和reponse.sendRedirect的区别
浏览器显示地址是否变化
能否带request的值
能否转到网站以外的url
forward速度比sendRedirect快
JSP EL
减少jsp的代码
方便jsp中代码的修改
设定JSP不使用JSP EL
或者修改web.xml
<web-app...>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</jsp-config>
</web-app>
或者转义
\${} '$'{}
定制标记库
TimerTag.java
package com.mwang;
import java.io.IOException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class TimerTag extends TagSupport{
private long starttime;
private long endtime;
public int doStartTag() {
starttime = System.currentTimeMillis();
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspTagException{
endtime = System.currentTimeMillis();
long eclapse = starttime - endtime;
try {
JspWriter out = pageContext.getOut();
out.println("Running time = " + eclapse + " ms.");
} catch (IOException e) {
e.printStackTrace();
throw new JspTagException();
}
return EVAL_PAGE;
}
}
util.tld 需保存在WEB-INF下面
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library exercising SimpleTag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>util</short-name>
<uri>http://v521.com/taglib/util</uri>
<tag>
<description>timer</description>
<name>timer</name>
<tag-class>com.mwang.TimerTag</tag-class>
<body-content>JSP</body-content>
</tag>
</taglib>
body-content: JSP, empty, sciptless, tagdependent
JSP: 标记中间可以包含java或jsp代码
empty:标记中间不可以包含内容
sciptless: 不可以包含脚本
tagdependent:由标记决定
定义标记属性
编写loopTag标记
doAfterBod() {
return EVAL_BODY_AGAIN
return SKIP_BODY
}
可以加工body,进行二次加工
标记库打包
classes和tld文件,tld放在META-INF里面
常用标记库介绍
(1)JSTL
(2)Jakarta Taglibs
(3)Display tag 可以生成xml,csv和xls
JSTL1.2已成为J2EE5的标准功能
下载apache taglibs
core
format 标记库
SQL标记库 不推荐使用,表示层不能直接访问数据库
XML标记库 不推荐使用
Functions标记库
Servlet 监听器 配置web.xml
可以在web应用中响应特定对象的特定事件
(1)可以更加方便的控制application、session和request对象的发生的特定事件
(2)可以集中处理特定的事件
httpsession监听器接口
HttpSessionListener
sessionCreated, sessionDestroyed
HttpSessionAttributeListener
attributeAdded, attributedReplaced, attributeRemoved
HttpSessionBindingListener
HttpSessionActivationListener
ServletContextListener
initialized destroyed
ServletContextAttributeListener
ServletRequestListener
ServletRequestAttributeListener
Servlet 过滤器
(1)用户认证与授权管理
(2)统计web应用的访问量,命中率,形成访问报告
(3)实现web应用的日志处理功能
(4)实现数据压缩功能
(5) 对数据传输进行加密
(6)实现XML文件的XSLT转换
编写javax.servlet.Filter接口的类
配置Servlet过滤器
文件上传
package com.mwang;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFileServlet extends HttpServlet {
ServletContext sc;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) {
System.out.println(item.getFieldName() + ":" + item.getString("UTF-8"));
} else {
if (item.getName()!= null && !item.getName().equals("")){
System.out.println("File size:" + item.getSize());
System.out.println("File type:" + item.getContentType());
System.out.println("File name:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + "aaa",tempFile.getName());
item.write(file);
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void init(ServletConfig config) throws ServletException {
sc = config.getServletContext();
}
}
Java邮件发送
javamail 下载,发送程序复杂
利用apache commons email
public static void main(String[] args) {
SimpleEmail email = new SimpleEmail();
email.setHostName("202.38.64.8");
email.setAuthentication("xxx@mail.ustc.edu.cn", "xxx");
email.setCharset("utf-8");
try {
email.setFrom("xxx@mail.ustc.edu.cn");
email.addTo("xxx@mail.ustc.edu.cn");
email.setSubject("Hello");
email.setMsg("This is my first mail!");
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
MultiPartEmail email = new MultiPartEmail();
email.setHostName("202.38.64.8");
email.setAuthentication("xxx@mail.ustc.edu.cn", "xxx");
email.setCharset("utf-8");
try {
email.setFrom("xxx@mail.ustc.edu.cn");
email.addTo("xxx@mail.ustc.edu.cn");
email.setSubject("Hello");
email.setMsg("This is my first mail!");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath("c:/abc.txt");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setName("abcabcabca");
email.attach(attachment);
email.send();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
DAO设计模式和数据分页显示
Displaytag标记库
http://displaytag.sourceforge.net/
Pager 标记库
http://jsptags.com/tags/navigation/pager
乱码问题
native2ascii -encoding utf-8 c.properties d.properties
把utf-8格式的文件转换成ascii码
eclipse windows -> Preference -> Content Type