赞
踩
web开发:
在Java中,动态web资源开发的技术统称为lavaWeb;
web应用程序:可以提供浏览器访问的程序;
web应用程序编写完毕后,若想提供给外界访问:需要一个服务器来统一管理;
页面会动态展示:“Web的页面展示的效果因人而异";
缺点:
优点:
新手村:–魔鬼训练(分析原理,看源码)–>PK场
ASP:
JSP/Servlet:
B/S:浏览和服务器
C/S:客户端和服务器
服务器是一种被动的操作,用来处理用户的一些请求和给用户一些响应信息;
IIS
Tomcat
下载tomcat:
文件夹作用:
启动。关闭Tomcat
访问测试: http://localhost:8080/
可能遇到的问题:
可以配置启动的端口号
<Connector port="8081" protoco1="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
可以配置主机的名称
<Host name="www.qinjiang.com" appBase="webapps"
unpackWARs="true" autoDeploy="true">
高难度面试题:
请你谈谈网站是如何进行访问的!
不会就先模仿
--webapps : Tomcat服务器的web目录
-ROOT
-kuangstudy : 网站的目录名
- WEB-INF
-classes : java程序
-lib: web应用所依赖的jar包
-web.xm1 :网站配置文件
- index.htm1 默认的首页
- static
-css
-style.css-js
-img
HTTP协议︰面试
Maven:构建工具
Servlet入门
HTTP(超文本传输协议)是一个简单的请求-响应协议,它通常运行在TCP之上。
Https:安全的
http1.0
http2.0
客户端—发请求—服务器
百度:
Request URL: https://www.baidu.com/ //请求地址
Request Method: GET //get方法/post方法
Status Code: 200 OK
Remote(远程) Address: 110.242.68.3:443 //状态码:200
Referrer Policy: no-referrer-when-downgrade
Accept:text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9 //语言
Cache-Control: max-age=0
Connection: keep-alive
1、请求行
请求行中的请求方式:GET
请求方式: Get,Post,HEAD,DELETE,PUT,TRACT…
2、消息头
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式GBK UTF-8 GB2312 IS08859-1
Accept-Language:告诉浏览器,它的语言环境
cache-contro1:缓存控制
connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../ .
服务器—响应-----客户端
百度响应:
Cache-Control: private //缓存控制
Connection: keep-alive //连接
Content-Encoding: gzip //编码
Content-Type: text/html //类型
1、响应体
Accept:告诉浏览器,它所支持的数据类型
Accept-Encoding:支持哪种编码格式GBK UTF-8 GB2312 IS08859-1
Accept-Language:告诉浏览器,它的语言环境
cache-contro1:缓存控制
connection:告诉浏览器,请求完成是断开还是保持连接
HOST:主机..../ .
Refresh:告诉客户端,多久刷新一次;
Location:让网页重新定位;
2、响应状态码
200:请求响应成功 200
3xx:请求重定向
4xx:找不到资源 404
5xx:服务器代码错误 500 502:网关错误
常见面试题:
当你的浏览器中地址栏输入地址并回车的一瞬间到页面能够展示回来,经历了什么?
我为什么要学习这个技术?
我们目前用来就是方便导入jar包的!
Maven的核心思想:约定大于配置
Maven会规定好你该如何去编写我们的Java代码,必须要按照这个规范来;
官网:https://maven.apache.org
下载完成后,解压即可;
小狂神友情建议:电脑上的所有环境都放在一个文件夹下,方便管理;
在我们的系统环境变量中
配置如下配置:
测试Maven是否安装成功,保证必须配置完毕!
镜像:mirrors
国内建议使用阿里云的镜像
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
在本地的仓库,远程仓库;
建立一个本地仓库:
<localRepository>D:\Environment\apache-maven-3.6.2\maven-repo</localRepository>
1.启动IDEA
2.创建一个MavenWeb项目
3.等待项目初始化完毕
4.观察maven仓库中多了什么东西?
5.IDEA中的Maven设置
IDEA项目创建成功后,看一眼Maven的配置
6.到这里,Maven在IDEA中的配置和使用就OK了!
这个只有在Web应用下才会有!
解决警告问题
必须要的配置: 为什么会有这个问题:我们访问一个网站,需要指定一个文件夹名字;
pom.xml是Maven的核心配置文件
-Maven的高级之处在于,他会帮你导入这个JAR包所依赖的其他jar
maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<!--在build中配置resources,来防止我们资源导出失败的问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
1.Maven 3.6.2
解决方法:降级为3.6.1
2.Tomcat闪退
3.IDEA中每次都要重复配置Maven
在IDEA中的全局默认配置中去配置
4.Maven项目中Tomcat无法配置
5.maven默认web项目中的web.xml版本问题
6.替换为webapp4.0版本和tomcat一致
7.Maven仓库的使用
地址:https://mvnrepository.com/
把实现了Servlet接口的Java程序叫做,Servlet
Serlvet接口Sun公司有两个默认的实现类:HttpServlet,GenericServlet
1、构建一个普通的Maven项目,删掉里面的src目录,以后我们的学习就在这个项目里面建立Moudel;这个空的工程就是Maven主工程;
2、关于Maven父子工程的理解:
父项目中会有
<modules>
<module>servlet-01</module>
</modules>
子项目会有
<parent>
<artifactId>HelloServlet</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
父项目中的java子项目可以直接使用
son extends father
3、Maven环境优化
4、编写一个Servlet程序
package com.xiaojian.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class HelloServlet extends HttpServlet { //由于get或者post只是请求实现的不同的方式,可以相互调用,业务逻辑都一样; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter();//响应流 writer.println("Hello Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
5、编写Servlet的映射
为什么需要映射:我们写的是JAVA程序,但是要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要再web服务中注册我们写的Servlet,还需给他一个浏览器能够访问的路径;
<!--注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.xiaojian.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6、配置Tomcat
注意:配置项目发布的路径就可以了
7、启动测试
Servlet是由Web服务器调用,web服务器在收到浏览器请求之后,会:
1、一个Servlet可以指定一个映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
2、一个Servlet可以指定多个映射路径
<!--servlet的请求路径--> <!--localhost:8080/s1/hello--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello4</url-pattern> </servlet-mapping>
3、一个Servlet可以指定通用映射路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
4、默认请求路径
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
5、指定一些后缀或者前缀等等…
<! --可以自定义后缀实现请求映射
注意点,*前面不能加项目映射的路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.qinjiang</url-pattern>
</servlet-mapping>
6、优先级问题
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
<servlet>
<servlet-name>error</servlet-name>
<servlet-class>com.xiaojian.servlet.ErrorServlet</servlet-class>
</servlet>
<!--servlet的请求路径-->
<!--localhost:8080/s1/hello-->
<servlet-mapping>
<servlet-name>error</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
web容器在启动的时候,它会为每个web程序都创建一个对应的ServletContext对象,它代表了当前的web应用;
package com.xiaojian.servlet; 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; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // this.getInitParameter() 初始化参数 // this.getServletConfig() Servlet配置 // this.getServletContext() Servlet上下文 ServletContext servletContext = this.getServletContext(); String username="java"; servletContext.setAttribute("username",username);//将一个数据保存在了ServletContext中,名字为: username 。值username } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
package com.xiaojian.servlet; 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; public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String username =(String) servletContext.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().println("名字"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.xiaojian.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>getc</servlet-name> <servlet-class>com.xiaojian.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping>
测试访问结果;
<servlet>
<servlet-name>gp</servlet-name>
<servlet-class>com.xiaojian.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gp</servlet-name>
<url-pattern>/gp</url-pattern>
</servlet-mapping>
package com.xiaojian.servlet; 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; public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); String url = servletContext.getInitParameter("url"); resp.getWriter().println(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<servlet>
<servlet-name>sd4</servlet-name>
<servlet-class>com.xiaojian.servlet.ServletDemo04</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd4</servlet-name>
<url-pattern>/sd4</url-pattern>
</servlet-mapping>
package com.xiaojian.servlet; 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; public class ServletDemo04 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = this.getServletContext(); System.out.println("进入了ServletDemo04"); // RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/gp");//转发的请求路径 // requestDispatcher.forward(req,resp);//调用forward实现请求转发 servletContext.getRequestDispatcher("/gp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Properties
发现:都被打包到了同一个路径下: classes,我们俗称这个路径为classpath:
思路:需要一个文件流(db.properties);
username=root
password=123456
<servlet>
<servlet-name>sd5</servlet-name>
<servlet-class>com.xiaojian.servlet.ServletDemo05</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sd5</servlet-name>
<url-pattern>/sd5</url-pattern>
</servlet-mapping>
package com.xiaojian.servlet; 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.io.InputStream; import java.util.Properties; public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties properties = new Properties(); properties.load(resourceAsStream); String username = properties.getProperty("username"); String password = properties.getProperty("password"); resp.getWriter().println(username+":"+password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
访问测试即可ok
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse;I
负责向浏览器发送数据的方法
ServletOutputStream getoutputstream() throws IOException;
PrintWriter getWriter() throws IOException;
负责向浏览器发送响应头的方法
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1,long var2);
void addDateHeader(String var1,long var2);
void setHeader(String var1,String var2);
void addHeader(String var1,String var2);
void setIntHeader(String var1,int var2);
void addIntHeader(String var1,int var2);
响应的状态码
public static final int SC_CONTINUE = 100; /** * Status code (101) indicating the server is switching protocols * according to Upgrade header. */ public static final int SC_SWITCHING_PROTOCOLS = 101; /** * Status code (200) indicating the request succeeded normally. */ public static final int SC_OK = 200; /** * Status code (201) indicating the request succeeded and created * a new resource on the server. */ public static final int SC_CREATED = 201; /** * Status code (202) indicating that a request was accepted for * processing, but was not completed. */ public static final int SC_ACCEPTED = 202; /** * Status code (203) indicating that the meta information presented * by the client did not originate from the server. */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** * Status code (204) indicating that the request succeeded but that * there was no new information to return. */ public static final int SC_NO_CONTENT = 204; /** * Status code (205) indicating that the agent <em>SHOULD</em> reset * the document view which caused the request to be sent. */ public static final int SC_RESET_CONTENT = 205; /** * Status code (206) indicating that the server has fulfilled * the partial GET request for the resource. */ public static final int SC_PARTIAL_CONTENT = 206; /** * Status code (300) indicating that the requested resource * corresponds to any one of a set of representations, each with * its own specific location. */ public static final int SC_MULTIPLE_CHOICES = 300; /** * Status code (301) indicating that the resource has permanently * moved to a new location, and that future references should use a * new URI with their requests. */ public static final int SC_MOVED_PERMANENTLY = 301; /** * Status code (302) indicating that the resource has temporarily * moved to another location, but that future references should * still use the original URI to access the resource. * * This definition is being retained for backwards compatibility. * SC_FOUND is now the preferred definition. */ public static final int SC_MOVED_TEMPORARILY = 302; /** * Status code (302) indicating that the resource reside * temporarily under a different URI. Since the redirection might * be altered on occasion, the client should continue to use the * Request-URI for future requests.(HTTP/1.1) To represent the * status code (302), it is recommended to use this variable. */ public static final int SC_FOUND = 302; /** * Status code (303) indicating that the response to the request * can be found under a different URI. */ public static final int SC_SEE_OTHER = 303; /** * Status code (304) indicating that a conditional GET operation * found that the resource was available and not modified. */ public static final int SC_NOT_MODIFIED = 304; /** * Status code (305) indicating that the requested resource * <em>MUST</em> be accessed through the proxy given by the * <code><em>Location</em></code> field. */ public static final int SC_USE_PROXY = 305; /** * Status code (307) indicating that the requested resource * resides temporarily under a different URI. The temporary URI * <em>SHOULD</em> be given by the <code><em>Location</em></code> * field in the response. */ public static final int SC_TEMPORARY_REDIRECT = 307; /** * Status code (400) indicating the request sent by the client was * syntactically incorrect. */ public static final int SC_BAD_REQUEST = 400; /** * Status code (401) indicating that the request requires HTTP * authentication. */ public static final int SC_UNAUTHORIZED = 401; /** * Status code (402) reserved for future use. */ public static final int SC_PAYMENT_REQUIRED = 402; /** * Status code (403) indicating the server understood the request * but refused to fulfill it. */ public static final int SC_FORBIDDEN = 403; /** * Status code (404) indicating that the requested resource is not * available. */ public static final int SC_NOT_FOUND = 404; /** * Status code (405) indicating that the method specified in the * <code><em>Request-Line</em></code> is not allowed for the resource * identified by the <code><em>Request-URI</em></code>. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** * Status code (406) indicating that the resource identified by the * request is only capable of generating response entities which have * content characteristics not acceptable according to the accept * headers sent in the request. */ public static final int SC_NOT_ACCEPTABLE = 406; /** * Status code (407) indicating that the client <em>MUST</em> first * authenticate itself with the proxy. */ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** * Status code (408) indicating that the client did not produce a * request within the time that the server was prepared to wait. */ public static final int SC_REQUEST_TIMEOUT = 408; /** * Status code (409) indicating that the request could not be * completed due to a conflict with the current state of the * resource. */ public static final int SC_CONFLICT = 409; /** * Status code (410) indicating that the resource is no longer * available at the server and no forwarding address is known. * This condition <em>SHOULD</em> be considered permanent. */ public static final int SC_GONE = 410; /** * Status code (411) indicating that the request cannot be handled * without a defined <code><em>Content-Length</em></code>. */ public static final int SC_LENGTH_REQUIRED = 411; /** * Status code (412) indicating that the precondition given in one * or more of the request-header fields evaluated to false when it * was tested on the server. */ public static final int SC_PRECONDITION_FAILED = 412; /** * Status code (413) indicating that the server is refusing to process * the request because the request entity is larger than the server is * willing or able to process. */ public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; /** * Status code (414) indicating that the server is refusing to service * the request because the <code><em>Request-URI</em></code> is longer * than the server is willing to interpret. */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** * Status code (415) indicating that the server is refusing to service * the request because the entity of the request is in a format not * supported by the requested resource for the requested method. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** * Status code (416) indicating that the server cannot serve the * requested byte range. */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** * Status code (417) indicating that the server could not meet the * expectation given in the Expect request header. */ public static final int SC_EXPECTATION_FAILED = 417; /** * Status code (500) indicating an error inside the HTTP server * which prevented it from fulfilling the request. */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** * Status code (501) indicating the HTTP server does not support * the functionality needed to fulfill the request. */ public static final int SC_NOT_IMPLEMENTED = 501; /** * Status code (502) indicating that the HTTP server received an * invalid response from a server it consulted when acting as a * proxy or gateway. */ public static final int SC_BAD_GATEWAY = 502; /** * Status code (503) indicating that the HTTP server is * temporarily overloaded, and unable to handle the request. */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** * Status code (504) indicating that the server did not receive * a timely response from the upstream server while acting as * a gateway or proxy. */ public static final int SC_GATEWAY_TIMEOUT = 504; /** * Status code (505) indicating that the server does not support * or refuses to support the HTTP protocol version that was used * in the request message. */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
1.向浏览器输出消息(一直在讲,就不说了)
2.下载文件
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // - 要获取下载文件的路径 String realPath = "C:\\Users\\ASUS\\Desktop\\Java\\javaweb\\HelloServlet\\response\\src\\main\\resources\\1.jpg";//获取绝对地址 System.out.println("下载文件的路径"+realPath); // - 下载的文件名是啥? String filename = realPath.substring(realPath.lastIndexOf("\\") + 1); // - 设置想办法让浏览器能够支持(Content-Disposition)下载我们需要的东西,中文文件名URLEncoder.encode编码,否则有可能乱码 resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8")); // - 获取下载文件的输入流创建缓冲区 FileInputStream fileInputStream = new FileInputStream(realPath); int len=0; byte[] buffer = new byte[1024]; // - 获取OutputStream对象 ServletOutputStream outputStream = resp.getOutputStream(); // - 将FileOutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端! while ((len=fileInputStream.read(buffer))>0){ outputStream.write(buffer,0,len); } outputStream.close(); fileInputStream.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
验证怎么来的?
package com.jian.servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //如何让浏览器5秒自动刷新一次; resp.setHeader("refresh","3"); //在内存中创建一个图片 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //得到图片 Graphics2D graphics = (Graphics2D) image.getGraphics();//笔 //设置图片的背景颜色 graphics.setColor(Color.GRAY); graphics.fillRect(0,0,80,20); //给图片写数据 graphics.setColor(Color.CYAN); graphics.setFont(new Font(null,Font.BOLD,20)); graphics.drawString(makeNum(),0,20); resp.setContentType("image/jpg"); //网站存在缓存,不让浏览器缓存 resp.setDateHeader("Expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //把图片写给浏览器 ImageIO.write(image,"jpg",resp.getOutputStream()); } //生成随机数 private String makeNum(){ Random random = new Random(); String s = random.nextInt(9999999) + ""; StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < 7-s.length(); i++) { stringBuffer.append("0"); } s=stringBuffer.toString()+s; return s; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
B一个web资源收到客户端A请求后,B他会通知A客户端去访问另外一个web资源C,这个过程叫重定向
常见场景:
void sendRedirect(string var1) throws IOException;
测试:
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*resp.setHeader("Location","/response_war/img"); resp.setStatus(302);*/ resp.sendRedirect("/response_war/img");//重定向 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
面试题:请你聊聊重定向和转发的区别?
相同点
不同点
package com.jian.servlet; 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.util.Arrays; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); String username = req.getParameter("username");//获取单个参数 String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("========================="); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobbys)); System.out.println("========================="); //通过请求转发 //这里的 / 代表当前的web应用 req.getRequestDispatcher("/success.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
有状态会话: 一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过
你能怎么证明你是学生?
你 学校
一个网站,怎么证明你来过?
客户端 服务端
服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了;cookie
服务器登记你来过了,下次你来的时候我来匹配你;session
cookie
session
常见常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
1.从请求中拿到cookie信息
⒉.服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//获得cookie
Cookie.getName();//获得cookie中的key
Cookie.getValue();//获得cookie中的v1aue
new Cookie("lastLoginTime".System.currentTimeMi11is()+"");//新建一个cookie
Cookie.setMaxAge(24*60*60);//设置cookie的有效期
resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下appdata;
一个网站cookie是否存在上限!聊聊细节问题
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.crypto.Data; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; //保存用户上一次访问的时间 public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //服务器,告诉你,你来的时间,把这个时间封装成为一个信件,你下带来,我就知道你来了 //解决中文乱码 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); PrintWriter out = resp.getWriter(); //Cookie,服务器端从客户端获取 Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个 //判断Cookie是否存在 if (cookies!=null){ //如果存在怎么办 out.write("您上一次访问的时间是"); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; //获取cookie的名字 if (cookie.getName().equals("lastLoginTime")){ //获取cookie中的值 long lastLoginTime = Long.parseLong(cookie.getValue()); Date date = new Date(lastLoginTime); out.write(date.toLocaleString()); } } }else { out.write("这是您第一次访问本站"); } //服务器给客户端响应一个cookie Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+""); //cookie有效期为一天 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
删除Cookie:
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //保存用户上一次访问的时间 public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建一个cookie,名字必须要和要删除的名字一致 Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+""); //将cookie有效期设置为0.立马过期 cookie.setMaxAge(0); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
编码解码:
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; //中文数据传递 public class CookieDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //服务器,告诉你,你来的时间,把这个时间封装成为一个信件,你下带来,我就知道你来了 //解决中文乱码 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); PrintWriter out = resp.getWriter(); //Cookie,服务器端从客户端获取 Cookie[] cookies = req.getCookies();//这里返回数组,说明Cookie可能存在多个 //判断Cookie是否存在 if (cookies!=null){ //如果存在怎么办 out.write("您上一次访问的时间是"); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; //获取cookie的名字 if (cookie.getName().equals("name")){ //获取cookie中的值 System.out.println(cookie.getValue()); //out.write(cookie.getValue()); //解码 out.write(URLDecoder.decode(cookie.getValue(),"utf8")); } } }else { out.write("这是您第一次访问本站"); } //服务器给客户端响应一个cookie //Cookie cookie = new Cookie("name","编程"); //编码 Cookie cookie = new Cookie("name", URLEncoder.encode("编程","utf8")); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
什么是Session :
Session和cookie的区别:
使用场景:
package com.jian.servlet; import com.jian.pojo.Person; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决乱码问题 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); resp.setContentType("text/html;charset=utf8"); //得到session HttpSession session = req.getSession(); //给session中存东西 // session.setAttribute("name","编程"); session.setAttribute("name",new Person("java",1)); //获取session的id String id = session.getId(); //判断session是不是新创建的 if (session.isNew()){ resp.getWriter().write("session创建成功,ID:"+id); }else { resp.getWriter().write("session已经在服务器中存在了,ID:"+id); } //session创建的时候默认做了什么事情 // Cookie jsessionid = new Cookie("JSESSIONID", id); // resp.addCookie(jsessionid); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决乱码问题 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); resp.setContentType("text/html;charset=utf8"); //得到session HttpSession session = req.getSession(); //获取session中存的东西 String name = (String) session.getAttribute("name"); // System.out.println(name); System.out.println(name.toString()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决乱码问题 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); resp.setContentType("text/html;charset=utf8"); //得到session HttpSession session = req.getSession(); session.removeAttribute("name"); //手动注销session session.invalidate(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
会话自动过期:web.xml配置
可以设置session默认的失效时问
<!--设置session默认的失效时问-->
<session-config>
<!--15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:
思路:JSP到底怎么执行的!
我电脑的地址:
c:\users \Administrator\.Inte11iJIdea2018.1\system\tomcat\Unnamed_javaweb-session-cookie\work \catalina\ 7ocalhost\RoOT\org\apache\jsp
发现页面转变成了Java程序!
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
JSP最终也会被转换成为一个Java类!
JSP本质上就是一个Servlet
//初始化
public void _jspinit( {
}
//销毁
public void _jspDestroy() i}
//JSPservice
public void _jspService(.HttpservletRequest request,HttpServletResponse response)
1.判断请求
2.内置一些对象
final javax.servlet.jsp.Pagecontext pageContext;//页面上下文
javax.servlet.http. Httpsession session = null;
final javax.servlet.Serv1etContext application;
final javax.servlet.Servletconfig config;
javax.servlet.jsp.Jspwriter out = nu11;
final java.lang. object page = this;
javax.servlet.jsp.Jspwriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
3.输出页面前增加的代码
response.setcontentType ("text/html");//设置响应的页面类型
pagecontext = _jspxFactory.getPageContext(this,request,response,
nu11,true,8192,true);
_jspx_page_context = pageContext;
application = pagecontext.getservletContext();
config = pageContext.getservletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
4.以上的这些个对象我们可以在JSP页面中直接使用!
在JSP页面中;
只要是JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为
out.write ("<html>\r\n");
这样的格式,输出到前端!
任何语言都有自己的语法,JAVA中有,。JSP作为java技术的一种应用,它拥有一些自己扩充的语法(了解,知道即可! ) ,Java所有语法都支持!
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%--jsp表达式
作用:用来将程序的输出,输出到客户端
<%= 变量或者表达式%>
--%>
时间: <%= new Date()%>
</body>
</html>
<%--jsp脚本片段--%>
<%
int sum=0;
for (int i = 1; i < 100; i++) {
sum+=i;
out.print("<h1>"+sum+"</h1>");
}
<% int x=20; out.println(x); %> <p>这是一个jsp文档</p> <% int y=20; out.println(y); %> <hr> <%--在代码中嵌入HTML元素--%> <% for (int i = 0; i < 5; i++) { %> <h1>Hello Word <%= i%></h1> <% } %>
<%!
static {
System.out.println("Loading Servlet");
}
private int globalVar=0;
public void java(){
System.out.println("进入了java方法");
}
%>
JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到_jspService方法中!
在JSP,嵌入Java代码即可!
<%%>
<%=%>
<%!%>
<%--注释--%>
JSP的注释,不会在客户端显示,HTML就会!
web.xml可以配置错误页面
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
报错页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <%--定制错误页面--%> <%--<%@ page errorPage="error/500.jsp" %>--%> <%--显示的声明这是一个错误页面--%> <%@ page isErrorPage="true" %> <%@ page pageEncoding="utf-8" %> <head> <title>Title</title> </head> <body> <% int x=1/0; %> </body> </html>
500页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--定制错误页面--%>
<head>
<title>Title</title>
</head>
<body>
<img src="./image/500.png">
</body>
</html>
404页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--定制错误页面--%>`在这里插入代码片`
<head>
<title>Title</title>
</head>
<body>
<img src="./image/404.jpg">
</body>
</html>
页面合并,页面拼接
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--@include会将两个页面合二为一--%> <%@ include file="common/header.jsp"%> <h1>我是主体</h1> <%@ include file="common/footer.jsp"%> <hr> <%--jsp标签--%> <%--jsp:incLude:拼接页面,本质还是三个--%> <jsp:include page="common/header.jsp"/> <h1>我是主体</h1> <jsp:include page="common/footer.jsp"/> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <%--内置对象--%> <% pageContext.setAttribute("name01","java01");/*保存的数据只在一个页面中有效*/ request.setAttribute("name02","java02");//保存的数据只在一次请求中有效,请求转发会携带这个数据 session.setAttribute("name03","java03");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器 application.setAttribute("name04","java04");//保存的数据只在服务器中有效,从打开服务器到关闭服务器 %> <%-- 脚本片段中的代码,会被原封不动生成到.JSP.java 要求:这里面的代码:必须保证Java语法的正确性 --%> <% /*通过pageContext取出我们保存的值*/ /*从底层到高层(作用域);page- >request-->session-->application */ /*scope:作用域 abstract public void setAttribute(String name, Object value, int scope); */ String name01=(String)pageContext.findAttribute("name01"); String name02=(String)pageContext.findAttribute("name02"); String name03=(String)pageContext.findAttribute("name03"); String name04=(String)pageContext.findAttribute("name04"); String name05=(String)pageContext.findAttribute("name05");//不存在 %> <%--使用EL表达式输出 ${}--%> <h1>取出的值为:</h1> <h2>${name01}</h2> <h2>${name02}</h2> <h2>${name03}</h2> <h2>${name04}</h2> <h2>${name05}</h2> <h2><%=name05%></h2><%--输出为:null--%> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--转发--%>
<%
pageContext.forward("/index.jsp");
//request.getRequestDispatcher("/index.jsp").forward(request,response);
%>
</body>
</html>
request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的
session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:
聊天数
据;
EL表达式: ${}
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <!--jsp依赖--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api --> <!--jstl表达式依赖--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <!--standard标签库--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
JSP标签
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>jsptag.jsp</h1> <%--拼接页面:<jsp:include page="jsptag.jsp"/>--%> <%-- http://localhost:8080/jsptag.jsp?name=java&age=12 --%> <jsp:forward page="jsptag2.jsp"> <jsp:param name="name" value="java"/> <jsp:param name="age" value="12"/> </jsp:forward> </body> </html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--拼接页面:<jsp:include page="jsptag.jsp"/>--%>
<h1>jsptag2.jsp</h1>
<%--取出参数--%>
名字:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
</body>
</html>
JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和ava代码—样!
核心标签
<%–引入了STL核心标签库,我们才能使用JSTL标签–%>
<%@taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
JSTL标签库使用步骤
c:if
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--引入了STL核心标签库,我们才能使用JSTL标签--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <h4>if测试</h4> <hr> <form action="coreif.jsp" method="get"> <%-- EL表达式获取表单中的数据 ${param.参数名} --%> <input type="text" name="username" value="${param.username}"> <input type="submit" value="登录"> </form> <%--判断如果提交的用户名是管理员,则登录成功--%> <c:if test="${param.username=='admin'}" var="isAdmin" > <c:out value="管理员欢迎你"/> </c:if> <%--自闭合标签--%> <c:out value="${isAdmin}"/> </body> </html>
c:choose
c:when
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--引入了STL核心标签库,我们才能使用JSTL标签--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <c:set var="score" value="85"> <c:choose> <c:when test="${score>=90}"> 你的成绩为优秀 </c:when> <c:when test="${score>=80}"> 你的成绩为良好 </c:when> <c:when test="${score>=70}"> 你的成绩为一般 </c:when> <c:when test="${score>=60}"> 你的成绩为及格 </c:when> <c:when test="${score<=60}"> 你的成绩为不及格 </c:when> </c:choose> </c:set> </body> </html>
c:forEach
<%@ page import="java.util.ArrayList" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--引入了STL核心标签库,我们才能使用JSTL标签--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <% ArrayList<String> people = new ArrayList<>(); people.add(0,"张三"); people.add(1,"李四"); people.add(2,"王五"); people.add(3,"赵六"); people.add(4,"田七"); request.setAttribute("list",people); %> <%-- var , 每一次遍历出来的变量 items, 要遍历的对象 begin, 哪里开始 end, 到哪里 step, 步长 --%> <c:forEach var="people" items="${list}"> <c:out value="${people}"/> <br> </c:forEach> <hr> <c:forEach var="people" items="${list}" begin="1" end="3" step="2"> <c:out value="${people}"/> <br> </c:forEach> </body> </html>
格式化标签
SQL标签
XML标签
实体类
JavaBean有特定的写法:
—般用来和数据库的字段做映射 ORM;
ORM:对象关系映射
people表
id | name | age | address |
---|---|---|---|
1 | 张三 | 3 | 北京 |
2 | 李四 | 4 | 上海 |
3 | 王五 | 5 | 深圳 |
class Peop1e{
private int id;
private String name;
private int age;
private String address;
}
class A{
new People(1,"张三",3,"北京");
new People(2,"李四",4,"上海");
new People(3,"王五",5,"深圳");
}
什么是MVC: Model view Controller模型、视图、控制器
用户直接访问控制层,控制层就可以直接操作数据库;
servlet-->CRUD-->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
|
JDBC
|
Mysql oracle SqlServer ..
Model
View
Controller (Servlet)
接收用户的请求: (req:请求参数、Session信息…)
交给业务层处理对应的代码
控制视图的跳转
登录--->接收用户的登录请求--->处理用户的请求(获取用户登录
的参数,username,password)---->交给业务层处理登录业务
(判断用户名密码是否正确:事务) --->Dao层查询用户名和密码是否
正确-->数据库
Filter:过滤器,用来过滤网站的数据;
Filter开发步骤:
1.导包
2.编写过滤器
package com.jian.filter; import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { //初始化:web服务器启动,就以及初始化了,随时等待过滤对象出现! @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); System.out.println("CharacterEncodingFilter初始化"); } //chain:链 /* * 1.过滤中的所有代码,在过滤特定请求的时候都会执行 * 2.必须要让过滤器继续通行 * chain.doFilter ( request, response); * */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); System.out.println("CharacterEncodingFilter执行前"); chain.doFilter(request,response);//让我们的请求继续走,如果不写,程序到这里就被拦截停止! System.out.println("CharacterEncodingFilter执行后"); } //销毁:web服务器关闭的时候,过滤会销毁 @Override public void destroy() { Filter.super.destroy(); System.out.println("CharacterEncodingFilter销毁"); } }
过滤的页面
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ShowServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //resp.setCharacterEncoding("utf8"); resp.getWriter().write("你好啊,世界"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
3.在web.xml中配置Filter和servlet
<servlet> <servlet-name>ShowServlet</servlet-name> <servlet-class>com.jian.servlet.ShowServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/servlet/show</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/show</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.jian.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!--只要是/servLet的任何请求,会经过这个过滤器--> <url-pattern>/servlet/*</url-pattern> <!--<url-pattern>/*</url-pattern>--> </filter-mapping>
实现一个监听器的接口;(有N种)
1.编写一个监听器实
现监听器的接口
package com.jian.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; //统计网站在线人数: 统计session public class OnlineCountListener implements HttpSessionListener{ //创建session监听 //一旦创建Session就会触发一次这个事件! @Override public void sessionCreated(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount=new Integer(1); }else { int i = onlineCount.intValue(); onlineCount=new Integer(i+1); } servletContext.setAttribute("OnlineCount",onlineCount); } //销毁session监听 //一旦销毁Session就会触发一次这个事件! @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext servletContext = se.getSession().getServletContext(); Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount=new Integer(0); }else { int i = onlineCount.intValue(); onlineCount=new Integer(i-1); } servletContext.setAttribute("OnlineCount",onlineCount); } /* * session销毁: 1.手动销毁getSession( ).invalidate(); * 2.自动销毁 */ }
2.web.xml中注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.jian.listener.OnlineCountListener</listener-class>
</listener>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
监听器:GUI编程中经常使用;
package com.jian.listener; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class TestPanel { public static void main(String[] args) { Frame frame = new Frame("监听测试"); Panel panel = new Panel(); frame.setLayout(null); frame.setBounds(300,300,500,500); frame.setBackground(new Color(40, 101, 52)); panel.setBounds(50,50,300,300); panel.setBackground(new Color(180, 46, 177)); frame.add(panel); frame.setVisible(true); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); System.exit(0); } }); } }
用户登录之后才能进入主页!用户注销后就不能进入主页了!
1.用户登录之后,向Sesison中放入用户的数据
2.进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="/servlet/login" method="post">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取前端请求的参数 String username = req.getParameter("username"); if (username.equals("admin")){//登录成功 req.getSession().setAttribute("USER_SESSION",req.getSession().getId()); resp.sendRedirect("/sys/success.jsp"); }else {//登录失败 resp.sendRedirect("/error.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主页</h1>
<a href="/servlet/logout">注销</a>
</body>
</html>
package com.jian.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object user_session = req.getSession().getAttribute("USER_SESSION"); if (user_session!=null){ req.getSession().removeAttribute("USER_SESSION"); resp.sendRedirect("/login.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>错误</h1>
<h3>没有权限,用户名错误</h3>
<a href="/login.jsp">返回登录页面</a>
</body>
</html>
package com.jian.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SysFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest request1= (HttpServletRequest) request; HttpServletResponse response1 = (HttpServletResponse) response; Object user_session = request1.getSession().getAttribute("USER_SESSION"); if (user_session==null){ response1.sendRedirect("/error.jsp"); } chain.doFilter(request,response); } @Override public void destroy() { Filter.super.destroy(); } }
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.jian.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.jian.servlet.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/servlet/logout</url-pattern> </servlet-mapping> <filter> <filter-name>SysFilter</filter-name> <filter-class>com.jian.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>/sys/*</url-pattern> </filter-mapping>
什么是JDBC : Java连接数据库!
需要jar包的支持:
实验环境搭建
1、创建users表
CREATE TABLE users( id INT PRIMARY KEY, `name` VARCHAR(40), `password` VARCHAR(40), email VARCHAR(60), birthday DATE ) INSERT INTO users( id,`name`,`password`,email,birthday) VALUES (1,'张三','123456','zs@qq.com','2000-01-01'); INSERT INTO users( id,`name`,`password`,email,birthday) VALUES (2,'李四','123456','ls@qq.com','2000-01-01'); INSERT INTO users( id,`name`,`password`,email,birthday) VALUES (3,'张王五','123456','wu@qq.com','2000-01-01'); SELECT * FROM users;
导入数据库依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
IDEA中连接数据库:
JDBC固定步骤:
package com.jian.test; import java.sql.*; public class TestJdbc { public static void main(String[] args) throws ClassNotFoundException, SQLException { //配置信息 //useUnicode=true&characterEncoding=utf-8解决中文乱码问题 String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true"; String username="root"; String password="123456"; //1、加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2、连接数据库,代表数据库 Connection connection = DriverManager.getConnection(url, username, password); //3、向数据库发送SQL的对象Statement : CRUD prepareStatement预编译对象,安全 Statement statement = connection.createStatement(); //4、编写SQL String sql="select * from users"; //5、执行查询SQL 返回一个ResultSet结果集 ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ System.out.println("id: "+resultSet.getInt("id")); System.out.println("name: "+resultSet.getString("name")); System.out.println("password: "+resultSet.getString("password")); System.out.println("email: "+resultSet.getString("email")); System.out.println("birthday: "+resultSet.getDate("birthday")); System.out.println("========================="); } //6、关闭连接,释放资源 先开后关 resultSet.close(); statement.close(); connection.close(); } }
预编译SQL
package com.jian.test; import java.sql.*; public class TestJdbc2 { public static void main(String[] args) throws ClassNotFoundException, SQLException { //配置信息 //useUnicode=true&characterEncoding=utf-8解决中文乱码问题 String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true"; String username="root"; String password="123456"; //1、加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2、连接数据库,代表数据库 Connection connection = DriverManager.getConnection(url, username, password); //3、编写sql String sql="insert into users (id, name, password, email, birthday) VALUE (?,?,?,?,?)"; //4、预编译 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,4); preparedStatement.setString(2,"赵六"); preparedStatement.setString(3,"123456"); preparedStatement.setString(4,"zl@qq.com"); preparedStatement.setDate(5,new Date(new java.util.Date().getTime())); //5、执行sql int i = preparedStatement.executeUpdate(); if (i>0){ System.out.println("插入成功"); } //6、关闭连接,释放资源 先开后关 preparedStatement.close(); connection.close(); } }
事务
要么都成功,要么都失败!
ACID原则:保证数据的安全。
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(900) --100--> B(1100)
导入Junit单元测试依赖
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
简单使用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!
package com.jian.test;
import org.junit.Test;
public class TestJdbc3 {
@Test
public void test(){
System.out.println("hello");
}
}
失败的时候是红色:
搭建一个环境
create table account(
id int primary key auto_increment,
name varchar(40),
money float
);
insert into account (name, money) VALUE ('a',1000);
insert into account (name, money) VALUE ('b',1000);
insert into account (name, money) VALUE ('c',1000);
package com.jian.test; import org.junit.Test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TestJdbc3 { @Test public void test() throws SQLException { //配置信息 //useUnicode=true&characterEncoding=utf-8解决中文乱码问题 String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=true"; String username="root"; String password="123456"; Connection connection =null; try { //1、加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2、连接数据库,代表数据库 connection = DriverManager.getConnection(url, username, password); //3、通知数据库开启事务,false 开启 connection.setAutoCommit(false); String sql1="update account set money=money-100 where name='a'"; connection.prepareStatement(sql1).executeUpdate(); //制造错误 //int i=1/0; String sql2="update account set money=money+100 where name='b'"; connection.prepareStatement(sql2).executeUpdate(); connection.commit();//以上两条SQL都执行成功了,就提交事务! System.out.println("success"); } catch (Exception throwables) { //如果出现异常,就通知数据库回滚事务 connection.rollback(); throwables.printStackTrace(); }finally { connection.close(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。