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`) )
添加多条数据,这里略
对应类:
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; } }
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); } }
用到的连接池工具类(注意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(); } } }
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>
这里运用了简单的MVC三层架构
注意:访问/product_list.jsp将会没有内容
访问/productList查询数据库转发后才会有内容