Servlet案例7:jsp技術及案例,servlet案例7jsp

來源:互聯網
上載者:User

Servlet案例7:jsp技術及案例,servlet案例7jsp

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'>商城價:&yen;"+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查詢資料庫轉寄後才會有內容

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.