FreeMarker Seven: FreeMarker and Servlet integration; (this blog is the core focus of the Freemarker part)

This blog is the core focus of Freemarker! ! ! However, in the actual development in the future, Servlet is less used, but high-level frameworks such as Spring are used; so the focus in the future is the integration of Freemarker and these high-level frameworks! ! !

Note: In practice, whether to use JSP or Freemarker, which is better, different people may have different opinions, but FreeMarker seems to be more acceptable than JSP at present.

table of Contents

One: the integration of freemarker and Servlet environment

1. Introduce freemarker.jar

2. Configure FreemarkerServlet in web.xml (core focus)

3. Check if the integration is successful

annotation:

Two: Case: Develop employee information form

1. Prepare front-end static resources such as css; create ftl files (copy the files in the original html)

2. Prepare data and write background logic code:

3. Front-end employee.ftl file, load data

4. Effect:

5. Annotation: employee.ftl obtains data from: request object, session object, global object;


One: the integration of freemarker and Servlet environment

FreeMarker has good support for JavaWeb by default;

1. Introduce freemarker.jar

 

2. Configure FreemarkerServlet in web.xml (core focus)

Use [ctrl+shift+t] shortcut key to find class files in Eclipse:

That is, the Servlet class FreemarkerServlet introduced in freemarker.jar is the key! ! !

\

Configure in web.xml: To make freemarker work in web projects, you need to configure the Servlet class of FreemarkerServlet in freemarker.jar:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>fm-web</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>
  	<servlet-name>freemarkerppppp</servlet-name>
  	<!-- FreemarkerServlet这个类就是freemarker提供的一个Servlet,来简化web程序的开发 -->
  	<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
  	<init-param>
  		<!-- 设置ftl加载目录 -->
  		<param-name>TemplatePath</param-name>
  		<!-- 以后的ftl文件都会放在 /WEB-INF/ftl目录下-->
  		<param-value>/WEB-INF/ftl</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>freemarkerppppp</servlet-name>
  	<!-- *.ftl的意思是,浏览器输入的url如果是以.ftl结尾的话,就会被 FreemarkerServlet这个Servlet处理-->
  	<!-- 即只要客户端浏览器输入的地址是以.ftl结尾的,这个FreemarkerServlet就会自动的到/WEB-INF/ftl目录中去查找对应名字的文件,并且将其进行输出 -->
  	<url-pattern>*.ftl</url-pattern>
  </servlet-mapping>
</web-app>

………………………………

Web.xml configuration analysis:

The function of the FreemarkrServlet class is: as long as the address entered by the client browser ends with .ftl, the FreemarkerServlet will automatically find the file with the corresponding name in the /WEB-INF/ftl directory, and output it! ! ! ! !

………………………………

3. Check if the integration is successful

In order to demonstrate whether the configuration is successful and observe the effect, create an ftl directory under the /WEB-INF directory and add a test.ftl file:

Start the application:

………………………………

annotation:

It can be considered that the configuration of the Servlet class of FreemarkerServlet in freemarker.jar is the basis;;;; When the jar package of freemarker.jar is introduced and the FreemarkerServlet is configured, the web application (processing business) Servlet can recognize the ftl script file. Behind it is freemarker doing support! ! !

………………………………


Two: Case: Develop employee information form

1. Prepare front-end static resources such as css; create ftl files (copy the files in the original html)

It can be found that it was originally employee.html, but now it has become employee.ftl ! ! !

 

Start the application and visit emloyee.ftl:

The browser displays the content of the static html page employee.ftl, so how does the data of this static page change from dead to alive?

 

2. Prepare data and write background logic code:

ListServlet: (1) accept and process client browser requests to prepare data; (2) prepare data; (3) forward the request to employee.ftl, and display the data in a better way; (pay attention to the notes)

package com.imooc.freemarker.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ListServlet
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<Employee> empList = new ArrayList<Employee>();
		empList.add(new Employee(7733,"刘芳","销售部","销售经理",8500f));
		empList.add(new Employee(7733,"李四","研发部","工程师",7000f));	
		// So,这两个员工放在哪里,才能被脚本读取到呐?
		// 在web环境下中使用freemarker,其会自动从当前的请求会话(ServletRequest),或者是ServletContext中自动进行查找;
		// 这儿我们将empList放在了ServletRequest对象中;一会访问的时候,模板引擎(即FreeMarker)就会自动的从当前请求中获取数据了;
		request.setAttribute("employee_list",empList);
		// 数据添加好了,如何跳转到employee.ftl那个界面上呐???
		// 利用请求转发,跳转到employee.ftl
		request.getRequestDispatcher("/employee.ftl").forward(request, response);
	}

}

Servlet data has been created, and the request has been forwarded to employee.ftl, then how can the employee.ftl file obtain the data and display it? ? ?

 

3. Front-end employee.ftl file, load data

employee.ftl: Load data: (1) Obtain the data prepared in the Servlet; organize the data into html;

The initial employee.ftl: (this is not important, it is for reference)


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>员工列表</title>
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet"></link>
    
    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>

    <style type="text/css">
        .pagination {
            margin: 0px
        }

        .pagination > li > a, .pagination > li > span {
            margin: 0 5px;
            border: 1px solid #dddddd;
        }

        .glyphicon {
            margin-right: 3px;
        }

        .form-control[readonly] {
            cursor: pointer;
            background-color: white;
        }
        #dlgPhoto .modal-body{
            text-align: center;
        }
        .preview{

            max-width: 500px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <h1 style="text-align: center">IMOOC员工信息表</h1>
        <div class="panel panel-default">
            <div class="clearfix panel-heading ">
                <div class="input-group" style="width: 500px;">
                    
                </div>
            </div>

            <table class="table table-bordered table-hover">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>员工编号</th>
                    <th>姓名</th>
                    <th>部门</th>
                    <th>职务</th>
                    <th>工资</th>
                    <th>&nbsp;</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>1</td>
                    <td>7782</td>
                    <td>张晓涛</td>
                    <td>研发部</td>
                    <td>研发工程师</td>
                    <td style="color: red;font-weight: bold">¥7,780.00</td>
                    
                </tr>
                <tr>
                    <td>2</td>
                    <td>7839</td>
                    <td>张丽</td>
                    <td>研发部</td>
                    <td>运维工程师</td>
                    <td style="color: red;font-weight: bold">¥8,820.00</td>
                    
                </tr>
                
                <tr>
                    <td>3</td>
                    <td>5243</td>
                    <td>张倩</td>
                    <td>市场部</td>
                    <td>客户经理</td>
                    <td style="color: red;font-weight: bold">¥6,000.00</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

 Modified employee.ftl: (emphasis!!!)


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>员工列表</title>
    <link href="css/bootstrap.css" type="text/css" rel="stylesheet"></link>
    
    <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>

    <style type="text/css">
        .pagination {
            margin: 0px
        }

        .pagination > li > a, .pagination > li > span {
            margin: 0 5px;
            border: 1px solid #dddddd;
        }

        .glyphicon {
            margin-right: 3px;
        }

        .form-control[readonly] {
            cursor: pointer;
            background-color: white;
        }
        #dlgPhoto .modal-body{
            text-align: center;
        }
        .preview{

            max-width: 500px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <h1 style="text-align: center">IMOOC员工信息表</h1>
        <div class="panel panel-default">
            <div class="clearfix panel-heading ">
                <div class="input-group" style="width: 500px;">
                    
                </div>
            </div>

            <table class="table table-bordered table-hover">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>员工编号</th>
                    <th>姓名</th>
                    <th>部门</th>
                    <th>职务</th>
                    <th>工资</th>
                    <th>&nbsp;</th>
                </tr>
                </thead>
                <tbody>
                <#list employee_list as emp>
                <tr>
                    <td>${emp_index + 1}</td>
                    <td>${emp.empno?string("0")}</td>
                    <td>${emp.ename}</td>
                    <td>${emp.department}</td>
                    <td>${emp.job}</td>
                    <td style="color: red;font-weight: bold">¥${emp.salary?string("0.00")}</td>
                    
                </tr>
                </#list>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

 

4. Effect:

………………………………

5. Annotation: employee.ftl obtains data from: request object, session object, global object;


Note:

      ● View (view) part, need to extract background data, and html combined together, this work requires a template engine, JSP is a template engine, FreeMarker is also a template engine! ! !

      ● Naturally, the template engine of JSP is the standard of JEE. Tomcat has built-in JSP implementation in the manufacturer’s implementation and can be used directly; the file is .jsp;

      ● The template engine FreeMarker is not a JEE standard. If you want to use FreeMarker, you need to import the jar package and configure it; the file is .ftl;

      ● Although there are differences in the usage strategy and specific grammar between JSP and FreeMarker, the overall usage routines of the two are very similar; the core of JSP is el and jstl expressions, and the core of FreeMarker is freemarker grammar and built-in functions;

Guess you like

Origin blog.csdn.net/csucsgoat/article/details/114649887