Servlet是sun公司开发动态web的一门技术
Sun在这些API中提供一个接口叫Servlet ,如果想开发一个Servlet程序,只需要完成两个步骤
-
-
把开发好的java类部署到web服务器中
把实现了servlet接口的java程序叫做servlet
2、关于Maven父子工程的理解
父项目中会有
<modules> <module>servlet-01</module> </modules>
子项目中会有
<parent> <artifactId>javaweb-servlet</artifactId> <groupId>com.cheng</groupId> <version>1.0-SNAPSHOT</version> </parent>
3、Maven环境优化
1、修改web.xml为最新的 (内容是tomcat的webapps/root/WEB-INF/web.xml)
2、将maven的结构搭建完整
4、编写一个servlet程序
1、编写一个普通类
2、实现Servlet嗟阔,这里我们直接继承HttpServlet
public class HelloServlet extends HttpServlet { //由于get或者post只是请求实现的不同方式,可以相互调用,业务逻辑都一样 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter();//响应流 writer.print("hello,servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
5、编写Servlet的映射
<!--注册Servlet--> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.cheng.servlet.HelloServlet</servlet-class> </servlet> <!--Servlet的请求路径--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
7、启动测试
<!--在build中配置resoureces,来防止我们资源导出失效的问题--> <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>
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
2、一个servlet可以指定多个映射路径
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <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>
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
<!--可以自定义后缀实现请求映射 注意:*前面不能加映射的路径 比如 hello/sdsds.miaomiao--> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.miaomiao</url-pattern> </servlet-mapping>
指定了固有的映射路径优先级最高,如果找不到就会走默认的处理请求
<!--404--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.cheng.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
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.PrintWriter; public class ErrorServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); PrintWriter writer = resp.getWriter(); writer.print("<h1>404</h1>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
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 context = this.getServletContext(); String username="喵喵";//数据 context.setAttribute("username",username);//将一个数据保存在ServletContext中,名字为:username,,值为username System.out.println("Hello"); } }
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username = (String) context.getAttribute("username"); resp.setContentType("text/html"); resp.setCharacterEncoding("utf-8"); resp.getWriter().print("名字"+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.cheng.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.cheng.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>getc</servlet-name> <url-pattern>/getc</url-pattern> </servlet-mapping>
<context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybatis</param-value> </context-param>
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().print(url); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); System.out.println("进入了ServletDemo04"); //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//转发的请求路径 //requestDispatcher.forward(req,resp);//调用forward实现请求转发 context.getRequestDispatcher("/gp").forward(req,resp); }
propertie
-
-
在resources目录下新建properties
发现都被打包到了同一个路径下:classes ,俗称这个路径为类路径
思路:需要一个文件流
username=root
password=1235465
public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is= this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is); String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user+":"+pwd); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
访问测试即可
web服务器接收到客户端的http请求,针对这个请求,分别创建一个代表请求的HttpServletRequest对象,代表响应的一个HttpServletResponse
如果要获取客户端请求过来的参数,找HttpServletRequest
如果要给客户端响应一些信息,找HttpServletResponse
向浏览器发送数据的方法
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);
响应的状态码
int SC_CONTINUE = 100; int SC_SWITCHING_PROTOCOLS = 101; int SC_OK = 200; int SC_CREATED = 201; int SC_ACCEPTED = 202; int SC_NON_AUTHORITATIVE_INFORMATION = 203; int SC_NO_CONTENT = 204; int SC_RESET_CONTENT = 205; int SC_PARTIAL_CONTENT = 206; int SC_MULTIPLE_CHOICES = 300; int SC_MOVED_PERMANENTLY = 301; int SC_MOVED_TEMPORARILY = 302; int SC_FOUND = 302; int SC_SEE_OTHER = 303; int SC_NOT_MODIFIED = 304; int SC_USE_PROXY = 305; int SC_TEMPORARY_REDIRECT = 307; int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; int SC_NOT_FOUND = 404; int SC_METHOD_NOT_ALLOWED = 405; int SC_NOT_ACCEPTABLE = 406; int SC_PROXY_AUTHENTICATION_REQUIRED = 407; int SC_REQUEST_TIMEOUT = 408; int SC_CONFLICT = 409; int SC_GONE = 410; int SC_LENGTH_REQUIRED = 411; int SC_PRECONDITION_FAILED = 412; int SC_REQUEST_ENTITY_TOO_LARGE = 413; int SC_REQUEST_URI_TOO_LONG = 414; int SC_UNSUPPORTED_MEDIA_TYPE = 415; int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; int SC_EXPECTATION_FAILED = 417; int SC_INTERNAL_SERVER_ERROR = 500; int SC_NOT_IMPLEMENTED = 501; int SC_BAD_GATEWAY = 502; int SC_SERVICE_UNAVAILABLE = 503; int SC_GATEWAY_TIMEOUT = 504; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
1、向浏览器发送消息
2、下载文件
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 = "F:\\JavaProjects\\javaweb-servlet\\response\\src\\main\\resources\\test1.jpg"; System.out.println("下载文件的路径"+realPath); //下载的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); //设置让浏览器能够支持下载我们需要的东西(web下载文件的头消息) resp.setHeader("Content-Disposition","attachment;filename"+URLEncoder.encode(fileName,"UTF-8")); //获取下载文件的输入流 FileInputStream in = new FileInputStream(realPath); //创建缓冲区 int len=0; byte[] buffer = new byte[1024]; //获取outputStream对象 ServletOutputStream out = resp.getOutputStream(); //将FileoutputStream流写入到buffer缓冲区,使用outputstream将缓冲区中的数据输出到客户端 while((len=in.read(buffer))>0){ out.write(buffer,0,len); } //关闭流 in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
3、验证码功能
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_3BYTE_BGR); //得到图片 Graphics2D g = (Graphics2D) image.getGraphics();//笔 //设置图片的背景颜色 g.setColor(Color.white); g.fillRect(0,0,80,20); //给图片写数据 g.setColor(Color.blue); g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); //告诉浏览器这个请求用图片的方式打开 resp.setContentType("image/jpeg"); //网站存在缓存,不让浏览器缓存 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 num = random.nextInt(99999999)+""; StringBuffer sb = new StringBuffer(); for(int i=0;i<7-num.length();i++){ sb.append("0"); } num= sb.toString()+num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
一个web资源收到客户端请求后,它会通知客户端去访问另外一个web资源,这个过程叫重定向
void sendRedirect(String var1) throws IOException;
测试
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.setHeader("Location","/img"); // resp.setStatus(302); resp.sendRedirect("/img"); }
重定向和转发的区别?
-
相同点: 页面都会实现跳转
不同点:
-
请求转发的时候,url不会产生变化
-
重定向的时候,url地址栏会发生变化
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话
1、服务器给客户端一个信件,客户端下次访问服务器带上信件就可以了,cookie
2、服务器登记你来过,下次你来的时候我来匹配你,session
cookie
客户端技术(响应,请求)
1、从请求中拿到cookie信息
2、服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//获得cookie cookie.getName();//获得cookie中的key cookie.getValue();//获得cookie中的value new Cookie("lastLoginTime", System.currentTimeMillis()+"");//新建一个cookie cookie.setMaxAge(24*60*60);//设置cookie的有效期 resp.addCookie(cookie);//响应给客户端一个cookie
//保存用户上一次访问的时间 public class CookieDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); 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有效期为1天 cookie.setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
cookie一般会保存在本地的用户目录下appdata
session
-
服务器会给每一个用户(浏览器)创建一个session对象
-
一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
-
用户登录后,整个网站它都可以访问
session和cookie的区别
-
cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
-
session把用户的数据写到用户独占session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
-
session对象由服务器创建
使用场景:
-
保存一个登录用户的信息
-
购物车信息
-
在整个网站中经常使用的数据,我们将它保存在session中
使用session
public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决乱码问题 req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); //得到session HttpSession session = req.getSession(); //给session中存东西 session.setAttribute("name","喵喵"); //获取session的id String sessionId = session.getId(); //判断session是不是新创建的 if(session.isNew()){ resp.getWriter().write("session创建成功,ID:"+sessionId); }else { resp.getWriter().write("session已经在服务器中存在,ID:"+sessionId); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } } //得到session HttpSession session= req.getSession(); Person person = session.getAttribute("name"); System.out.println( person.toString()); //手动注销session HttpSession session= req.getSession(); session.removeAttribute("name"); session.invalidate();
会话自动过期 web.xml
<!--设置session默认的失效时间--> <session-config> <!--15分钟后session自动失效,以分钟为单位--> <session-timeout>15</session-timeout> </session-config>
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问servlet
jsp最终也会被转换成一个java类
<%--JSP表达式 作用:用来将程序的输出,输出到客户端--%> <%= new java.util.Date()%> <hr> <%--jsp脚本片段--%> <% int sum=0; for (int i = 0; i < 100; i++) { sum+=i; } out.print("<h1>Sum="+sum+"</h1>"); %> <%--在代码中嵌入HTML元素--%> <% for (int i = 0; i < 5; i++) { %> <h1>hello</h1> <% } %> <hr> <%--jsp声明--%> <%! static { System.out.println("loading servlet"); } private int globalVar=0; public void miao(){ System.out.println("进入了方法miao"); } %>
jsp声明会被编译到JSP生成的java的类中,其他就会被生成到jspService方法中
在jsp中嵌入java代码即可
jsp的注释,不会在客户端显示,html就会
9大内置对象
PageContext 存东西
Request 存东西
Response
Session 存东西
Application [ServletContext ] 存东西
config [ServletConfig]
out
page 不用
exception
pageContext.setAttribute("name1","喵喵1号");//保存的数据只在一个页面中有效 request.setAttribute("name2","喵喵2号");//保存的数据只在一次请求中有效,请求转发会携带这个数据 session.setAttribute("name2","喵喵2号");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器 application.setAttribute("name2","喵喵2号");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
request:客户端向服务器发送请求,产生的数据,用户看完就没用了。比如新闻
session:客户端向服务器发送请求,产生的数据,用户用完一会儿还有用,比如购物车
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可以使用,比如聊天数据
<!--jstl表达式的依赖--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
EL表达式: ${}
-
获取数据
-
执行运算
-
获取web开发的常用对象
JSP标签
<jsp:forward page="/jsptag2.jsp"> <jsp:param name="name" value="miaomiao"></jsp:param>
JSTL标签
<%--引入JSTL核心标签库,我们才能使用JSTL标签--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <form action="jsptag2.jsp" method="get"> <%--EL表达式获取表单中的数据--%> <input type="text" name="username" value="${param.username}"> <input type="submit" value="登录"> <c:if test="${param.username='admin'}" var="isAdmin"> <c out value="管理员欢迎您"/> </c:if> <c: out value="${isAdmin}"/>
实体类
-
JavaBean有特定的写法
-
必须要有一个无参构造
-
属性必须私有化
-
必须有对应的get/set方法
一般用来和数据库的字段作映射