javaweb之servlet(三)JSP

一JSP:  Java  Server  Pages
Java服务器页面
和servlet一样都是sun出品
Jsp由两部分构成(html和java)
Html:静态网页内容
Servlet:服务端的小应用程序,适合编写java逻辑,但是不适合写页面。

Jsp:适合写动态输出的页面内容


二、查看jsp被编译后的class文件(反编译)代码(login.jsp)

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/8.5.23
 * Generated at: 2018-05-14 08:50:56 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;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class login_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("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=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("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>lll</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("\t");
 
		String bool =(String) request.getAttribute("loginfailure");
	
      out.write("\r\n");
      out.write("\t<form action='login' method='post'>\r\n");
      out.write("\t\t用户名<input type='text' name='username' /><br>\r\n");
      out.write("\t\t 密码<input type='password' name='password' />\r\n");
      out.write("\t\t<font color=\"red\"> ");

		 	if(bool!=null&&bool.equals("false")){
		 		out.print("lll");
		 	}
		 
      out.write("\r\n");
      out.write("\t\t </font><br>\r\n");
      out.write("\t\t  <input type='checkbox' name='rem' /><br> \r\n");
      out.write("\t\t<input type='submit' value='l' />\r\n");
      out.write("\t</form>\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } 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);
    }
  }
}

三、内置对象的使用(包括四个域)、EL表达式的使用、JSTL的使用

<%@page import="com.qfedu.xu.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- 我是注释 -->
	<%-- 我是注释 --%>
	<%-- 与html注释不同,jsp注释不会翻译成java代码。进而不会显示在网页上,因此,jsp注释更省流量、更安全。 --%>
	这是我们的第一个JSP页面。
	<%-- java小脚本 --%>
	<%-- java小脚本编写的代码会直接变为_jspService方法中的代码 --%>
	<%
		int a = 0;
		a++;
		System.out.println("a1=" + a);
	%>
	<h1>我是一个标题</h1>
	<%-- java小脚本是连续的。 --%>
	<%
		a++;
		System.out.println("a2=" + a);
	%>
	<%--html和java小脚本的混合使用 --%>
	<a href="<% if(2>1){out.print("http://www.baidu.com");} %>">百度</a>
	<%
	for(int i=0;i<10;i++){
		String str="<a href='";
		str=str+"http://www.baidu.com?pageno="+i+"'>百度</a><br>";
		out.print(str);
	}
	%>
	<br>
	<%
		User user=new User();
		user.setUsername("张三");		out.print(user.getUsername());
	%>
	<%-- 这句话相当于User user1=new User(); --%>
	<jsp:useBean id="user1" class="com.qfedu.xu.User" />
	<%-- 这句话相当于user1.setUsername("李四") --%>
	<jsp:setProperty property="username" value="李四" name="user1"/>
	<%-- 这句话相当于out.print(user1.getUsername()); --%>
	<jsp:getProperty property="username" name="user1"/>
	<br>
	<jsp:include page="testinclude.jsp"></jsp:include>
	<jsp:forward page="/MyServlet">
		<jsp:param name="username" value="zhangsan"/>
	</jsp:forward>	
</body>
</html>
<%@page import="java.util.Map"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.qfedu.xu.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%-- 内置对象——九大内置对象 --%>
	<%-- 你既不用get,也不用new,就有的对象
直接就能拿来用。
比如out.print();中out就是一个内置对象
request:代表了请求
response:代表了响应
session:代表了会话
application:代表了网站上下文,相当于context
exception:网页的异常
page:代表了页面
config:代表了servletConfig
pageContext:代表了页面上下文
out:代表了输出对象
内置对象其实就是_jspService方法中的局部变量。
 --%>
	<%-- 域对象
 域指的是共享域,
 application,最大,在整个网站上全局共享。
 session,其次大小,在一次会话中共享。
 request,在一次请求中共享。
 pageContext,在一个页面中共享数据。
  --%>
	<%
		//application.setAttribute("username", "zhangsan1");
		//application.removeAttribute("username");
		//session.setAttribute("username", "zhangsan1");
		//session.removeAttribute("username");
		//request.setAttribute("username", "zhangsan2");
		pageContext.setAttribute("username", "zhangsan3");
	%>

	<%
		//out.println(application.getAttribute("username"));
		//out.println(session.getAttribute("username"));
		//out.println(request.getAttribute("username"));
		out.println(pageContext.getAttribute("username"));
	%>
	<%-- <jsp:forward page="/testinclude.jsp">
		<jsp:param name="username123" value="zhangsan"/>
	</jsp:forward> --%>

	<%-- EL表达式:它是jsp中的一种取值规范 --%>
	<%-- 它取的就是共享域里的值 --%>
	<%-- EL表达式:${key.username} --%>

	<%
		User user = new User();
		user.setUsername("lisi");
		application.setAttribute("user", user);
	%>

	<br> ${user.username}
	<%-- 如果不用EL表达式 --%>
	<%
		User temp = (User) application.getAttribute("user");
		if (temp != null) {
			out.print(temp.getUsername());
		}
	%>
	<br> ${user["username"]}
	<br> ${user['username']}
	<br>
	<%
		List<String> list = new ArrayList<String>();
		list.add("123");
		list.add("456");
		list.add("789");
		request.setAttribute("list1", list);
	%>
	${list1[1]}
	<br>
	<%
		Map<String, String> map = new HashMap<String, String>();
		map.put("a", "aaa");
		map.put("b", "bbb");
		map.put("c", "ccc");
		request.setAttribute("map1", map);
	%>
	${map1['a']}
	<br> ${map1["a"]}
	<br> ${map1.a}
	<br>
	<%-- 在el取值中,map和实体类,取值是一样的。 --%>
	
	<%-- JSTL
	JavaServerPages  Standard Tag Library
	jsp标准标签库
	 --%>
	<c:set var="num" scope="session" value="2001"></c:set>
	<c:if test="${num>2000 }">
		<p>num大于2000</p>
	</c:if>
	
	<%-- 循环 --%>
	<c:forEach var="str" items="${list1 }" varStatus="status">
	<div>${status.index+1 }</div><font>${str }</font><br>
	</c:forEach>
</body>
</html>


四、MVC模式

MVC全名:Model  View  Controller
模型-视图-控制器
最经典的MVC就是jsp+servlet+javabean
三者各司其职。
表示层:View      jsp
逻辑层:Controller   servlet

数据层:Model     javabean

service业务逻辑层处理逻辑

MVC的特点是业务逻辑、数据、界面三个部分的代码彼此分离。
使得开发、维护变得“模块化”。
阅读更多
版权声明:dangjinh@163.com专有 https://blog.csdn.net/qq_41813207/article/details/80317627
上一篇Javaweb之servlet(二)
下一篇javaweb之--文件上传(UUID)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭