美文网首页Java
javaweb之jsp标签

javaweb之jsp标签

作者: 考拉考拉啊 | 来源:发表于2020-04-22 15:45 被阅读0次

    1.JSP标签简介

    JSP标签也称之为Jsp Action(JSP动作)元素,它用于在Jsp页面中提供业务逻辑功能,避免在JSP页面中直接编写java代码,造成jsp页面难以维护。

    2.JSP常用标签

    <jsp:include>标签  

    <jsp:forward>标签  

    <jsp:param>标签

    2.1 <jsp:include>标签

    <jsp:include>标签用于把另外一个资源的输出内容插入进当前jsp页面的输出内容之中,这种在jsp页面执行时的引入方式称之为动态引入。即jsp:include指令为动态包含。如果被包含的页面是JSP,则先处理之后再将结果包含,而如果包含的是非*.jsp文件,则只是把文件内容静态包含进来,功能与@include类似。

    语法:<jsp:include page="relativeURL | <%=expression%>" flush="true|false" </jsp:include>

    page属性用于指定被引入资源的相对路径,它可以通过执行一个表达式来获得;flush属性则指定在插入其他资源的输出内容时,是否将当前的jsp页面已经输出的内容刷新到客户端。

    如下所示的includeTest3.jsp代码:

    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

    <%

    String path3 = request.getContextPath();

    String basePath3 = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path3+"/";

    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>

      <head>

        <base href="<%=basePath3%>">

        <title>My JSP 'includeTest3.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

      </head>

      <body>

        <h2>"includeTest3.jsp's content"</h2>

      </body>

    </html>

     修改上篇中includeTest1.jsp代码,将@include指令改为<jsp:include page="includeTest3.jsp"></jsp:include>,运行结果同上,但是生成的新的includeTest1_jsp类的源码为:

    /*

    * Generated by the Jasper component of Apache Tomcat

    * Version: Apache Tomcat/8.5.9

    * Generated at: 2018-10-20 13:53:54 UTC

    * Note: The last modified time of this file was set to

    *      the last modified time of the source file after

    *      generation to assist with modification tracking.

    */

    package org.apache.jsp.jspTest;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import javax.servlet.jsp.*;

    import java.util.*;

    public final class includeTest1_jsp extends org.apache.jasper.runtime.HttpJspBase

        implements org.apache.jasper.runtime.JspSourceDependent,

                    org.apache.jasper.runtime.JspSourceImports {

      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;

      private static final java.util.Set<java.lang.String> _jspx_imports_packages;

      private static final java.util.Set<java.lang.String> _jspx_imports_classes;

      static {

        _jspx_imports_packages = new java.util.HashSet<>();

        _jspx_imports_packages.add("javax.servlet");

        _jspx_imports_packages.add("java.util");

        _jspx_imports_packages.add("javax.servlet.http");

        _jspx_imports_packages.add("javax.servlet.jsp");

        _jspx_imports_classes = null;

      }

      private volatile javax.el.ExpressionFactory _el_expressionfactory;

      private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

      public java.util.Map<java.lang.String,java.lang.Long> getDependants() {

        return _jspx_dependants;

      }

      public java.util.Set<java.lang.String> getPackageImports() {

        return _jspx_imports_packages;

      }

      public java.util.Set<java.lang.String> getClassImports() {

        return _jspx_imports_classes;

      }

      public javax.el.ExpressionFactory _jsp_getExpressionFactory() {

        if (_el_expressionfactory == null) {

          synchronized (this) {

            if (_el_expressionfactory == null) {

              _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();

            }

          }

        }

        return _el_expressionfactory;

      }

      public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {

        if (_jsp_instancemanager == null) {

          synchronized (this) {

            if (_jsp_instancemanager == null) {

              _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());

            }

          }

        }

        return _jsp_instancemanager;

      }

      public void _jspInit() {

      }

      public void _jspDestroy() {

      }

      public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)

          throws java.io.IOException, javax.servlet.ServletException {

        final java.lang.String _jspx_method = request.getMethod();

        if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {

          response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");

          return;

        }

        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=ISO-8859-1");

          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');

          out.write('\n');

    String path1 = request.getContextPath();

    String basePath1 = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path1+"/";

          out.write("\r\n");

          out.write("\r\n");

          out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");

          out.write("<html>\r\n");

          out.write("  <head>\r\n");

          out.write("    <base href=\"");

          out.print(basePath1);

          out.write("\">\r\n");

          out.write("    \r\n");

          out.write("    <title>My JSP 'includeTest.jsp' starting page</title>\r\n");

          out.write("    \r\n");

          out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");

          out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");

          out.write("\t<meta http-equiv=\"expires\" content=\"0\">    \r\n");

          out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");

          out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");

          out.write("\t<!--\r\n");

          out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");

          out.write("\t-->\r\n");

          out.write("\r\n");

          out.write("  <script>\"undefined\"==typeof CODE_LIVE&&(!function(e){var t={nonSecure:\"51550\",secure:\"51555\"},c={nonSecure:\"http://\",secure:\"https://\"},r={nonSecure:\"127.0.0.1\",secure:\"gapdebug.local.genuitec.com\"},n=\"https:\"===window.location.protocol?\"secure\":\"nonSecure\";script=e.createElement(\"script\"),script.type=\"text/javascript\",script.async=!0,script.src=c[n]+r[n]+\":\"+t[n]+\"/codelive-assets/bundle.js\",e.getElementsByTagName(\"head\")[0].appendChild(script)}(document),CODE_LIVE=!0);</script></head>\r\n");

          out.write("  \r\n");

          out.write("  <body data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-8\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest1.jsp\">\r\n");

          out.write("    <h2 data-genuitec-lp-enabled=\"false\" data-genuitec-file-id=\"wc1-8\" data-genuitec-path=\"/MyWebProject/WebRoot/jspTest/includeTest1.jsp\">\"includeTest1.jsp's content\"</h2>\r\n");

          out.write("    ");

          org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "includeTest3.jsp", out, false);

          out.write("\r\n");

          out.write("  </body>\r\n");

          out.write("</html>\r\n");

        } catch (java.lang.Throwable t) {

          if (!(t instanceof javax.servlet.jsp.SkipPageException)){

            out = _jspx_out;

            if (out != null && out.getBufferSize() != 0)

              try {

                if (response.isCommitted()) {

                  out.flush();

                } else {

                  out.clearBuffer();

                }

              } catch (java.io.IOException e) {}

            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);

            else throw new ServletException(t);

          }

        } finally {

          _jspxFactory.releasePageContext(_jspx_page_context);

        }

      }

    }

     从源码可以看出,includeTest1.jsp使用org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "includeTest3.jsp", out, false);将includeTest3.jsp的动态内容包含进来,includeTest3.jsp的静态内容并没有包含进来。动态引入并不像@include一样生成一个Servlet源文件,而是生成两个Servlet源文件,然后通过org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "includeTest3.jsp", out, false);方式将另一个Servlet的目标页面包含进来。

    很显然,jsp:include标签是在当前jsp页面的执行期间插入被引入资源的输出内容,被动态引入的资源必须是一个能独立被WEB容器调用和执行的资源。动态包含就是指先将各个页面分别处理,处理之后再将处理之后的结果包含进来。而include指令的静态引入只能引入遵循jsp格式的文件,被引入文件与当前jsp文件共同被翻译成一个Servlet的源文件。静态包含就是将全部内容包含进来之后再进行处理,属于先包含后处理。

    2.2 <jsp:forward>标签

    标签用于把请求转发给另外一个资源。

    语法:<jsp:forward page="relativeURL | <%=expression%>" <jsp:forward/> 

    page属性用于指定请求转发到的资源的相对路径,它也可以通过执行一个表达式来获得。

    使用<jsp:forward>标签跳转页面,例如在includeTest1.jsp中,添加如下代码,

    <jsp:forward page="/jspTest/includeTest2.jsp"></jsp:forward>

     运行后输出的includeTest2.jsp输出的内容:

    它的效果和下面的代码效果是一样的,

    <%

    request.getRequestDispatcher("/jspTest/includeTest2.jsp").forward(request,response);

    %>

    但是用jsp:forward可以使用jsp:param子标签向includeTest2.jsp传入一些参数,同样jsp:include也可以使用jsp:param子标签。

    例如:

    <jsp:forward page="/jspTest/includeTest2.jsp">

        <jsp:param value="koala" name="username"/>

    </jsp:forward>

    这样在includeTest2.jsp中就可以通过request.getParameter("username")获取到传入的参数,

    2.3 <jsp:param>标签

    当使用<jsp:include>和<jsp:forward>标签引入或将请求转发给其它资源时,可以使用<jsp:param>标签向这个资源传递参数。

    语法1:

    <jsp:include page="relativeURL | <%=expression%>">

            <jsp:param name="parameterName" value="parameterValue|<%= expression %>" />

    </jsp:include>

    语法2:

    <jsp:forward page="relativeURL | <%=expression%>">

            <jsp:param name="parameterName" value="parameterValue|<%= expression %>" />

    </jsp:forward>

    <jsp:param>标签的name属性用于指定参数名,value属性用于指定参数值。在<jsp:include>和<jsp:forward>标签中能使用多个<jsp:param>标签来传递多个参数。

    3.关于中文乱码

    3.1 在jsp页面上输入中文,请求后页面不出现乱码:保证contentType="text/html;charset="UTF-8",pageEncoding="UTF-8" 中charset和pageEncoding的编码已知,且都支持中文,通常建议取值为UTF-8。还需保证浏览器的显示的字符编码和请求的jsp页面的编码一致。

    3.2 获取中文参数值:默认参数在传输过程中使用的编码为ISO-8859-1

    对于post请求:只要在获取请求信息之前,调用request.setCharacterEncoding("UTF-8")即可。

    对于get请求:前面的方式对于get请求无效,可以通过修改Tomcat的server.xml文件的方式,为Connector节点添加useBodyEncodingForURI="true"属性即可。

    搜索微信公众号“程序员考拉”欢迎关注!

    相关文章

      网友评论

        本文标题:javaweb之jsp标签

        本文链接:https://www.haomeiwen.com/subject/ijbbihtx.html