JSP quick start, MVC pattern and three-tier architecture, EL expressions, JSTL tags

1. Concept and function

● Concept: Java Server Pages, Java server page
● A dynamic web technology, which can define not only static content such as HTML, JS, CSS, but also dynamic content of Jva code
● JSP=HTML +Java
● JSP Function: Simplify development, avoid directly outputting HTML tags in Servletr, which is essentially Servlet

Two, JSP quick start

1. Import JSP coordinates

<dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
</dependency>

2. Create a JSP file

3. Write HTML tags and Java code

<body
<h1>hello jsp~</h1>
<% System.out.printf("jsp hello~"); %>
</body>

Three, JSP principle

●Concept: Java Server Pages, Java server page

●JSP=HTML+Java, used to simplify development

●JSP is essentially a Servlet

When JSP is accessed, the SP container (Tomcat) converts it into a Java file (Servlet), and the SP container (Tomcat) compiles it, and finally provides services to the outside world is actually this bytecode file

[External link image transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the image and upload it directly (img-LCbBe4jz-1653532347959) (C:\Users\可\AppData\Roaming\Typora\typora-user-images\ image-20220519105736625.png)]

Four, JSP script

● JSP scripts are used to define Java codes in JSP pages
● SP script categories:

1.<%…%>

The content will be placed directly in the _jspService() method

For example:

 public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {
    
    

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
    
    
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("    <title>Title</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\r\n");

    //1.接收用户名和密码
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    //2.调用MyBatis完成查询
    //2.1获取SqlSessionFactory对象
	//String resource = "mybatis-config.xml";
	//InputStream inputstream = Resources.getResourceAsStream(resource);
	//SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputstream);
    SqlSessionFactory sqlSessionFactory= SqlSessionFactoryUtils.getSqlSessionFactory();
    //2.2获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //2.3获取Mapper
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    //2.4调用方法
    User user = userMapper.selectById(username, password);
    //2.5释放资源
    sqlSession.close();

2.<%=…%>

The content will be placed in out.print() as a parameter of out.print()

For example:

      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("    <title>Title</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\r\n");

3.<%!..%>

The content will be placed outside the _spService() method and directly included by the class

public final class login_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
    
    


        void show(){
    
    

        }
        String name = "zhangsan";

    
  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

4. Disadvantages of JSP

Because in the SP page, both HTML tags and ava codes can be defined, resulting in the following problems:

1. Writing troubles: especially complex pages

2. Reading trouble

3. High complexity: the operation needs to depend on various environments, JRE, JSP container, JavaEE...

4. Occupies memory and disk: JSP will be automatically generated, java and .class. files occupy disk, and .class files occupy memory when running

5. Difficulty in debugging: after an error, you need to find the automatically generated .java file for debugging

6. It is not conducive to teamwork: front-end personnel do not know Java, and back-end personnel are not proficient in HTML

7.。。。。

Five, EL expression

Expression Language expression language, used to simplify the java code in the JSP page

Main function: get data

Syntax: get the data ${expression}

${brands}

stored in the domain with the key as brands

Four domain objects in JavaWeb:

1.page: the current page is valid

2.request:: the current request is valid

3.session: the current session is valid

4.application: the current application is valid

The data obtained by the expression will be searched from these 4 fields in turn until it is found

6. JSTL tags

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-unjmFXAG-1653532347961) (C:\Users\可\AppData\Roaming\Typora\typora-user-images\ image-20220522165908513.png)]

1. Import jstl, standard dependency

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
</dependency>
<dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
<dependency>

2. Learn the <c:if>\ tag, create a new jstl-if.jsp file, and import the taglib tag library.

<%--
  Created by IntelliJ IDEA.
  User: 可
  Date: 2022/5/22
  Time: 17:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:if test="${status==1}">
        启用
    </c:if>
    <c:if test="${status==0}">
        禁用
    </c:if>
</body>
</html>

3. Learn the <c:forEach>\ tag, create a new jstl-foreach.jsp file, and import the taglib tag library.

<%--
  Created by IntelliJ IDEA.
  User: 可
  Date: 2022/5/23
  Time: 10:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="button" value="新增">
<hr/>
<table border="2" cellspacing="" width="800">
    <tr>
        <th>序号</th>
        <th>品牌名称</th>
        <th>企业名称</th>
        <th>排序</th>
        <th>品牌介绍</th>
        <th>状态</th>
        <th>操作</th>
    </tr>
<c:forEach items="${brands}" var="brand">
            <tr align="center">
                <td>${brand.id}</td>
                <td>${brand.brandName}</td>
                <td>${brand.companyName}</td>
                <td>${brand.ordered}</td>
                <td>${brand.description}</td>
                <td>${brand.status==1 ? "启用" : "禁用"}</td>
                <td><a href="#">修改</a>&nbsp;&nbsp;<a href="#">删除</a></td>
            </tr>
</c:forEach>
</table>
</body>
</html>

4. The setting value of the varStatus="Nid" attribute in the <c:> tag ${brand.conut} means starting from 1, and ${Nid.index} means starting from 0

Seven, MVC mode and three-tier architecture

MVC pattern

Three-tier architecture

The data access layer is also called the dao layer and the persistence layer.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-KR4Lmv07-1653532347965) (C:\Users\可\AppData\Roaming\Typora\typora-user-images\ image-20220523170024498.png)]

8. Case

1. Prepare the environment

Create a new module brand-demo, import coordinates
<dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--导入jstl-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!--Servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>


        <!--JSP-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>
Create a package structure for a three-tier architecture
Database table tb brand
Entity class Brand
MyBatis basic environment

The tag header of version 3 of the xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
Mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <!--    起别名    -->
        <package name="cn.itheima.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--数据库连接池-->
            <dataSource type="POOLED">
                <!--数据库的连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///db1?useSSL=false&amp;useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="nigaoxian+0128"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 扫描mapper -->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>
BrandMapper.xml

Br and Mapper interface

Guess you like

Origin blog.csdn.net/weixin_48053866/article/details/124980054