日期:2017/11/16
承接上文,继续介绍JSP和Javabean。
一、JSP
它的语法和html有较大的相似之处,详细语法可以参考:http://www.runoob.com/jsp/jsp-tutorial.html 。下面是重要的几个点,jsp的使用有:浏览器通过URL(universal resource location)访问 、 java文件的程序调用(response.sendRedirect(“url”))、html的页面访问等等。
最主要的是jsp的语法,即嵌入html的指令:
(1) Declaration -- 声明
<%! int i ;
public void setname(){}
%>作用:声明成员变量、方法,这些会保留至JSP程序结束运行。
(2) Scriptlet -- 脚本
<%
for(int i =0; i<10; i++){
}
%>
作用:执行代码
(3) Expression -- 表达式
<%=
request.getParameter("name")
%> 作用:转换为字符串表达式
(4) Comment -- 注释
<%--
"Hope is a good thing."
--%> 作用:注释说明(5) Directive --编译(执行前编译)
<%@
Directive 属性=“属性值”
%> 作用: 对内容编译处理
常见的Directive:
page
include
taglib
5.1 page
<%@page language=“script language”|
extends=“className”|
import=“importList”|
buffer=“none|kb size”| --none:不缓冲,默认8k
session=“true|false”| --是否可以使用session,默认true
autoFlush=“true|false” --缓冲器是否自动清除,默认true
isThreadSafe=“true|false”| --默认false(永远不要设成true)
info=“infoText”| -- 任何字符
errorPage=“errorPageUrl ”|
isErrorPage=“true|false”|
contentType=“contentTyepInfo”|
pageEncoding=“gb2312”
%>
作用: 编译-设置与jsp Container 的沟通方式
5.2 include
<%@include file=“fileURL%>
作用: 编译-设置将文件(jsp或者html)包含进来。静态包含。
(6) Action --动作(运行期间的命令)
常见的:
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:include
jsp:forward
jsp:param
jsp:plugin
嵌入applet
(7)内置对象
共有9个,红色标注为常用:
JSP的内置对象:
out
request
response
pageContext 用的很少
session
application
config 用的很少
exception
Page用的很少
这些对象和参数,可以自行上网查找配置的方法和参数。
二、javabean
本质还是.java文件,类。
JDBC的使用分为好几个步骤,servlet中若是每次使用都重复编写,当有10000个数据库访问时,无疑会加重程序量和降低阅读性,如下例子1(优化前):
package com.java.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MysqlTestOne {
/**
* @SuppressWarnings 批注允许您选择性地取消特定代码段(即,类或方法)中的警告。
* 其中的想法是当您看到警告时,您将调查它,如果您确定它不是问题, 您就可以添加一个 @SuppressWarnings 批注,以使您不会再看到警告。
* */
@SuppressWarnings("resource")
public static void main(String [] args) throws Exception{
String user = "root";
String password = "";
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class. forName(driver);//加载驱动,Class.forName
con = DriverManager.getConnection(url, user, password);//建立连接
stmt = con.createStatement();//建立statement对象
stmt.execute("create table classtable(classmateId int NOT NULL AUTO_INCREMENT ,"//执行SQL语句
+ "name char(20) NOT NULL,"
+ "sex char(8) NOT NULL,"
+ "birthdate int NOT NULL,"
+ "address char(20) NOT NULL,"
+ "phonenumber int NOT NULL,"
+ "PRIMARY KEY (classmateId)"
+ ")ENGINE=InnoDB;");
// stmt.execute("select * from class ;");
// stmt.execute("insert into Employee values(3,'James1 ',2)");
// stmt.execute("insert int Employee values(2,'James2 ',26)");
rs = stmt. executeQuery("select * from classtable");//获取ResultSet
while(rs.next()){
System.out.println("Before**");
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4)+" "+rs.getString(5)+" "+rs.getInt(6));
}
stmt.execute("INSERT INTO classtable (classmateId,name,sex,birthdate,address,phonenumber)"
+ "VALUES(1,'mmb','male',19941123,'maoming',123456),"
+ "(2,'lhm','male',19941023,'guangdong',123616), "
+ "(3,'hzt','female',19951193,'zhanjiang',1246456),"
+ "(4,'Dhm','male',19941023,'guangdong',123616),"
+ "(5,'DDm','male',19641023,'guangdong',123631);");
//内存泄露
rs = stmt. executeQuery("select * from classtable;");
while(rs.next()){
System.out.println("After**");
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4)+" "+rs.getString(5)+" "+rs.getInt(6));
}
}
catch(SQLException e1){
e1. printStackTrace();
}finally{
try{
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}catch(SQLException e){
System.out.println(e. getMessage());
}
}
}
}
将之改为javabean,如下例子2:
package srevletTest;
import java.sql.*;
public class DB {
public static Connection getConn(){
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=");
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e ){
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(Connection conn){
Statement stmt = null;
try{
if(conn != null){
stmt = conn.createStatement();
}
} catch (SQLException e){
e.printStackTrace();
}
return stmt;
}
public static ResultSet getResultSet(Statement stmt,String sql){
ResultSet rs = null;
try {
if (stmt != null){
rs = stmt.executeQuery(sql);
}
} catch (SQLException e){
e.printStackTrace();
}
return rs;
}
public static void closeConn(Connection conn){
try{
if(conn != null){
conn.close();
conn = null;
}
} catch (SQLException e){
e.printStackTrace();
}
}
public static void closeStatement(Statement stmt){
try{
if(stmt != null){
stmt.close();
}
} catch(SQLException e){
e.printStackTrace();
}
}
public static void closeRs(ResultSet rs){
try {
if(rs != null){
rs.close();
rs = null;
}
} catch(SQLException e){
e.printStackTrace();
}
}
}
使用javabean的servlet代码,阅读性上升了,如下例子3:
package srevletTest;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DBtest extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("in doGet()!!");
PrintWriter out = response.getWriter();
Connection conn = DB.getConn();
Statement stmt = DB.getStatement(conn);
ResultSet rs = DB.getResultSet(stmt, "SELECT * FROM classtable");
out.println("<table border=1>");
out.println("<tr><td>Contend:</td></tr>");
try{
while (rs.next()){
out.println("<tr>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("</tr>");
}
}catch (SQLException e){
e.printStackTrace();
}finally{
DB.closeConn(conn);
DB.closeRs(rs);
DB.closeStatement(stmt);
System.out.println("allover..");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("in doPost()!!");
doGet(req,resp);
}
@Override
public void destroy() {
System.out.println("destory()...");
}
@Override
public void init() throws ServletException {
System.out.println("init()...");
}
}
待续...

本文介绍了JSP的基本语法及重要元素,包括声明、脚本、表达式等,并通过实例展示了如何利用JavaBean优化数据库操作,提高代码的可读性和复用性。
1万+

被折叠的 条评论
为什么被折叠?



