Servlet入门

1.什么是Servlet,Servlet的本质是什么

Servlet:Java服务连接器,(Server Applet),主要作用在于通过Java编写的服务端程序和前端交互的生成动态的web数据!
Servlet的本质:就是一个普通java类型,继承 HttpServlet,重写这个类中doGet()/或者doPost()方法(这两个方法常用的)

2.Servlet的执行流程

	1)用户在浏览器输入访问地址 :http://localhost:8080/webApplicationContext/后台地址(url-	pattern)
	2)tomcat的web容器解析路径上面的/webApplicationContext/后台地址(url-pattern),找到当前web工程下的web.xml--- url-pattern是否存在,如果存在,解析xml文件中的servlet-mapping里面的url-pattern对应的
servlet-name:获取到它的Servlet名称
	3)映射配置---->找到servlet基本配置--->通过servlet名称---找到servlet-class---->当前类的全限定名称
	4)加载类 
Class clazz  = Class.forName("当前类的全限定名称") ;
    5)创建当前类对象---->无参构造方法系统提供的 
  Object obj = clazz.newInstance();
    6)通过字节码文件对象获取当前类中的成员方法所在类对象Method
 Method m =    calzz.getDeclareMethod("doGet",HttpServletRequest.class,HttpServletResponse.class) ;
    7)取消Java语言访问检查
    m.setAccessiable(true)  ;
    8)可以调用方法
    m.invoke(obj,request,response) ;

3.xml配置方式:Servlet的步骤

1)自定义一个类,继承自HttpServlet
2)重写这个类中doGet()和doPost()方法,,doPost里面复用doGet(),获取前台参数的方式相同的!
		这些方法里面完成自己的业务...
3)配置这个类在web项目下的WEB-INF里面的web.xml文件中配置
	<servlet>
		<servlet-name>建议和当前类名一致</servlet-name>
		<servlet-class>当前类全限定名称</servlet-class>
	</servlet>
	<servlet-mapping>
	    <servlet-name>和上面的servlet-name一致</servlet-name>
	    <url-pattern>/名称</url-pattern>
	</servlet-mapping>
	
	如果url-pattern不是以"/"开头,启动tomcat报错----LifexxxException
	

4.Servlet的生命周期

Servlet是一个单例的:
servlet默认创建的时机:
在访问servlet的时候才会创建当前类对象----无参构造方法执行一次,以及init(ServletConfig config):执行一次
service():方法 称为,servlet入口(业务服务方法),可以调用多次
detroy():当前tomcat正常关闭,servlet对象被销毁---->交给jvm的垃圾回收线程来回收没有更多引用的对象!

public class LifeServlet extends HttpServlet {
    //无参构造
    public LifeServlet() {
        System.out.println("LifeServlet的对象被创建了....");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println(config.getServletName()+"被初始化了,init方法被调用了!");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("service方法被调用了");
    }
    //销毁

    @Override
    public void destroy() {
        System.out.println("servlet被销毁了...");
    }
}

5.Servlet的体系结构

自定义XXxServlet---->extends---->HttpServlet (重写了service方法,里面的业务逻辑就是通过获取前台的提交方式,执行不同的doXXX()方法)----->GenericServlet(里面涉及到一些生命周期相关的方法以及抽象方法service()—需要让它的子类重写)----->Servlet接口: (service(),init(Servletconfig config),destroy())

6.获取前台表单数据参数的方式

//HttpServletRequest

String getRequestParameter(String parameterName):通过前台的name属性的属性值:作为"参数名称"
    通过参数名称获取参数内容
    
    表单标签中表单项
    		文本输入框
    		密码输入框
    		
    				必填name="xx" 
    
    
    
    Servlet--->目的前台接收参数
    jsp:Java Server Page :写java代码的html页面----->目的 渲染数据--展示数据
    		doGet()
    
    			response.getWriter().append("<html>") ;
				response.getWriter().append("<head>") ;

				response.getWriter().append("<body>") ;
						//里面的html标签内容
                response.getWriter().append("</body>") ;
				
                response.getWriter().append("</head>") ;
	            response.getWriter().append("</html>") ;
package com.qf.servlet_04;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 就是登录的后台Servlet
 */
public class LoginServlet extends HttpServlet {


    /**
     * 执行get提交的方法
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); //解决post中文乱码

        //请求对象里面有什么功能HttpServletRequest
        //public String getParameter(String name):获取前台用户的参数名称对应的内容---参数就是前台的name属性的属性值
        //前端get提交数据:http://localhost:8080/Servlet_01/login?username=高圆圆&password=123
        String username = request.getParameter("username");
        System.out.println("姓名是:"+username) ;

        System.out.println("-------------------------------------") ;
        String password = request.getParameter("password");
        System.out.println("密码是:"+password);


    }

    /**
     * 执行的是前台post提交
     * @param request 请求对象
     * @param response  响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("进入post提交方法了...");

        //post提交:中文会出现乱码---解决
        //HttpServletRequest它的父接口里面有一个功能:public void setCharacterEncoding(String env)
       /* request.setCharacterEncoding("utf-8");

        //由于现在JavaEE5.0 :doPost和doGet他们获取前台用户提交的参数数据的方式都是通用的!
        public String getParameter(String name):获取前台用户的参数名称对应的内容---参数就是前台的name属性的属性值
        //在浏览器---->右键---检查---->点击 network---->headers后面有一个PayLoad里面看到表单数据
        //源码:username=高圆圆&password=123
        String username = request.getParameter("username");
        System.out.println("姓名是:"+username) ;
        String password = request.getParameter("password");
        System.out.println("密码是:"+password);*/

       //将doGet复用一下
        doGet(request,response);


    }
}

7.ServletConfig对象(了解):servlet配置对象

ServletConfig:称为Servlet配置对象,每一个Servlet可以有自己的配置
      可以加载web.xml文件的时候,就可以在servlet的基本配置配置一些初始化参数
      就可以在在Servlet中获取初始化参数的内容
      

例如:获取指定的文件的路径—完成IO流操作

package com.qf2.servletconfig_01;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Enumeration;

public class ServletConfigDemo extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //public String getInitParameter(String name):servletConfig里面的方法:通过初始化参数名称获取参数值

        //1)获取到配置对象:在他父类的父类的GenericServlet:ServletConfig getServletConfig()
        ServletConfig servletConfig = this.getServletConfig();
        //2)public String getInitParameter(String name)
        String path = servletConfig.getInitParameter("path");
        System.out.println(path);
        //3)io流操作
        FileWriter fw = new FileWriter(path+"a.txt") ;
        fw.write("hello");
        fw.flush();

        //3)关闭资源
        fw.close();
        System.out.println("----------------------------------------") ;
       // public java.util.Enumeration<E> getInitParameterNames():获取servlet的所有初始化参数名称
        Enumeration<String> en = servletConfig.getInitParameterNames();
        //里面有特有功能:boolean hasMoreElements()  判断是有更多的元素
        //Object nextElement():获取下一个元素
        while(en.hasMoreElements()){
            String initParamenterName = en.nextElement();
            //public String getInitParameter(String name):通过参数名称获取参数值
            String initParameterValue = servletConfig.getInitParameter(initParamenterName);
            System.out.println(initParamenterName+"---"+initParameterValue);

        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request,response);
    }
}

8.ServletContext:全局对象(域对象):整个web应用程序的范围

作用:
		1)获取上下文路径   /web应用程序名称/访问地址
						/web应用程序名称
		2)获取全局参数---->举例子使用 web.xml---><context-param>---以后的目的:加载配置文件
		
		3)可以请求转发:后端 通过JDBC方式拿到数据了---->直接页面跳转将数据展示
		
		4)就是作为域对象---在不同servlet之间进行数据共享!

1)获取上下文路径 /web应用程序名称/访问地址

​ /web应用程序名称

package com.qf2.servletcontext_02;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ServletContext:重点对象(全局对象)
 *  代表整个web应用程序,每一个web应用程序都有自己的上下文
 *
 *  作用1:获取web应用程序的上下文路径
 *
 *  前端  浏览器行为;----都需要带上上下文路径
 *          <a href="http://localhost:8080/web上下文路径/xx地址"></a>
 *          <img src="都需要带上下文路径" />
 *
 *         导入js文件
 *              <script src="都需要带上下文路径"></script>
 *         导入css文件
 *              <link href="都需要带上下文路径" ref="stylesheet">
 */
public class ContextServletDemo1 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        //获取ServletContext接口对象----->web容器 帮助我们创建对象了
        // public ServletContext getServletContext()
        //ServletContext servletContext = this.getServletContext();
        //获取上下文路径---->public String getContextPath()
       // String contextPath = servletContext.getContextPath();
       // System.out.println(contextPath);

        //简化书写格式:全局对象中的功能一部分都封装在请求对象中
        // String getContextPath()
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
}

2)获取全局参数

---->举例子使用 web.xml—>—以后的目的:加载配置文件

package com.qf2.servletcontext_02;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ServletContext作为全局对象的作用2:获取web.xml文件中全局参数
 */

public class ContextServletDemo2 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1)获取全局对象
        ServletContext servletContext = this.getServletContext();
        //2)获取全局参数
        //public String getInitParameter(String name):获取全局参数
        String encoding = servletContext.getInitParameter("encoding");
        //3)获取参数encoding的值---解决post提交中文乱码  (后期:使用过滤器)
        request.setCharacterEncoding(encoding);

        //获取用户的内容
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"---"+password) ;


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            doGet(request,response);
    }
}

3)可以请求转发:

后端 通过JDBC方式拿到数据了---->直接页面跳转将数据展示

package com.qf2.servletcontext_02;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ServletContext的作用3
 *      请求转发使用
 *
 *      请求转发---->服务器帮助我们转发到资源文件上------"服务器行为"是不需要带上下文路径
 *
 */
public class ContextServletDemo3 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //请求转发本身的写法格式:
        //1)获取全局对象Servletcontext
       // ServletContext servletContext = this.getServletContext();

        //2)创建一个转发器对象

        //public RequestDispatcher getRequestDispatcher(String path)
        //RequestDispatcher:定义接收来自客户端的请求并将它们发送到服务器上的任何资源
      //  RequestDispatcher rd = servletContext.getRequestDispatcher("/adv.html");//参数:转发的资源路径:路径上不能带上下文的,直接写资源路径(以"/开头")

        //3)使用RequestDispatcher转发去对象 去请求转发到静态资源或者动态资源上
        //public void forward(ServletRequest request, ServletResponse response)
       // rd.forward(request,response);

        //简写格式:直接就可以请求对象HttpServletRequest获取RequestDispatcher
       // public RequestDispatcher getRequestDispatcher(String path)

        //request.getRequestDispatcher("/adv.html").forward(request,response);

        //请求转发可以访问WEB-INF下的资源文件

        request.getRequestDispatcher("/WEB-INF/hello.html").forward(request,response);

        System.out.println("请求转发完成");

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request,response);
    }

}

4)就是作为域对象—在不同servlet之间进行数据共享

package com.qf2.servletcontext_02;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * ServletContext作用4:作为域对象
 */
public class ContextServletDemo4 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1)获取全局对象
        ServletContext servletContext = this.getServletContext();
        //2)public void setAttribute(String name, Object object):给全局对象(域对象)绑定属性以及它的内容
        //创建一个集合
        List<String> list = new ArrayList<>() ;
        //添加内容
        list.add("张三") ;
        list.add("高圆圆") ;
        list.add("文章") ;
        servletContext.setAttribute("list",list);
        System.out.println("-------------------");
        servletContext.setAttribute("name","刘桑");


        System.out.println("存储数据成功....");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}

四个域对象:从小到大

pageContext page对象:在某个jsp页面中有效

HttpServletRequest request对象 在一次请求中有效 (举例:请求转发) :使用居多

HttpSession session对象 (会话管理)里面一种技术 其次,使用居多

ServletContext context对象 :全局对象 :代表整个web应用程序

解决响应中文乱码和提交中文乱码

//1.利用全局对象
//)获取参数encoding的值---解决post提交中文乱码  (后期:使用过滤器)
 // <context-param>
       // <!--全局参数名称-->
        //<param-name>encoding</param-name>
       // <param-value>utf-8</param-value>
   //</context-param>
    request.setCharacterEncoding(encoding);

//2.请求中文乱码
	request.setCharacterEncoding("utf-8");

//3.相应中文乱码
	response.setContentType("text/html;charset=utf-8") ;

9.RR(掌握请求对象中一些常用的功能以及响应对象的重定向原理)

Http协议的一种规范
HttpServletRequest请求对象
			浏览器发请求---->浏览器---network---->可以看到一种格式
								请求头:请求内容
HttpServlerResponse响应对象
			服务器响应给浏览器----->network---->可以看到一种格式
							响应头:响应内容
							

请求对象常用方法

package com.qf2.request_03;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 浏览器将所有的信息都封装到HttpServletRequest对象中,获取请求的信息
 */
public class RequestDemo1 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1)获取请求行的内容 请求方式 URI HTTP协议版本
        // String getMethod()
        String method = request.getMethod();
        System.out.println("请求方式是:"+method);
        //StringBuffer getRequestURL();
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("请求的url地址是:"+requestURL.toString());
        //String getRequestURI();
        System.out.println("请求的uri是:"+request.getRequestURI()) ;

        // String getProtocol();获取协议版本
        System.out.println("http版本是:"+request.getProtocol());
        
        //请求对象中获取请求头的方法:
        //public String getHeader(String name):通过指定的请求头获取它的内容
		 String header = request.getHeader("user-agent");
        //判断用户使用的浏览器的类型时
        if(header.contains("Chrome")){
            System.out.println("用户使用的谷歌浏览器") ;
        }else if(header.contains(" Firefox")){
            System.out.println("用户使用的是火狐浏览器") ;
        }else if(header.contains("trident")){
            System.out.println("用户的是IE浏览器");
        }else{
            System.out.println("未知浏览器类类型");
        }

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

重定向原理:

浏览器请求服务器的时候,服务器将所有响应信息封装到HttpServletResponse
Http协议的一种规范要求:固定的格式
       服务器:tomcat,Jetty,nginx
 
       服务器响应给浏览器  :响应信息
                   响应行:两部分 Http协议版本   响应的状态码
                   响应头:key:value
 
           响应的状态码:
                   404:未找到的路径(前端错误)
                   405:请求方式有问题
                   500:后端代码错误(业务逻辑出问题了...)
                   200:响应成功
                   302:进一步发送请求
                                  跨域(Springboot +vue)问题(三阶段末尾)
 
 
   重定向的原理:(重定向最终属于浏览器行为: 必须携带上下文路径)
               当用户发送一次请求--->服务器接收请求,响应给浏览器
                       location响应头
                       响应的状态码:302  进一步请求

10.面试题:请求转发和重定向的区别

1)地址栏是否有明显变化
	请求转发没有变化的:
	重定向地址栏有明显变化
2)它们整个的两次request对象是否一致
    请求转发:服务器内部完成的---->(服务器行为:不需要携带上下文路径),两次request对象是一致的!
    重定向:原理:
    		设置一响应头:location+302状态码 
    		第一次请求的后台地址,然后给响应浏览器 302状态以及location地址,浏览器会再一次发送请求
    		两次request对象不一致,所以如果有业务需求的话,使用重定向获取不到request域对象中的数据的;
    		如果仅仅页面跳转,使用重定向!
 3)是否能够访问WEB-INF下的资源文件
 		WEB-INF:可以存放html/jsp文件,都是为了保证数据安全;是不能够直接访问的
 		WEB-INF:只能请求转发的方式来访问,重定向不可以访问的
 4)是否能够跨工程访问其他工程里面的资源文件
 		请求转发:只能访问当前工程下的文件包括WEB-INF的资源文件
 		重定向:可以访问 当前工程下的资源文件(除过WEB-INF),还可以跨工程访问其他资源文件...
    	   

11.MVC架构思想,描述

三层架构思想:
	M:Model :业务模型数据
				包名 xxx.xx.service :业务层代码(业务逻辑判断)
				包名 xx.xx.xx.dao:数据库访问层代码(JDBC方式访问数据库的操作)
	V:View:视图数据
				现在使用jsp/   (html+Jquery+ajax)--服务器端返回给前端都是"json数据"
	C:Controller:控制器(前端和后端的连接器)  :控制视图
				 前后端交互: 
				    现在技术就是Servlet:调用service层接口--->获取业务数据---->交给前端
				    			使用jsp技术:将业务数据获取到之后存"储域对象",然后请求转发给xxx.jsp
				    
				    以后的技术Springmvc:spring提供的框架

12.Jsp运行经历哪个阶段

hello.jsp---->被翻译成 hello_jsp.java文件
class hello_jsp entends HttpJspBase----->导入jasper.jar---->HttpJspBase 继承了HttpServlet
被tomcat解析---->创建当前类对象---->反射的创建对象---->调用_jspservice()—>解析jsp文件中html标签代码
------hello_jsp.java----->hello_jsp.class文件 (编译)

默认jsp的存储路径C:\Users\Administrator.IntelliJIdea2019.1\system\tomcat\Unnamed_servlet+jsp+jdbc\work\Catalina\localhost\servlet_jsp_jdbc\org\apache\jsp

13.jsp的入门

1.jsp的本质

Jsp的本质就是一个Servlet
  jsp:Java Server Page :写java代码的html页面----->目的 渲染数据--展示数据
 了解:
 	Jsp执行流程		
 			翻译----jsp文件---翻译.java文件
 			编译---->将.java文件---.class文件

2.jsp有三大指令/9大内置对象

<%@ page%> page指令
有默认属性
默认带的两个属性
    language:只支持java语言
    contentType:当前jsp的页面编码是utf-8
其他属性:    
    buffer:jsp中的html标签都需要被jsp内置对象:JspWriter(字符流) out对象,out对象不断给浏览器写入内容,缓冲区大小默认8kb
    errorPage:如果当前页面发生异常,跳转到错误页面上
    isErrorPage:当前页面是否是错误页面
    isELIgnored:是否忽略jsp的el表达式  ,默认值不会忽略 false
    import:导入相关的java类或者接口的包名

<%@include%>:静态包含指令 :将导入的jsp文件不会被单独翻译和编译,直接就将导入jsp文件内容直接写入到当前jsp文件中, 比较节省内存! (推荐)
        <%--@include指令:静态导入
            file属性:加载导入的jsp文件,只是将导入的jsp文件的内容写进来
        --%>

<%@taglib%>taglib指令 + 结合jsp的核心标签库 jstl使用---->必须导入jstl.jar包以及依赖包



9大内置:其中四个都是域对象 :重点四个域对象,其他5个了解一下

PageContext pageContext     :仅仅是在当前jsp页面中有效       jsp中使用el表达式:pageScope
HttpServletRequest request  :在一次请求中有效                               requestScope
HttpSession session         :在一次会话中有效                               sessionScope
ServletContext application  :是全局对象:代表整个web应用程序                   applicaionScope
      
       其他内置对象:
                ServletConfig config:配置对象
                JspWriter out:jspWriter---继承Writer:字符输出流对象  对象名称 out
                HttpServletResponse response:响应对象:直接响应给浏览器内容
                Object page (this):代表是当前jsp对象的地址值引用
                Throwable t :代表的异常对象

14.Jsp 里面代码格式

<% jsp的脚本代码:写Java代码的 %>

<%= jsp的输出表达式%>

<%  int i = 10 ; %>
<%=i%>

<%
	request.setAttribute("name","高圆圆") ; //给request域对象存储了一个数据
%>

jsp的el表达式  就是代替上面写法 <%=%> jsp的输出表达式:让写法更加简单
${pageScope.name属性值}
${requestScope.name属性值}---->里面有自己的内置对象
${sessionScope.name属性值}
${applicationScope.name属性值}

15.引入Jsp的el表达式

${可以从域对象中获取的后台数据}+jsp的核心标签库 (重点)

el表达式支持 (对象图导航语言Ognl:是Object Graph Navigation Language )

class Student{  //javaBean规范:这个类是具体类,必须有私有字段,必须提供对外公共访问setXXX/getXXX
    private String name ;
    
    public String getName(){ //name----bean属性
        return name ;
    }
    public void setName(String name){
        this.name = name ;
    }
    
}
Student s = new Student() ;
s.setName("高圆圆") ;
servlet已经将学生存储到了域对象中 request.setAttribute("student",student) ;

jsp----获取获取信息
   ${requestScope.student.name}--->调用getName()----->get()去掉,N变成小写---name
     

16.el表达式如何操作JavaBean?

//${} :el表达式的格式
class User{
    
    private String username ;
    private String password ;
    
    public void setUsername(String username){
        this.username = username ;
    }
      public String getUsername(){
       return username ;
    }
    
     public void setPassword(String password){
        this.password = password ;
    }
      public String getPassword(){
       return password ;
    }
}

//jsp文件中
<%
    //创建User对象
    User user = new User() ;
//封装数据
	user.setUsername("高圆圆") ;
     user.setPassword("123");
   //将user对象存储到了request域中
     request.setAttribute("user",user) ;

    %>
        
        //获取数据		
        			//ognl语言:对象图导航语言的一种格式
        ${域中的绑定属性.访问javabean的bean属性}--->调用就是getXxx()---get()去掉,第一个字母小写,这个就是bean属性
        ${user.username} 
        ${user.password}

17.jstl中的遍历list集合数据使用的标签格式

//后端给request域对象存储了list集合数据
request.setAttribute("list",list) ;
//请求转发到某个jsp文件中

						${list}                           n
<c:foreach itesm="${从域对象中获取属性绑定的内容}" var="循环中的变量名">
			${n} //获取每一个list集合中的数据
</c:foreach>

18.jstl中的if

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/5/25
  Time: 14:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--
    1)导入两个jar包jstl-1.2 ,standard-1.1.2
    2)导入核心标签库的路径
    <%@taglib prefix="c"  uri="核心标签库的网络路径"%>
--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>taglib指令</title>
</head>
<body>
        <%--就可以使用jstl的core核心库---里面的c标签--%>
<%--常见使用:c:if标签--%>
<%
    int number = 15 ;
    //number存储request域对象中
    request.setAttribute("number",number) ;
%>
<%--
        c:if标签就是单独判断类似于Java语言中的if(条件表达式){}
 test:属性就是判断 里面${变量名从域对象中获取并且进行判断}
            true,执行c:if标签的文本内容


--%>
<c:if test="${number==10}">

        <h4>number的结果是10</h4>
</c:if>
<%--没有c:else标签,如果还需要针对不成立结果 需要在书写c:if--%>
<c:if test="${number!=10}">
            <h4>条件不成立</h4>
</c:if>

<hr/>

<%--
    在el表达式有关键字empty,判断为空---结合c:if标签使用
        判断集合或者实体对象是否空
--%>
<%
    List<String> list = new ArrayList<>() ;
    list.add("hello") ;
    list.add("world") ;
    list.add("java") ;
    //将List存储到request域中
    request.setAttribute("list",list);
%>
<c:if test="${ empty list}"> <%--集合为空--%>

        <h4>list为空</h4>
</c:if>

<c:if test="${not empty list}"><%--判断集合不为空--%>
         ${list[0]} - ${list[1]} - ${list[2]}

</c:if>
</body>
</html>

19.jstl中的选择

<%--07_c_choose_选择判断标签.jsp
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/5/25
  Time: 15:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--导入taglib,指定的核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>c_choose_选择判断标签</title>
</head>
<body>
<%--
            Java代码的选择判断语句  /swtich
                if(条件表达式1){
                        语句1;
                }else if(条件表达式2){
                            语句2;
                            ...
                } else{
                      语句n;
                }


                jsp的jstl核心库中c:choose     :选择判断标签
                                        c:when
                                        c:otherwise...
        --%>
<%
    int weekNum = 0 ;
    //将weekNum存储request域中
    request.setAttribute("weekNum",weekNum) ;
%>

<c:choose>
    <%--选择判断--%>
    <%--test="${域对象中获取数据判断,true,成立,才执行c:when语句}"--%>
    <c:when test="${weekNum==1}">
        <h4>星期一</h4>
    </c:when>
    <c:when test="${weekNum==2}">
        <h4>星期二</h4>
    </c:when>
    <c:when test="${weekNum==3}">
        <h4>星期三  </h4>
    </c:when>
    <c:when test="${weekNum==4}">
        <h4>星期四</h4>
    </c:when>
    <c:when test="${weekNum==5}">
        <h4>星期五</h4>
    </c:when>
    <c:when test="${weekNum==6}">
        <h4>星期六</h4>
    </c:when>
    <c:when test="${weekNum==7}">
        <h4>星期日</h4>
    </c:when>
    <c:otherwise>
        <h4>非法数据</h4>
    </c:otherwise>
</c:choose>
</body>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值