📖 earlier posts 📖
@Configuration注解可从上一章Spring.Ioc中了解到,在annotation包下的ConfigAnnotation.java,即使用了@Configuration、@ComponentScan两个注解,实现了Spring applicationContext.xml的配置文件功能,而代码其意可以理解为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 package annotation;package annotation;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration @ComponentScan("annotation") public class ConfigAnnotation {
其中@Configuration将ConfigAnnotation.java成为了一个配置类,根据@Configuration注解,可让ConfigAnnotaation.java类成为相当于Spring XML中的配置文件。而@ComponentScan注解实现了Spring XML配置文件的语法“<context:component - scan base -package="Bean 包路径”/> “
Dao Java Spring TestDao.java 1 2 3 4 5 package annotation.dao;public interface TestDao { public void save () ; }
Spring IoC TestDao.java 1 2 3 4 5 package annotation.dao;public interface TestDao { public void save () ; }
Service Java Spring TestServce 1 2 3 4 5 6 7 8 9 10 11 package service;import dao.TestDao;public class TestService { TestDao testDao; public void setTestDao (TestDao testDao) { this .testDao = testDao; } public void save () { testDao.save(); } }
Spring IoC TestService 1 2 3 4 package annotation.service;public interface TestService { public void save () ; }
javaConfig JavaConfig.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package javaConfig;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import controller.TestController;import dao.TestDao;import service.TestService;@Configuration public class JavaConfig { @Bean public TestDao getTestDao () { return new TestDao (); } @Bean public TestService getTestService () { TestService testservice = new TestService (); testservice.setTestDao(getTestDao()); return testservice; } @Bean public TestController getTestController () { TestController testcontroller = new TestController (); testcontroller.setTestService(getTestService()); return testcontroller; } }
TestConfig.java 1 2 3 4 5 6 7 8 9 10 11 12 package javaConfig;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import controller.TestController;public class TestConfig { public static void main (String args[]) { AnnotationConfigApplicationContext annotationconfigapplicationcontext = new AnnotationConfigApplicationContext (JavaConfig.class); TestController testcontroller = annotationconfigapplicationcontext.getBean(TestController.class); testcontroller.save(); annotationconfigapplicationcontext.close(); } }
从Spring Java 与Spring IoC 来相比,Spring Java在类的方面很明显比Spring IoC少了一个类,但相比之下Java Script的代码比Spring IoC少了许多。但Java Script @Bean注解来完成@ComponentScan自动扫描的功能与服务。
控制反转(IoC,Inversion of Control)是Spring 框架中的核心,而这核心技术在他的官方文档"/docs/spring-framework-reference/core.html#spring-core"之中,第一句话标题就是”核心技术“。通常IoC也可以称之为依赖注入(DI,De),在此过程中,对象会通过构造函数参数,通过工厂参数在构造或从工厂方法中返回后的对象实例上设置的属性来定义其依赖项。 也就是说,当某个Java对象需要调用另一个Java对象时,在正常且传统的模式下,通常会使用new来实例化该类,而在之后出现的Spring时,则对象的实例不需要有你来创建,而是由Spring容器来创建,控制程序之间的关系。
Spirng 常用注解 声明Bean 注解 Spring框架中,使用XML配置文件可以简单的配置Bean,但如果项目庞大需要Bean装配时,将会导致XML配置文件过于庞大,不方便以后的维护和拓展,因此衍生出了注解(annotaion)的方式去配置Bean:
ID
DA
FA
@Component
一个泛化的概念,仅仅表示一个组件对象(bean),可以作用在让你和层次之上,没有明确的角色
Bean
@Repository
用于数据访问层(DAO)的类标识为Bean,即注解数据访问层Bean,功能与@Component 相同
DAO
@Service
用于标注一个业务逻辑组件类(Service层),功能与@Component相同
Service
@Controller
该注解用于标注一个控制器组件类(Spring MVC的Controller),功能与@Component相同
Spring MVC
注入Bean 注解
ID
DA
FA
@Autowired
可对成员变量、方法及构造方法进行标注,完成自动装配工作,通过@Autowired可消除set和get方法,默认按照Bean的类型进行装配
@Resource
与@Autowired的功能一样,区别与该注解默认按照名称来装配注入,只有当找不到名称匹配的Bean时才会按照类型来装配注入。可结合@Qualifier注解一起搭配食用可以按照名称来进行装配
@Resource
@Resource有两个属性,分别为name和type,Name属性指定Bean实例名称,而按照名称来装配注入;Type属性则指定Bean类型,即安装Bean的类型进行装配
@Qualifier
可与@Autowired注解配合使用,当@Autowired注解需要按照名称来进行装配注入时 ,则需要结合该注解进行使用,而@Qualifier注解可以指定Bean实例名
Java 配置注解
ID
DA
FA
@Configuration
声明一个Java的配置类,相当于Spring中的XML配置文件
XML
@ComponentScan
扫描使用的注解包,并创建指定的ConfigAnnotation的配置类
XML
基于注解的依赖注入 本文主要使用```@Override、@Resource、@Repository、@Controller、@Autowired、@Configuration、@ComponentScan等注解来实现Spring xml配置文件来实现配置、注解、依赖、注入等方式,而这也是Spring Boot所推荐的配置方式:
所需的外部Jar开发包 本文需实现基于注解的依赖注入,需要使用commons-logging-1.2.jar、spring-aop-5.1.4-RELEASE.jar、spring-beans-5.1.4.RELEASE.jar、spring-context-5.1.4.RELEASE.jar、spring-core-5.1.4.RELEASE.jar、spring-expression-5.1.4.RELEASE.jar等jar开发包引入至项目文件中WebContent/WEB-INF/lib目录下即可。
ID
DA
FA
TestDao.java
Dao
TestDaoImpl.java
@Repository
TestService.java
Service
TestServiceImpl.java
@Service、@Resource、@Override
TestController.java
@Controller、@Autowired
Controller
ConfigAnnotation.java
@Configuration、@ComponentScan
annotation
TestAnnotation.java
@Controller、@Autowired
Dao TestDao.java 1 2 3 4 5 package annotation.dao;public interface TestDao { public void save () ; }
TestDaoImpl.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package annotation.dao;import org.springframework.stereotype.Repository;@Repository("testDao") public class TestDaoImpl implements TestDao { @Override() public void save () { System.out.println("testdao save" ); } }
Service TestService.java 1 2 3 4 package annotation.service;public interface TestService { public void save () ; }
TestServiceImpl.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package annotation.service;import javax.annotation.Resource;import org.springframework.stereotype.Service;import annotation.dao.TestDao;@Service("testService") public class TestServiceImpl implements TestService { @Resource(name = "testDao") private TestDao testDao; @Override public void save () { testDao.save(); System.out.println("testService save" ); } }
Controller TestController.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package annotation.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import annotation.service.TestService;@Controller public class TestController { @Autowired private TestService testService; public void save () { testService.save(); System.out.println("testController save" ); } }
annotation ConfigAnnotation.java 1 2 3 4 5 6 7 8 9 10 11 12 13 package annotation;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration @ComponentScan("annotation") public class ConfigAnnotation { }
TestAnnotation.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package annotation.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import annotation.service.TestService;@Controller public class TestController { @Autowired private TestService testService; public void save () { testService.save(); System.out.println("testController save" ); } }
Spinrg jar Spring官网中主要建议开发者下载Maven和Gradle两种方式进行下载,如果不使用两者方式的开发者,可通过https://repo.spring.io/libs-release-local/org/springframework/spring/5.1.4.RELEASE/spring-framework-5.1.4.RELEASE-dist.zip直接下载Spring 5.1.4版本的Spring jar。 而在Spring jar文件解压后各个文件的说明如下:
ID
DA
FA
docs
用于存储包含Spring的API文档以及开发规范
/
libs
包含开发Spring应用所需要的JAR包以及源代码
/
RELEASE.jar 是Spring 开发所需要的jar 包
/libs
RELEASE-caradoc.jar Spring框架API文档压缩包
/libs
RELEASE-sources.jar 结尾的我文件是Spring框架源文件的压缩包
/libs
spring-core-5.1.4.RELEASE.jar、spring-beans-5.1.4.RELEASE.jar、spring-context-5.1.4.RELEASE-javadoc.jar 结尾的是Spring 核心容器的四个模块(Beans、Core、Context、SpEL)
/libs
schema
包含Spring 应用开发所需要的schema文件,主要定义了Spring的配置文件的约束
/
Commons-logging Spring主要依赖Apache Commons Logging组件,可通过https://downloads.apache.org//commons/logging/binaries/commons-logging-1.2-bin.zip下载,经解压后,主要使用commons-logging-1.2文件。
Spring 基本环境 导入 JRE 文件 在开发Spring应用的时候,需要引入四个基本核心类和一个Apache Commons Logging组件引入到WebContent\WEB-INF\lib\ 即可完成引入。
Spring Ioc 基本框架与流程 接口 TestDao.java Spring是解决业务逻辑层和其让他各层的耦合问题,因此他将面向接口的编程思想贯穿于整个系统之中应用:
1 2 3 4 package Dao;public interface TestOne { public void sayHello () ; }
接口实现类 TestDaoImpl.java 1 2 3 4 5 6 7 8 package Dao;public class TestDaoImpl implements TestDao { @Override public void sayHello () { System.out.println("Hello,world!" ); } }
spring 配置文件 applicationContext.xml 一般情况下,Spring不需要开发者手敲,可通过/docs/spring-framework-reference/core.html下API说明文档中的1.2.1. Configuration Metadata处直接复制即可:
1 2 3 4 5 6 <beans xmlns ="http://www.springframework.org/schema/beans" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" > <bean id ="test" class ="dao.TestDaoImpl" /> </beans >
测试类 Test.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import One.TestOne;public class Test { public static void main (String[] args) { @SuppressWarnings("resource") ApplicationContext appCon = new ClassPathXmlApplicationContext ("applicationContext.xml" ); TestDao testdao = (TestDao)appCon.getBean("test" ); testdao.sayHello(); } }
在执行测试类后,IDE控制台中将会输出接口实现类 TestOneImpl.java内中的”public void sayHello() {“下构造变量;。而整个输出的过程中,并没有使用new运算符来创建TestOneImpl类的对象,而是通过Spring容器来实现,而这个实现的过程就是 Spring IOC的工作机制,而这个工作机制也可以理解为工厂模式。
Spring 简介 Spring 框架可以在任何类型的部署平台为基于Java Web现代的企业应用程序而提供的全面编程和配置模型。是当前主流的Java开发框架之一,为企业级应用开发提供了丰富的使用功能。
Spring 的意思 在Spring的官方API帮助文档中,有一句官方的表述是: ”Spring 在不同的上下文中表示不同的事物,他可以用于指代Spring Framework项目的本身,而Spirng的意识是寓意,这一切都是从这里开始的 。随着时间的流逝,其他的Spring项目已经在Spring Framework基础上进行构建,通常人们说到Spirng的时候,他们将会表示整个项目的系列。如果有人跟你说的是Spring boot,那他一定不是泛指所有Spring项目,而是单指Spring boot这一系列。 “
Spring 概括 Spring是一个轻量级的开发框架,最初由Rod Johnson编写,在2003年6月首次在Apache 2.0许可证下发布,象征着Spring在那刻前正式开源,之后有很多开发者加入到一起来进行维护和开发,而Spring创建的主要目的就是解决企业应用开发的业务逻辑层的问题,是一个分层的轻量级开源框架(且一站式)
Spring 体系结构 Spring 常用结构 Spirng 本书所使用的结构 Data Access - Integration / World Wide Web(数据访问和集成/Web) Data Access / Integration
ID
DA
FA
JDBC
提供了一个JDBC的抽象层
消除了繁琐的JDBC编码和数据库厂商特有的错误代码解析
ORM
对流行的对象关系映射API的集成(Object-Relational apping),包括JPA、Hibenate
使用Spring-ORM可将这些O/R映射框架与Spring提供的所有功能结合使用
OXM
提供了一个支持对象/XML映射的抽象层实现
如JAXB、Castor、XML Beans、JiBX、XStream等
JMS
指Java消息传递服务,包含了用于生产和使用的消息功能
自Spring 4.1以后,提供那个了与Spring-messaging模块的集成
World Wide Web
ID
DA
FA
Web-Socket
提供了对WebSocket-based的支持
在Web应用中可以实现Web前端全双工通信的协议。
Web-Servlet(webmvc)
包含了用于Web应用程序的Spring MVC和 REST Web Services实现
提供了Spring下的MVC框架可以使全领域模型代码和web表单完全的分离,与Spring框架和其他所有功能进行集成
Web
提供了基本的Web开发集成功能
多文件上传功能、使用Servlet监听器初始化一个Ioc容器以及Web应用上下文
Portlet (Spring-webmvc-portlet)
提供Portlet环境中使用MVC的实现,并反映了Spring-webmvc的模块功能
Webflux
是一个非阻塞式函数Reactive Web框架
可用于建立异步、非阻塞、事件驱动服务,并拥有很好的扩展性
AAIM(Aop、Aspects、Instrumentation、Messaging) 面向切面编程(AOP) 和 使用容器(Instrumentation) 该层主要有AOP、Aspects、Instrumentation、Messaging四个模块,其主要模块响应的功能有:
ID
DA
FA
AOP
提供了一个符合APO要求的面向切面的编程实现
允许在定义方法拦截器和切入点,可将代码按照功能进行分离,方便干净的进行解藕
Aspects
是一个强大且成熟的面向切面编程(AOP)框架
提供了AspectJ的集成功能
Instrumentation
提供了类植入(Instrumentation)支持和类的加载器实现,而Instrumentation提供了一种虚拟机级别的支持的AOP实现方式
无需对JDK进行改动或升级,可实现AOP的某些功能
消息(Spring-Messaging) Messaging是Spring 4.0所增加的信息模块“Spring-messaging”,其主要提供了对信息传递的结构体系和协议支持,且支持为STOMP、WebSocket等子协议时候使用。
Spring 核心容器 Spring的核心容器是其他模块建立的基础部分,主要由Spring-core、Spring-beans、Spring-Context、Spring-context-support、Spring-expression(Spring表达式语言)模块所组成:
ID
DA
FA
Spring-core
提供了框架的基本组成部分
控制反转(ioc,Inversion of Control)、依赖注入(DI,Dependency Injection)
Spring-Beans
是工厂模式的经典实现,主要移除了编码式的单列需要,可从配置和以来从实际编码逻辑中耦合
提供了BeanFactory
Spring-context
主要建立在core、Beans之上,提供了一个框架式的对象访问方式,是一个访问定义、配置、任何对象的媒介
context
Spring-context-support
支持整合得到第三方库到Spring应用程序上下文,用于高速缓存(EhCache,JCache)和任务调度(COmmonJ,Quartz)的支持。
Spring-expression
提供了强大的表达式语言,用于在运行时查询和操作对象图 ,是JSP2.1规范中定义统一表达式语言扩展(Unified EL)
支持set和get属性值、属性赋值、方法调用、访问数组集合等索引内容,逻辑运算符、命名变量、通过名字从 ```Spring-Ioc容器检索对象,支持列表投影、选及其常见列表聚合
Spring-Beans 工厂模式 Spring-Beans工厂模式主要是代替了Java中的new 的实例化操作, 虽然这样做会做多一点工作,但是会增加整个项目的可扩展性。也就是说,当需要实例化类或方法的时候,new的工作会由一个class类所执行,所以在本类之中可以直接使用工厂模式进行开发。
Servlet过滤器是可以理解为,当用户浏览某个Web servler的时候,此实现时可以利用过滤器(Filter)来实现特定用户的访问。过滤器主要位于服务器处理请求或服务器响应请求职权,即通过过滤浏览器对服务器的请求,也可过滤服务器对浏览器的响应。Servlet过滤器主要用于验证、过滤等功能,而Servlet过滤器可在web.xml中进行定义,如果去除web.xml中过滤器的文件条目,则Servlet 过滤器也会被删除。
Filter类与Filter对象和方法
ID
DA
FA
public void init(FilterConfig fConfig)
方法用于初始化过滤器对象
可设置初始参数 (可用getInitParameter(String paramName)获取参数值)
public void doFile(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException)
当Web servlet对象调用service()的时候将会自动调用doFile()
public void destroy()
当Web Server终止服务的时候,destroy()将会被执行,使得Filter对象摧毁
ID
DA
FA
chain.doFilter(request, response)
执行下一个过滤器,如果没有下一个过滤器,将会返回请求目标程序。
如果没有执行chain.doFilter()。则请求不会继续给下一个过滤器或某个目标的应用程序,即拦截请求
会话跟踪在通常是用于维持用户数据和状态的方法,通常分为Cookie和session两项常用技术。在Servlet也被称之为Servlet会话管理,也可以称之为“会话追踪”都是没有问题的。当用户通过浏览器来访问和进行交互请求的时候,我们需要使用Cookie和session两项中的任意一项来维护状态,每次用户向服务器请求时,服务器就将会该请求视为新的请求。所谓为了避免这种问题,需要区别进行对待,在这种情况中会话跟踪技术慢慢的发展和壮大。
Cookie Cookie即“小饼干”,是为了Web站点进行辨别用户从而实现免密登入来进行访问,和Session的区别之处在于Cookie将数据存储于客户端中,而Session存储与服务器之中。Cookie可以包含用户信息、小文本文件等信息,通过Cookie技术,可以让用户何时访问Web服务器,Web都可以通过访问或获取存储于用户本地之中的Cookie进行利用。
1 Cookie vistedCountC = new Cookie ("name", "null");
通过上方的Cookie够走可以看出,name可指定Cookie的属性名,第二个参数null可以用于指定值。创建完Cookie可以使用addCookie()添加到响应对象之中那个,从而实现存储于用户本地计算机上。如果想实现访问或获取存储于用户计算机之中的Cookie的数据可以通过getCookies()来进而获取。
在Cookie中有一定的存活时间,不可能在客户端中永久保存,这样会给安全性带来问题,在默认的情况之下Cookie在用户关闭之时将会自动会被销毁,如果想自行进行定义可以使用setMaxAge(int time)方法来设置Cookie的存货时间。
ID
DA
FA
AddCookie()
将Cookie添加到响应对象中
即存储于用户计算机中
getCookies()
来获取用户计算机之中的Ckkoie数据
setMaxAge(int time)
设置Cookie存活时间
如为整数则以秒进行计算,为负数则表示为临时Cookie,但为0则表明通知浏览器删除相应Cookie数据
访问次数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 package Cookie; import java.util.Date; import java.text.SimpleDateFormat; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class TimeCookie */ @WebServlet("/TimeCookie") public class TimeCookie extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TimeCookie() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); // Time PrintWriter printWriter = response.getWriter(); SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime = simpledateformat.format(new Date()); // 访问时间 String lastVistTime = ""; // 访问次数 int vistedCount = 0; // 获取Cookie Cookie[] myCookies = request.getCookies(); if (myCookies != null) { for (Cookie cookie:myCookies) { // 是否为最近访问的Cookies if ("lastVist".equals(cookie.getName())) { lastVistTime = cookie.getValue(); } if ("vistedCount".equals(cookie.getName())) { vistedCount = Integer.valueOf(cookie.getValue()); } } } if (!"".equals(lastVistTime)) { printWriter.println("上次访问时间" + lastVistTime); } // 访问次数 printWriter.println("访问次数" + (vistedCount +1)); // 创建 Cookie Cookie lastVistTimeC = new Cookie("lastVist",nowTime); // Cookie 生存时间 lastVistTimeC.setMaxAge(365*24*60*60); // 访问时创建同名cookie Cookie vistedCpimtC = new Cookie("vistedCount", (vistedCount +1) + ""); // Cookie Timesize vistedCpimtC.setMaxAge(365*24*60*60); // 将Cookie添加到响应客户端中 response.addCookie(lastVistTimeC); response.addCookie(vistedCpimtC); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
登录演示
ID
DA
FA
Lagin
登录界面
JSP
LoginServlet
登入验证
Servlet
LogoutServlet
Cookie注销
Servlet
ProfileServlet
获取Cookie
Servlet
Lagin.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="LoginServlet" method="post" > user:<input type="text" name="name" ></br> Pass:<input type="password" name="password" ><br> <input type="submit" value="login" > </form> </body> </html>
LoginServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package Cookie; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // user and password String name = request.getParameter("name"); String password = request.getParameter("password"); // pass or user if (password.equals("admin")) { out.println("Yes!"); out.println("<br>User" + name); // Cookie Cookie cookie = new Cookie("name", name); response.addCookie(cookie); // 添加到响应头 } else { out.println("No!"); request.getRequestDispatcher("login.jsp").include(request, response); } out.close(); } }
LogoutServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package Cookie; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // user and password String name = request.getParameter("name"); String password = request.getParameter("password"); // pass or user if (password.equals("admin")) { out.println("Yes!"); out.println("<br>User" + name); // Cookie Cookie cookie = new Cookie("name", name); response.addCookie(cookie); // 添加到响应头 } else { out.println("No!"); request.getRequestDispatcher("login.jsp").include(request, response); } out.close(); } }
ProfileServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 package Cookie; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // user and password String name = request.getParameter("name"); String password = request.getParameter("password"); // pass or user if (password.equals("admin")) { out.println("Yes!"); out.println("<br>User" + name); // Cookie Cookie cookie = new Cookie("name", name); response.addCookie(cookie); // 添加到响应头 } else { out.println("No!"); request.getRequestDispatcher("login.jsp").include(request, response); } out.close(); } }
session session即HttpSession对象实现会话跟踪技术,而Session和Cookie的区别就是当用户第一次访问服务器的时候将会创建一个session对象,之后将会为其分配一个唯一的会话标识(sessionId)之后将会以"JSESSIONID"作为属性名保存在客户端cookie中
Session 对象
ID
DA
FA
getSession()
返回与此请求关联的当前会话
如果没有则创建一个
getSession (boolean create)
返回与此请求关联的当前HttpSession
或者如果当前没有create为true,则创建一个对象
getAttribute()
获取指定属性
Session 接口
ID
DA
FA
getRequestedSessionId()
返回包含session唯一标识符的字符串
getCreation Time()
返回创建此会话的时间
以格林尼治标准时间1970年1月1日午夜以来的毫秒数来作为单位
getLastAccessedTime()
返回客户端最后一次发送与此会话相关的请求时间
以格林尼治标准时间1970年1月1日午夜以来的毫秒数来作为单位
invalidate()
使得此会话无效,之后取消绑定到该会话中的任何对象
Session 获取用户名 通过setSession() 和getAttribute()对象,实现了Servlet通过session来获取jsp中用户填写的数据并使用了url重写:
login.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="finstServlet" > Username<input type="text" name="nameuser" > <input type="submit" value="up" > </form> </body> </html> ```` #### session.java ```java package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/secondServlet") public class session extends HttpServlet { private static final long serialVersionUID = 1L ; public session () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false ); String uaname = (String)session.getAttribute("uname" ); out.println("Hello:" + uaname); out.close(); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
finstServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/finstServlet") public class attribute extends HttpServlet { private static final long serialVersionUID = 1L ; public attribute () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); String name = request.getParameter("nameuser" ); out.println("用户: " + name); HttpSession session = request.getSession(); session.setAttribute("uname" , name); out.println("| <a href='secondServlet'>secondServlet</a>" ); out.close(); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
secondServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/secondServlet") public class secondservlet extends HttpServlet { private static final long serialVersionUID = 1L ; public secondservlet () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(false ); String uaname = (String) session.getAttribute("uname" ); out.println("Hello:" + uaname); out.close(); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
获取session id 从Session获取用户名的基础上,我们在finstServlet中加入(getRequestedSessionId)即可获取到session ID:
finstServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/finstServlet") public class firstservlet extends HttpServlet { private static final long serialVersionUID = 1L ; public firstservlet () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); String name = request.getParameter("nameuser" ); out.println("用户: " + name); HttpSession session = request.getSession(); session.setAttribute("uname" , name); out.println(request.getRequestedSessionId()); out.println("| <a href='secondServlet'>secondServlet</a>" ); out.close(); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
URL重写 使用url重写的优势在于无论浏览器是否禁用cookie或session,传输都将有效,也不需要在每个页面上提交额外的网关,关于重写url和不重写url的区别可以是:
重写 secondServlet.java url finstServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/finstServlet") public class firstservlet extends HttpServlet { private static final long serialVersionUID = 1L ; public firstservlet () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); String name = request.getParameter("nameuser" ); out.println("用户: " + name); HttpSession session = request.getSession(); session.setAttribute("uname" , name); out.println("| <a href='secondServlet?uname=" + name + "'>secondServlet</a>" ); out.close(); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
表单域隐藏 表单域和上述URL重写区别在于URL重写会将原先 http://localhost:8080/Testsp/secondServlet的链接改为http://localhost:8080/Testsp/secondServlet?uname=Adminsitrator,而隐藏表单域则会将URL重写后的链接写为“http://localhost:8080/Testsp/secondServlet”。表单域的有点则是不管Cookie是否禁用,都合URL重写一样,可以正常使用。
login.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="finstServlet" method="post" > Username:<input type="text" name="nameuser" > <input type="submit" value="up" > </form> </body> </html>
finstServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 package session; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class finstServlet */ @WebServlet("/finstServlet") public class firstservlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public firstservlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("nameuser"); out.print("User: " + name); /* out.print("<form action='secondServlet'>"); out.print("<input type='hidden' name='namer' value='" + name + "'>"); out.print("<input type='submit' value='up'>"); out.print("</form>"); */ out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
Java Servlet 即“服务器连接器”,主要用于创建Web应用,可在交互式地浏览和生成数据(动态Web内容)。当用户请求一个JSP页面的Web服务器,Servlet会自动生成一个对应的Java对文件。通过编译该Java文件用编译得到的字节码文件在服务器端创建一个Servlet对象。但在项目的实际需求之中,Web服应用需要Servlet对象有特定的功能,需要编写和创建Servlet对象和类就是本章重点介绍的一部分。
部署 Servlet 相关的接口和类
ID
DA
protected void doGet(HttpServletRequest request, HttpServletResponse response)
请求指定资源
protected void doPost(HttpServletRequest request, HttpServletResponse response)
向指定的资源提交要被处理的数据
创建一个Servlet类 Eclipse Web 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package demofile;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/NewFile") public class NewFile extends HttpServlet { private static final long serialVersionUID = 1L ; public NewFile () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: " ).append(request.getContextPath()); response.setContentType("text/html;charset=utf-8" ); PrintWriter out = response.getWriter(); out.println("<br>" ); out.println("Hello,world!" ); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
需要注意的事情是,Servlet可使用Eclipse Web 内自带的Servlet类型文件进行直接的创建,Servlet类必须要有一个包名,不然的话不是一个完整的Servlet类文件。在生成Servlet的同时,Eclipse会自动创建和部署有关的xml文件信息,通常该文件名称为web.xml。
@WebServlet @WebServlet用于将一个类声明为Servlet对象,该注解将会在开始运行服务器时将部署时被Web容器根据Servlet对象进行处理.@WebServlet (name = "newfile", urlPatterns = {"newfile"}) 有兴趣的读者可自行进行了解或学习。
Servlet 生命周期 一个Servlet生命周期主要分为三个过程,分别为:初始化对象(int)、方法响应请求(service)、对象消亡(destroy),也就是说当Servlet对象第一次被请求加载的时候会创建一个Servlet对象,主要调用int()方法进行初始化。Service()方法响应请求,创建的Servlet对象之后调用service()方法响应客户端进行请求。当服务器进行关闭时,Servlet对象会调用destroy()方法来使得对象销毁。
三个周期输出 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package demofile;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/NewFile") public class NewFile extends HttpServlet { private static final long serialVersionUID = 1L ; public NewFile () { super (); } @Override public void init () throws ServletException { System.out.println("初始化时输出" ); } @Override protected void service (HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { System.out.println("开启服务时输出" ); } @Override protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override public void destroys () { System.out.println("结束时输出" ); } }
JSP 调用Servlet NewFile.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="loginServlet" method="post" > <%-- User = user \ Pass = pass submit up \ reset set--%> <table> <tr> <td>User:</td> <td><input type="text" name="user" /></td> </tr> <tr> <td>pass:</td> <td><input type="text" name="pass" /></td> </tr> <tr> <td><input type="submit" value="up" /></td> <td><input type="reset" value="set" ></td> </tr> </table> </form> </body> </html>
loginServlet.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 package demofile;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/loginServlet") public class loginServlet extends HttpServlet { private static final long serialVersionUID = 1L ; public loginServlet () { super (); } protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); String name = request.getParameter("user" ); String password = request.getParameter("pass" ); out.println("<html><body>" ); if (name == null || name.length() ==0 ) { out.println("user null" ); } else if (password == null || name.length() == 0 ) { out.println("pass null" ); } else if (name.length() > 0 && password.length() >0 ) { if (name.equals("sun" ) && password.equals("kun" )) { out.println("ok" ); } else { out.println("no" ); } } out.println("</body></html>" ); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: " ).append(request.getContextPath()); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
ID
DA
getParameter
获取input输出数据
Servlet MVC MVC即“Model、View、Controller”的缩写,分别代表Web应用程序的三种职责,即:
ID
DA
FA
模型
用于存储数据以及处理用户请求的业务能力
一个或多个JavaBean对象、用于存储数据(实体模型)和处理业务逻辑
页面
向控制器提交数据,显示模型中的数据
一个或多个Jsp页面,向Servlet提交数据和为模型提供数据显示(JSP主要使用HTML来标记JavaBean来显示数据)
Servlet
根据页面提出的请求来判断将请求和数据交给那个模型中处理,处理后的那个页面更新显示
一个或多个Servlet对象,根据页面提交的请求进行控制。(即将请求转发给处理业务逻辑的JavaBean,并将处理结果存放在JavaBean中,市输出给视图显示)
JSP、Servlet、JavaBean实现MVC 通过使用JSP、Servlet、JavaBean来实现i个简单的MVC用户登录验证程序,其中包括MVC模型、页面、Servlet:
ID
DA
FA
User
用于创建模型,存储用户信息
JAVA
UserCheck
判断用户名和密码是否正确
LoginCheck
用于完成请求控制
loginCheak.jsp
用于编写登入界面
JSP
loginOk.jsp
登录成功页面
User.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package demofile; public class User { private String name; private String password; public String getName () { return name; } public void setName (String name) { this .name = name; } public String getPassword () { return password; } public void setPassword (String password) { this .password = password; } }
UserCheck (Service) 1 2 3 4 5 6 7 8 9 10 11 12 13 package service; import demofile.User; public class UserCheck { public boolean validate (User user) { if (user!=null &&user.getName().equals("Sun" )) { if (user.getPassword().equals("kun" ))return true ; else return false ; } return false ; } }
LoginCheck (Servlet) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 package servlet; import java.io.IOException; import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import service.UserCheck;import demofile.User; @WebServlet(name="LoginCheckServlet",urlPatterns= {"/LoginCheckServlet"}) public class LoginCheck extends HttpServlet { private static final long serialVersionUID = 1L ; public LoginCheck () { super (); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8" ); String nameuser = request.getParameter("nameuser" ); String password = request.getParameter("password" ); User user=new User (); user.setName(nameuser); user.setPassword(password); UserCheck uc=new UserCheck (); if (uc.validate(user)) { request.setAttribute("user" , user); RequestDispatcher dis = request.getRequestDispatcher("loginOk.jsp" ); dis.forward(request, response); }else { response.sendRedirect("loginCheck.jsp" ); } } }
loginCheak (Jsp) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" > <title>loginCheck.jsp</title> </head> <body> <form action="LoginCheckServlet" methods="get" > <table> <tr> <td>User:</td> <td><input type="text" name="nameuser" /></td> </tr> <tr> <td>Pass:</td> <td><input type="password" name="password" ></td> </tr> <tr> <td><input type="submit" value="Up" /></td> <td><input type="reset" value="Set" /></td> </tr> </table> </form> </body> </html>
loginOK (Jsp) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@page import ="demofile.User" %> <!DOCTYPE html"> <html> <head> <meta http-equiv=" Content-Type" content=" text/html; charset=UTF-8 "> <title>loginSuccess.jsp</title> </head> <body> <jsp:useBean id=" user" type=" demofile.User" scope=" request"/> User:<jsp:getProperty property=" name" name=" user"/> success! </body> </html>
JavaBean是遵循一定标准,用Java语言别编写的类,该类的实例称为一个JavaBean,JavaBean主要遵循了一下约定:
有一个无参数的构造函数;
可序列化
提供设置和获取属性的方法,(称之为get和set方法)
总之,编写玩一个JavaBean就是编写一个Java类,在编写的过程中,该类必须引入包名package com.bean。通过JavaBean可以将许多对象封装成一个对象 ,因此可以从多个位置访问该对象从而易于维护。
Bean 方法
ID
DA
FA
useBean
连接Bean 类
setProperty
向Bean类中的构造方法插入数据
getProperty
访问Bean类中的构造方法数据
JavaBean 创建一个JavaBean类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package demofile;public class Demo implements java .io.Serializable { private String id; private String name; public Demo () {} public void setId (String id) { this .id=id; } public String getId () { return id; } public void setName (String name) { this .name=name; } public String getName () { return name; } }
访问与写入JavaBean构造方法 1 2 3 4 5 6 7 8 9 10 11 12 package demofile;public class Test { public static void main (String args[]) { Demo demo = new Demo (); demo.setId("10" ) demo.setName("Name = Yes" ); System.out.println(demo.getId()); System.out.println(demo.getName()); } }
JspBean 创建一个JspBean类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package demofile;public class Demo implements java .io.Serializable { private String name; private String username; public String getName () { return name; } public void setName (String name) { this .name = name; } public String getUsername () { return username; } public void setUsername (String username) { this .username = username; } }
访问与写入JspBean构造方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <p>NewFile.jsp</p> <hr> <%-- 连接 Java Bean类 --%> <jsp:useBean id="demo" class="demofile.Demo" /> <%-- 向JSP name构造函数插入数据 --%> <jsp:setProperty property="name" name="demo" value="Admin" /> <jsp:setProperty property="username" name="demo" value="Administrator" /> <%-- 访问JSP Bean类 --%> <p>名称:<jsp:getProperty property="name" name="demo" /></p> <p>帐号:<jsp:getProperty property="username" name="demo" /></p> </body> </html>
对象的作用域就是对象的生命周期和可访问性 ,在JSP中主要拥有四种作用域 ,即:页面域、请求域、会话域、应用域。
ID
SM
DA
页面域 (page scope)
页面域的生命周期是指页面的执行时间
存储在页面域的对象只能在他所在的页面进行访问 。
请求域 (request scope)
请求域的生命周期是指一次的请求过程
存储在请求域之中的对象只能在请求过程中才能访问
会话域 (session scope)
会话域的生命周期是指莫个客户端与服务器连接的所用时间
客户端在第一次访问服务器时会创建绘画,在会话过期之前,存储在会话域中的对象都可以被访问
应用域 (application scope)
服务器开始执行服务到服务器关闭的时间就是应用域的生存时间
存储在应用域中的对象在整个程序运行期间可以被所有的JSP和服务器连接器(Servlet)共享访问。
作用与对应函数
ID
DA
pageContext
页面域
requesteContext
请求域
sessionContext
会话域
applicationContext
应用域
页面域 1 2 3 4 5 6 7 8 9 10 11 <% int pagecontext = 1 ; if (pageContext.getAttribute("pageContext" ) != null ) { pagecontext = Integer.parseInt(pageContext.getAttribute("pageContext" ).toString()); pagecontext++; } pageContext.setAttribute("pageCount" , pagecontext); %> <p>page:<%=pagecontext %></p>
请求域 1 2 3 4 5 6 7 8 9 <% int requestcontext = 1 ; if (request.getAttribute("requestContext" ) !=null ) { requestcontext = Integer.parseInt(request.getAttribute("requestContext" ).toString()); requestcontext++; } request.setAttribute("requestContext" , requestcontext); %> <p>request:<%=requestcontext %></p>
会话域 1 2 3 4 5 6 7 8 9 <% int sessioncontext = 1 ; if (session.getAttribute("sessionContext" ) !=null ) { sessioncontext = Integer.parseInt(session.getAttribute("sessionContext" ).toString()); sessioncontext++; } session.setAttribute("sessionCount" ,sessioncontext); %> <p>session:<%=sessioncontext %></p>
会话域访问范围为当前浏览器的绘画,因此刷新页面访问会计数增加,但是新开浏览器时则会重置为0;
应用域 1 2 3 4 5 6 7 8 9 <% int applicationcontext = 1 ; if (application.getAttribute("applicationContext" ) !=null ) { applicationcontext = Integer.parseInt(application.getAttribute("applicationContext" ).toString()); applicationcontext++; } application.setAttribute("applicationContext" ,applicationcontext); %> <p>application:<%=applicationcontext %></p>
应用域为整个应用,只要服务器不停止运行,计数就会累计进行增加
内置对象是值这些对象在Java Server Pages页面中不需要声明和实例化,可以直接在Java程序片和Java表达式中部分使用,通常这种对象被称之为“Jsp内置对象”。
常用的JSP内置对象主要分为request、responese、out、session、application、pageContent、page、config、exception等内置对象的使用方法。
四大类,九大对象 JSP内置对象由WEB服务器负责实现和股哪里,JSP九个功能强大的内置对象,主要分为四大类
ID
DA
FA
input / output
request 、response、out
作为客户端和服务器之间的通信桥梁
request
表示客户端对服务器端发送请求
response
表示服务器对客户端的响应
out
负责吧处理结果输出到客户端
context
session、application、pageContext
与上下文(Context)有关的内置对象
session
表示浏览器与服务器会话的上下文环境
application
表示应用程序的上下文环境
pageContext
表示当前JSP页面上的上下文环境
servlet
page、config
page
表示JSP文件转换为Java文件后的Servlet对象
config
表示JSP 文件转换JAVA文件后的服务连接器(Servlet)
error
exception
当JSP页面发生错误时将产生异常,而该对象就是用于处理这个异常的
request request 内置对象常用方法
ID
DA
Object getAttribute(String name)
返回制定属性的属性值
Enumeration getAttributeNames()
返回所有可用的属性名枚举
String getCharacterEncoding()
返回字符编码格式
int getContentLength()
返回请求体字节数
String getContentType()
返回请求体的MIME类型
ServletInputStream getInputStream()
返回请求提中一行的二进制流
String getParameter(String name)
获取提交数据
Enumeration getParameterNames()
可用参数名的枚举
String[] getParameterValues(String name)
返回包含参数Name所有值的数组
String getProtocol()
返回请求用的协议类型及版本号
String getServerName()
返回接受请求 服务器主机名
int getServerPort()
返回服务器接受此请求所用的端口号
String getRemoteAddr()
返回发送此请求的客户端IP地址
String getRemoteHost()
返回发送此请求的客户端主机名
void setAttribute (String key,Object obj)
设置属性的属性值
String getRealPatch(String path)
返回一个虚拟路径的真实路径
request.getParameter(String name) 获取提交数据 NewFile.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="NewFile1.jsp" > <input type="text" name="data" > <input type="submit" value="up" > </form> </body> </html>
NewFile1.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% String requestdata = request.getParameter("data" ); out.println(requestdata); %> </body> </html>
String[] getParameterValues(String args) 返回参数名称的所有参数名 NewFile.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="NewFile1.jsp" > 城市:<br/> <input type="checkbox" name="data" value="Beijing" />Beijing <input type="checkbox" name="data" value="Shenzhen" />Shenzhen <input type="checkbox" name="data" value="Jilin" />Jilin <input type="submit" value="up" > </form> </body> </html>
NewFile1.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> 城市:<br> <% String Cities[] = request.getParameterValues("data" ); for (int one = 0 ; one < Cities.length; one++) { out.println(Cities[one] + "<br>" ); } %> </body> </html>
response 当客户端请求服务器的一个页面时会提交一个HTTP请求,服务器收到请求后返回一个HTTP响应。之后request进行封装,与request对象相互映照的是response对象。
动态改变 contentType值 (setContentType) JSP页面使用Page指令标记了设置页面的contentType属性值,response对象按照此属性值的方式对客户端作出相应,page指令中只能为contentType属性指定一个值,如果改变值可以通过response对象调用一个setContentTyoe(String s)方法来重新设置contentType的属性值。 客户端通过单击页面上的不同按钮可以改变页面响应的MIME类习惯,当点击word按钮时,jsp页面动态改变contentType的属性值为application/msword,从而启动本地Word软件来显示当前页面内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <form action="" method="post" > <p>Hello,response</p> <input type="submit" value="word" name="submit" > <% String str = request.getParameter("submit" ); if ("word" .equals(str)) { response.setContentType("application/msword" ); } %> </form> </body> </html>
response可以通过setHeader(String name,String value)来设置指定名字的HTML文件头值,以用于操作HTTP文件头。如实现每页三秒刷新一次,那么可以使用```setHeader(“refesh”,”3”)即可。
1 2 3 4 <% out.println("Hello,world" ); response.setHeader("refresh" ,"3" ); %>
三秒跳转 1 2 3 4 <% out.println("3m ->NewFile.jsp" ); response.setHeader("refresh" ,"3;url=NewFile.jsp" ); %>
利用response对象的setHeader方法来实现3秒后跳转至“NewFile.jsp”文件之中。
重定向 (sendRedirect) 需要将当前页面跳转至另外一个页面时,即实现HTML中的<a>效果,可以使用reponse对象的sendRedirect(String url)方法进行重定向。
NewFile.jsp 1 2 3 4 5 6 <form action="NewFile1.jsp" method="post" name=form> <p>password</p> <br> <input type="password" name="pass" > <input type="submit" value="up" > </form>
NewFile1.jsp 1 2 3 4 5 6 7 8 <% String str = request.getParameter("pass" ); if (!"12345" .equals(str)) { response.sendRedirect("NewFile.jsp" ); } else { out.println("Hello,world!" ); } %>
forward forward和上述response对象的区别在于,forward可以不用跳转单纯的在本页显示另一个页面的信息,而response必须以跳转的形式才可以显示另一个解界面信息。
NewFile.jsp 1 2 3 <jsp:forward page="NewFile1.jsp" > <jsp:param value="hello" name="user" /> </jsp:forward>
NewFile1.jsp 1 2 3 4 <p>NewFile1.jsp</p> <%= request.getParameter("user" ) %>
ID
DA
FA
setContentType
修改response响应
setHeader
操作页面消息头
刷新、跳转
sendRedirect
实现页面跳转
重定向
forward
服务器端跳转、但URL保持不变
out 在input/output类别之中,out主要功能就是负责把处理结果输出到客户端主要共五个方法如下:
ID
DA
DF
void clear()
清除缓存区内容
void clearBuffer()
清除缓存区当前内容
void flush()
清空流
void close()
关闭输出流
void println()
输出各种数据类型
void newLine()
输出一个换行符号
int getBufferSize()
返回缓存区字节数
如不设缓存数则为0
int getRemaining()
返回缓存区剩余大小
boolean isAutoFlush()
返回缓存区满时是自动清空还是输出异常
缓存区剩余大小 (out.Remaining) 1 2 3 4 5 6 7 8 9 10 11 12 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <%=out.getRemaining()%> byte <br><%--返回缓存区剩余大小 --%> </body> </html>
输出各种类型(println) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% out.println("<p>Hello,world!</p>" ); %> </body> </html>
session 浏览器会与Web服务器之间使用HTTP协议进行通信,客户端向服务器发出Request(请求)服务器返回response(响应),之后链接就会被关闭了。而这时,在服务端不必保留链接的相关信息,所以当时的开发人员就想法设想采取某种手段来记录每个客户端的连接信息。通常我们可以使用session来存放有关的链接信息
session对象ID 当访问一个Web服务器的时候,Web服务器会给每个访问的用户分配和自动创建一个session对象,每个session标识都是一个在当时期间内都具有唯一性的
获取session ID (getId) 1 2 3 4 5 <% String string = session.getId(); out.println(string); %>
或
1 2 3 4 5 <% String string = session.getId(); %> <%=string %>
需要注意的是,session Id在当前服务内是具有唯一性的,比如在“http://zsdk.org.cn/”下的session ID是```7170F444E491358B191187B0400291C6``,则在另一个服务器下(http://jiangxue.org.cn/)又是另一个session ID了
session 获取与存储数据 提交数据 (NewFile.jsp) 1 2 3 4 <form action="NewFile1.jsp" method="post" > <input type="text" name="tame" > <input type="submit" name="submit" value="up" > </form>
存储数据 (NewFile1.jsp) 1 2 3 4 <% String tame = request.getParameter("tame" ); %>
输出session 数据 (NewFile.jsp)
session 生命周期 session的生命周期主要依赖于以下几个方式:
session对象是否调用invalidata()方法使session ID 失效;
session 对象是否达到session ID的最长等待时间;
用户是否关闭浏览器 在session中,也为开发者提供了很多关于session生命周期的对象于方法,分别为:
ID
DA
FA
long getCreation Time()
返回session创建的时间
long getLastAccessedTime()
返回session用户最后一次请求的时间
void invalidate()
使session ID失效
void setMaxInactiveInterval()
设置两次请求的间隔时间
默认为秒
boolean isNew()
判断用户是否已经进入服务器创建的session
session 创建时间 (long getCreation Time) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <%@ page import ="java.util.*" %> <%@ page import ="java.text.*" %> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% Date createTime = new Date (session.getCreationTime()); out.println(createTime); %> </body> </html>
或
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <%@ page import ="java.util.*" %> <%@ page import ="java.text.*" %> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% long sessiontime = session.getCreationTime(); Date timeout = new Date (sessiontime); out.println(timeout); %> </body> </html>
需要注意,在此段代码块之中我们引入了<%@ page import="java.util.*"%>包和<%@ page import="java.text.*">。主要用于将获取的session id创建时间转换为Date可读且标准的时间形式。
application application主要表示应用程序的上下文环境,而application也提供了一个存储数据的支持,而application可以提供一个共享的对象,这弥补了session的存储对象不足的问题。application用于任何用户访问同一个application对象,而生存周期直到服务器关闭这个application才会被取消:
ID
DA
FA
public void setAttribute(String key, Object obj)
将参数obj保指定保存在key中
key 为所保存对象的一个关键字
public void getAttribute(String key)
获取application中关键字是key 的对象
public void removeAttibute(String key)
从application关键字中删除key所对应的对象
public Enumeration getAttributeNames()
产生一个枚举对象
该对象可以使用nextElements()遍历
getMajorVersion()
获取服务器支持Servlet主版本号
getMinorVersion()
获取服务器支持 Servlet版本号
getServerInfo()
Java Server pages Tomcat 版本号
Java Server pages Tomcat 版本号 (getServerInfo) 1 2 <p>Java Server pages Tomcat 版本号</p> <%=application.getServerInfo()%>
获取当前访问数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% int n = 0 ;if (application.getAttribute("num" )==null ) n=1 ; else { String string = application.getAttribute("num" ).toString(); n=Integer.valueOf(string).intValue()+1 ; } application.setAttribute("num" ,n); out.println("您是:" + application.getAttribute("num" ) + "位用户" ); %> </body> </html>
pageContext pageContext主要表示当前JSP页面上的上下文对象,也表示当前页面运行环境,也就是说,PageContext可以访问本页面所有的session ,也可以获取本页面所在的application的某一些属性值,虽然是这样,但是在实际的开发过程之中,很少使用pageContexrt调用对象。。
ID
DA
ServletRequest getRequest()
获取当前JSP页面的请求(request)对象
ServletResponse getResponse()
获取当前JSP页面的响应(response)对象
ServletContext getServleContext()
返回当前页面的application对象
HttpSession getSession()
返回当前页的session对象
Object getpPage()
返回当前页的page对象
Exception getException()
返回当前页的Exception对象
获取 session 数据 (getSession) 1 2 3 4 5 6 <% session.setAttribute("one" ,"pageContext" ); %> <%=pageContext.getSession().getAttribute("one" ) %>
page page主要表示JSP文件转换为Java文件后的Servlet对象,代表JSP页面本身(即this),因此他可以调用Servlet(服务器连接端)类所定义的方法,在实际的开发过程中,基本上很少使用page对象。
ID
DA
getServletInfo()
使用this获取本页面说明信息
((HttpsJspPage)page)getServletInfo()
使用page获取本页的说明信息
getClass()
返回当前Object类
int hashCode
返回Object的hash代码
获取本页面说明信息 (this) 1 2 3 4 5 6 7 8 9 10 11 12 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <%=this .getServletInfo() %> </body> </html>
返回当前Object类 (getClass) 1 2 3 4 5 6 7 8 9 10 11 12 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <%=page.getClass() %> </body> </html>
config config即页面配置对象,表示JSP 文件转换JAVA文件后的服务连接器(Servlet)的ServletConfig对象,主要存储一些初始数据。config和page对象一样,相比之前的九大对象很少被用到。
ID
DA
getServletName()
获得JSP页面转义后Servlet服务器连接端的对象名
getInitParameter()
返回指定名字的初始参数值
获得JSP页面转义后Servlet服务器连接端的对象名 (getServletName) 1 2 3 4 5 6 7 8 9 10 11 12 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <%=config.getServletName() %> </body> </html>
exception exception主要用于当JSP页面发生错误时将产生异常,而该对象就是用于处理这个异常的,如果JSP页面需要使用该对象,必须将该页面的page指令的inErrorPage属性设置为true,否则无法编译。
ID
DA
getMessage()
返回描述异常的消息
toString()
返回关于异常的简短描述消息
printStackTrace()
显示异常及栈轨迹
FillInStackTrace()
重写异常的执行栈轨迹
返回描述异常的消息 NewFile.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <%@ page language="java" contentType="text/html; charset=UTF-8" errorPage="NewFile1.jsp" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <% int one = 10 ; int two = 0 ; %> <%= (one/two) %> </body> </html>
NewFile1.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 <%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" > <title>Insert title here</title> </head> <body> <p>获取错误</p> <%=exception.getMessage() %> </body> </html>
📖 more posts 📖