Servlet case 7: jsp technology and cases, servlet case 7 jsp
Jsp running principle:
Create a java file (servlet) based on the jsp file and compile and run it.
The first access will be translated into a servlet and then executed
Three jsp commands:
1. page command: configure the running properties of page translation (usually the default setting is used)
Language = "java" language that can be embedded
ContentType = "text/html; charset = UTF-8" set servlet response. setContentType content
PageEncoding = "UTF-8" encoding of the current jsp file
Session = "true" default session can be used directly
Import = "java. util. *" import java package
ErrorPage = "xxx. jsp" If java code is incorrect, jump to a new page
Note that the error here is not a 404 error, but a code error. If you want to configure a 404 error jump page, you must configure it in web. xml.
IsErrorPage = "true" indicates whether the page is redirected due to an error
2. include command: Other jsp pages can be included in another jsp page.
<% @ Include file = "Address" %>
3. taglib command: Introduce the tag library on the jsp page
<% @ Taglib uri = "tag library address" prefix = "prefix" %>
Jsp built-in objects:
Two objects that need special attention
1. out object: function: Output content on the client page
Three methods:
1. <% out. write ("hello world"); %>
2. <% response. getWriter (). write ("hello world"); %>
3. <% = "hello world" %>
Essentially, both are converted into out objects.
1, 3 Write out buffer, 2 write response Buffer
Because tomcat obtains content from the response buffer, the content in the out buffer is flushed to the response buffer.
So the first output is 2, but the buffer (8 KB by default) buffer is set to 0 kb, the output is in order
2. pageContext object: Page Context object
Is a domain object in the range of the current page
The domain object methods, such as setAttribute, are similar to request and session fields.
The range can be set.
// Use pageContext to store data in the request domain // request. setAttribute ("name", "zhangsan"); // pageContext. setAttribute ("name", "sunba"); // pageContext. setAttribute ("name", "lisi", PageContext. REQUEST_SCOPE); // request domain // pageContext. setAttribute ("name", "wangwu", PageContext. SESSION_SCOPE); // session domain // pageContext. setAttribute ("name", "tianqi", PageContext. APPLICATION_SCOPE); // application domain
Retrieve
<%=request.getAttribute("name") %><%=pageContext.getAttribute("name", PageContext.REQUEST_SCOPE)%>
Unique Method: findAttribute
<! -- FindAttribute searches for the name in the range from small to large --> <! -- Page domain <request domain <session domain <application domain --> <% = pageContext. findAttribute ("name") %>
Obtain other objects
<% pageContext.getRequest(); pageContext.getOut(); %>
Static and Dynamic include:
Static: <% @ include file = "Address" %>
Synthesize a page and translate it into a java file.
Dynamic: <jsp: include page = "Address"/>
Translate two jsp files into java files and compile and run
Running stage call method include
Request forwarding:
<Jsp: forward page = "resource"/>
The address remains unchanged after forwarding
The following is a case:
Dynamic Display of product list
Database preparation:
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
Add multiple data entries.
Corresponding class:
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, response) throws ServletException, IOException {// prepare all product data and store it in 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 ();} // Save the data to the request domain and forward it to the jsp file 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
Connection Pool tool class used (pay attention to the c3p0-config.xml configuration ):
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 performanceutils {private static DataSource dataSource = new ComboPooledDataSource (); private static ThreadLocal <Connection> tl = new ThreadLocal <Connection> (); // you can directly obtain a connection pool public static DataSource getDataSource () {return dataSource;} // gets the Connection object public static Connection getConnection () throws SQLException {Connection con = tl. get (); if (con = null) {con = dataSource. getConnection (); tl. set (con) ;}return con ;}// enable the public static void startTransaction () throws SQLException {Connection con = getConnection (); if (con! = Null) {con. setAutoCommit (false) ;}// transaction rollback public static void rollback () throws SQLException {Connection con = getConnection (); if (con! = Null) {con. rollback () ;}/// submit and close resources and release public static void commitAndRelease () throws SQLException {Connection con = getConnection (); if (con! = Null) {con. commit (); // transaction commit con. close (); // close the resource tl. remove (); // remove from thread binding} // close the resource method 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
Content on the jsp page:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <% @ page import = "java. util. * "%> <% @ page import =" domain. * "%> ............ <% // obtain the set 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 hrefpolic'product_info.htm '>"); out. write (" <a href='product_info.html 'style = 'color: green'>" + product. getPname () + "</a> </p>"); out. write ("<p> <font color = '# FF0000'> marketplace price: & 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
The simple MVC three-layer architecture is used here
Note: Accessing/product_list.jsp will have no content
Access/productList to query the content forwarded by the database.