Servlet案例7:jsp技術及案例
jsp運行原理:
根據jsp文件創建java文件(servlet),並編譯運行
第一次訪問時會被翻譯成servlet後執行
jsp三個指令:
1.page指令:頁面翻譯運行的屬性的配置(通常使用默認)
language="java" 可以嵌入的語言
contentType="text/html; charset=UTF-8" 設置servlet的response.setContentType內容
pageEncoding="UTF-8" 當前jsp文件的編碼
session="true" 默認session可以直接使用
import="java.util.*" 導入java包
errorPage="xxx.jsp" 如果java代碼有錯,跳轉到某個新頁面
註意這裏的錯誤不是404錯誤,而是代碼錯誤,如果要配置404錯誤跳轉的頁面,需要在web.xml中配置
isErrorPage="true" 是否是由於錯誤跳轉後的頁面
2.include指令:可以將其他的jsp頁面包含到另一個jsp頁面中
<%@ include file ="地址" %>
3.taglib指令:在jsp頁面中引入標簽庫
<%@taglib uri="標簽庫地址" prefix="前綴"%>
jsp內置對象:
需要特別強調的2個對象
1.out對象:作用:在客戶端頁面輸出內容
三種方法:
1.<% out.write("hello world");%>
2.<% response.getWriter().write("hello world");%>
3.<%="hello world"%>
本質上後兩者都是轉化成out對象
1,3寫入out緩沖區,2寫入response緩沖區
由於tomcat會從response緩沖區獲得內容,所以out緩沖區內容會被刷到response緩沖區
於是先輸出的是2,但是設置緩沖區(默認8kb)buffer=0kb,則按順序輸出
2.pageContext對象:頁面上下文對象
是一個域對象,範圍是當前頁面
域對象方法setAttribute等和request,session域類似
範圍可以設置
//使用pageContext向request域存數據 //request.setAttribute("name", "zhangsan"); //pageContext.setAttribute("name", "sunba"); //pageContext.setAttribute("name", "lisi", PageContext.REQUEST_SCOPE);//request域 //pageContext.setAttribute("name", "wangwu", PageContext.SESSION_SCOPE);//session域 //pageContext.setAttribute("name", "tianqi", PageContext.APPLICATION_SCOPE);//application域
取出
<%=request.getAttribute("name") %> <%=pageContext.getAttribute("name", PageContext.REQUEST_SCOPE)%>
特有的方法:findAttribute
<!-- findAttribute會從小到大搜索域的範圍中的name --> <!-- page域<request域<session域<application域 --> <%=pageContext.findAttribute("name") %>
獲得其他對象
<% pageContext.getRequest(); pageContext.getOut(); %>
靜態包含和動態包含:
靜態:<%@include file="地址" %>
合成一個頁面,再進行翻譯成java文件
動態:<jsp:include page="地址"/>
兩個jsp文件翻譯成java文件,編譯運行
運行階段調用方法include
請求轉發:
<jsp:forward page="資源"/>
轉發後地址不變
接下來做一個案例:
動態顯示商品列表
數據庫準備:
CREATE DATABASE web; USE web; CREATE TABLE `product` ( `pid` VARCHAR(50) NOT NULL, `pname` VARCHAR(50) DEFAULT NULL, `market_price` DOUBLE DEFAULT NULL, `shop_price` DOUBLE DEFAULT NULL, `pimage` VARCHAR(200) DEFAULT NULL, `pdate` DATE DEFAULT NULL, `is_hot` INT(11) DEFAULT NULL, `pdesc` VARCHAR(255) DEFAULT NULL, `pflag` INT(11) DEFAULT NULL, `cid` VARCHAR(32) DEFAULT NULL, PRIMARY KEY (`pid`) )View Code
添加多條數據,這裏略
對應類:
package domain; public class Product { private String pid; private String pname; private double market_price; private double shop_price; private String pimage; private String pdate; private int is_hot; private String pdesc; private int pflag; private String cid; public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public double getMarket_price() { return market_price; } public void setMarket_price(double market_price) { this.market_price = market_price; } public double getShop_price() { return shop_price; } public void setShop_price(double shop_price) { this.shop_price = shop_price; } public String getPimage() { return pimage; } public void setPimage(String pimage) { this.pimage = pimage; } public String getPdate() { return pdate; } public void setPdate(String pdate) { this.pdate = pdate; } public int getIs_hot() { return is_hot; } public void setIs_hot(int is_hot) { this.is_hot = is_hot; } public String getPdesc() { return pdesc; } public void setPdesc(String pdesc) { this.pdesc = pdesc; } public int getPflag() { return pflag; } public void setPflag(int pflag) { this.pflag = pflag; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } }View Code
servlet:
package servlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import domain.Product; import utils.DataSourceUtils; public class ProductListServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //準備所有商品數據,存入List QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); List<Product> productList = null; String sql = "select * from product"; try { productList = runner.query(sql, new BeanListHandler<Product>(Product.class)); } catch (SQLException e) { e.printStackTrace(); } //將數據存到request域,轉發給jsp文件 request.setAttribute("productList", productList); request.getRequestDispatcher("/product_list.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }View Code
用到的連接池工具類(註意c3p0-config.xml的配置):
package utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtils { private static DataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); // 直接可以獲取一個連接池 public static DataSource getDataSource() { return dataSource; } // 獲取連接對象 public static Connection getConnection() throws SQLException { Connection con = tl.get(); if (con == null) { con = dataSource.getConnection(); tl.set(con); } return con; } // 開啟事務 public static void startTransaction() throws SQLException { Connection con = getConnection(); if (con != null) { con.setAutoCommit(false); } } // 事務回滾 public static void rollback() throws SQLException { Connection con = getConnection(); if (con != null) { con.rollback(); } } // 提交並且 關閉資源及從ThreadLocall中釋放 public static void commitAndRelease() throws SQLException { Connection con = getConnection(); if (con != null) { con.commit(); // 事務提交 con.close();// 關閉資源 tl.remove();// 從線程綁定中移除 } } // 關閉資源方法 public static void closeConnection() throws SQLException { Connection con = getConnection(); if (con != null) { con.close(); } } public static void closeStatement(Statement st) throws SQLException { if (st != null) { st.close(); } } public static void closeResultSet(ResultSet rs) throws SQLException { if (rs != null) { rs.close(); } } }View Code
jsp頁面中的內容:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.*" %> <%@ page import="domain.*" %> ...... ...... <% //獲得集合List<Product> List<Product> productList = (List<Product>)request.getAttribute("productList"); if(productList!=null){ for(Product product : productList){ out.write("<div class=‘col-md-2‘ style=‘height:250px‘>"); out.write("<a href=‘product_info.htm‘>"); out.write("<img src=‘"+product.getPimage()+"‘ width=‘170‘ height=‘170‘ style=‘display: inline-block;‘>"); out.write("</a>"); out.write("<p><a href=‘product_info.html‘ style=‘color: green‘>"+product.getPname()+"</a></p>"); out.write("<p><font color=‘#FF0000‘>商城價:¥"+product.getShop_price()+"</font></p>"); out.write("</div>"); } } %>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>WEB7</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>ProductListServlet</display-name> <servlet-name>ProductListServlet</servlet-name> <servlet-class>servlet.ProductListServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ProductListServlet</servlet-name> <url-pattern>/productList</url-pattern> </servlet-mapping> </web-app>View Code
這裏運用了簡單的MVC三層架構
註意:訪問/product_list.jsp將會沒有內容
訪問/productList查詢數據庫轉發後才會有內容
Servlet案例7:jsp技術及案例