Servlet
Servlet是很多框架的技术基础
Servlet是特殊的java类,没有main方法,运行于服务端,创建和销毁都由Servlet容器管理
Servlet容器值tomcat。
Servlet与http紧密联系,Servlet可以处理几乎所有http相关的内容
简单的Servlet程序,输出hello
添加Servlet类:
package com.jike.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { @Override public void init() throws ServletException { System.out.println("====init无参方法====="); super.init(); } @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub System.out.println("====init带参方法====="); super.init(config); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("====service====="); //super.service(arg0, arg1); // 编写service方法体 PrintWriter pw = resp.getWriter(); pw.println("hello"); pw.close(); } @Override public void destroy() { System.out.println("====destroy====="); super.destroy(); } }
在web.xml文件中添加:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet><!-- 用于注册一个Servlet --> <servlet-name>HelloServlet</servlet-name><!-- 设置注册名称 --> <servlet-class>com.jike.servlet.HelloServlet</servlet-class><!-- 设置完全限定名 --> </servlet> <servlet-mapping><!-- 映射Servlet对外访问的路径 --> <servlet-name>HelloServlet</servlet-name><!-- servlet的注册名称,与 <servlet-name>中的一致--> <url-pattern>/Hello</url-pattern><!-- 指定Servlet对外访问的路径 --> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
在浏览器中访问http://localhost:8080/JSPStudy/Hello
Servlet中的包:
javax.servlet: 包含了Servlet最基本的接口和类。
接口:
- Servlet :声明所有Servlet必须实现的方法
- ServletRequest:获取客户端请求信息的方法
- ServletResponse:声明了向客户端浏览器发送相应的方法
- ServletConfig : 什么了Servlet配置信息的方法
- ServletContext : 用于获取Servlet容器信息的方法
类:
- GenericServlet :定义通用的,独立于底层协议的一般性的Servlet
- ServletInputStream : 从客户端读取二进制数据
- ServletOutputStream : 向客户端发送二进制数据
javax.servlet.http:基于http协议的接口和类
接口:
- HttpServletRequest : 为http提供请求信息
- HttpServletResponse : 发送http协议的相应信息
- HttpSession : 表示客户端并存储客户端的有关信息
类:
- HttpServlet : 扩展自GenericServlet,创建基于http协议的Servlet
- Cookie : 存储Servlet发送给客户端的信息
javax.servlet.annotation:Servlet的一些注解
javax.servlet.descriptor : 获取jsp或者标签库的配置信息
Servlet编程实例
登录信息:
设置登录页面:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="<%= request.getContextPath() %>/loginServlet"> userName:<input type="text" name="uname"/><br/> password:<input type="password" name="upwd"/><br/> <input type="submit" value="Login"/> <input type="reset" value="Reset"/> </form> </body> </html>
Servlet:
package com.jike.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 5864346102781070171L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.service(req, resp); // 获取表单提交的内容 String userName = req.getParameter("uname"); String password = req.getParameter("upwd"); System.out.println("username:" + userName); System.out.println("password:" + password); } }
在web.xml中添加:
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.jike.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping>
HTTP请求的类型
OPTIONS : 返回服务器支持的HTTP方法
POST : 将指定的资源提交到服务器进行处理
GET : 从指定的资源请求数据
PUT : 上传指定的资源
DELETE : 删除指定的资源
HEAD : 与get相同,但是只返回HTTP的报头,不会返回主体
GET 与POST的区别:
对LoginServlet.java做如下修改:
package com.jike.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 5864346102781070171L; // @Override // protected void service(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // TODO Auto-generated method stub //super.service(req, resp); // 获取表单提交的内容 // String userName = req.getParameter("uname"); // String password = req.getParameter("upwd"); // // System.out.println("username:" + userName); // System.out.println("password:" + password); // } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("============doGet=============="); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("========doPost============="); String userName = req.getParameter("uname"); String password = req.getParameter("upwd"); System.out.println("username:" + userName); System.out.println("password:" + password); } }
这样GET和POST请求可以共用。
完善登陆页面
完整代码如下:
Servlet:
package com.jike.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 5864346102781070171L; // @Override // protected void service(HttpServletRequest req, HttpServletResponse resp) // throws ServletException, IOException { // TODO Auto-generated method stub //super.service(req, resp); // 获取表单提交的内容 // String userName = req.getParameter("uname"); // String password = req.getParameter("upwd"); // // System.out.println("username:" + userName); // System.out.println("password:" + password); // } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("============doGet=============="); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("========doPost============="); String userName = req.getParameter("uname"); String password = req.getParameter("upwd"); System.out.println("username:" + userName); System.out.println("password:" + password); String forword = null; if(userName.equals("thystar") && password.equals("thystar")){ // 请求转发 // 使用请求转发只能使用同一应用的地址,不能转发其他页面的地址 // 假设forward = "http://www.baidu.com";则请求转发出现404错误 forword = "/08/success.jsp";//转发地址 //RequestDispatcher 请求调度器,封装转发的操作,接收来自客户端的请求 // 然后将其转发到指定的资源 RequestDispatcher rd = req.getRequestDispatcher(forword); rd.forward(req, resp); // 请求重定向 // 请求重定向无法在跳转页面得到username,和password的值, // 但是请求转发可以使用不同应用的地址 // 假设forward="http://www.baidu.com";请求重定向可以访问。 //resp.sendRedirect(req.getContextPath() + "/08/success.jsp"); }else{ // 请求转发 forword = "/08/error.jsp"; RequestDispatcher rd = req.getRequestDispatcher(forword); rd.forward(req, resp); // 请求重定向 //resp.sendRedirect(req.getContextPath() + "/08/error.jsp"); } } }
在WebRoot下新建 /08/success.jsp,添加代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 登陆成功<br/> 用户名: <%= request.getParameter("uname") %><br/> 密码:<%= request.getParameter("upwd") %><br/> <a href="login.jsp">返回登陆页面</a> </body> </html>
新建 /08/error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 登陆失败<br/> 用户名: <%= request.getParameter("uname") %><br/> 密码:<%= request.getParameter("upwd") %><br/> <a href="login.jsp">返回登陆页面</a> </body> </html>
/08/login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="<%= request.getContextPath() %>/loginServlet" method="post"> userName:<input type="text" name="uname"/><br/> password:<input type="password" name="upwd"/><br/> <input type="submit" value="Login"/> <input type="reset" value="Reset"/> </form> </body> </html>
在web.xml中添加:
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.jike.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping>
极客学院:http://www.jikexueyuan.com/course/584.html
部分图片从课程中直接截取