1.Servlet基础
servlet是运行在Web服务器端的Java应用程序,与Java此程序的区别就是,Serlvet对象主要封装了HTTP请求的处理,并且它的运行需要Servle容器的支持。
1.1 Servlet结构体系
Servlet是一个标准 Servlet和ServletConfig定义了Servlet的基本方法和相关配置信息
1.2 Sevlet技术特点
1.3 Servlet与JSP的区别
- 角色不同
- 编程方法不同
- Servlet需要编译后运行
- 速度不同
1.4 第一个Servlet例子
创建Servlet
package com.lxg.servlet;
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 java.io.IOException;
public class Serlvet3 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}
在web.xml中配置servlet
<servlet>
<servlet-name>servlet3</servlet-name>
<servlet-class>com.lxg.servlet.Servlet3</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servlet3</servlet-name>
<url-pattern>/servlet3</url-pattern>
</servlet-mapping>
1.5 Servlet生命周期
- 初始化阶段,可以是在服务器启动初始化,也可以在第一次调用初始化,生成实例。
- 调用init();
- 调用servicr();判断是哪一种请求,get请求会调用doGet(),post请求调用doPost();
- 在服务器停止的时候,调用destroy();
package com.lxg.servlet;
import javax.servlet.*;
import java.io.IOException;
public class Servlet2 implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init...");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service...");
}
public String getServletInfo() {
return null;
}
public void destroy() {
System.out.println("destroy...");
}
}
几个知识点:
- Servlet 启动时自动装载servlet,需要在 web.xml配置,在之间添加如下代码:< loadon-starup >1< /loadon-starup>,数字越小,优先级越高。如果不配置,则第一次访问servlet时装载。
- servlet被加载的时候,会调用init()方法,在整个生命周期中init() 只会调用一次,装载后,实例贮存在服务器的内存中。
2.Servlet API编程常用接口和类
2.1 Servlet接口
package com.lxg.servlet;
import javax.servlet.*;
import java.io.IOException;
public class Servlet1 implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("servlet service running...");
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
2.2 ServletConfig接口
封装Servlet的配置信息,在Serlvet初始化期间被传递,每一个Servlet都有且是有一个ServletConfig对象。
ServletConfig servletConfig = getServletConfig();
servletConfig.getInitParameter("init");
servletConfig.getInitParameterNames();
servletConfig.getServletContext();
servletConfig.getServletName();
2.3 HttpServletRequest接口
继承了javax.servlet.ServletRequest接口。
req.getContextPath();
req.getCookies();
req.getMethod();
req.getQueryString();
req.getRequestURI();
req.getServletPath();
req.getSession();
package com.lxg.request;
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 java.io.IOException;
import java.util.Enumeration;
@WebServlet("/request1")
public class Request1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
String contextPath = req.getContextPath();
String servletPath = req.getServletPath();
String queryString = req.getQueryString();
String requestURI = req.getRequestURI();
StringBuffer requestURL = req.getRequestURL();
String protocol = req.getProtocol();
System.out.println(method);
System.out.println(contextPath);
System.out.println(servletPath);
System.out.println(queryString);
System.out.println(requestURI);
System.out.println(requestURL);
System.out.println(protocol);
System.out.println("-------------------------------");
Enumeration<String> headerNames = req.getHeaderNames();
while(headerNames.hasMoreElements()){
String header = req.getHeader(headerNames.nextElement());
System.out.println(header);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}
2.4 HttpServletResponse接口
继承了javax.servlet.ServletResponse接口
resp.addCookie(new Cookie("hh","test"));
resp.sendError(404);
resp.sendError(404,"msg");
resp.sendRedirect("/location");
2.5 GenericServlet类
GenericServlet实现了Servlet接口,将接口中的其他方法都做了默认实现,只是将service()方法作为抽象方法 如果通过集成GenericServlet来实现Serlvet类,只需要重写service方法即可,其他的方法,根据需要来选择是否重写
2.6 HttpServlet类
HttpServlet继承了GenericServlet类,通过其对GenericServlet类的扩展,可以很方便的对HTTP 请求进行处理及响应.
3.Servlet获取表单数据
login.jsp
<html>
<head>
<title>login</title>
<script>
window.onload=function () {
document.getElementById("img").onclick=function(){
this.src="checkCodeServlet?time="+new Date().getTime();
}
}
</script>
<style>
div{
color:red;
}
</style>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td>验证码</td>
<td><input type="text" name="checkCode"></td>
</tr>
<tr>
<td colspan="2"><img id="img" src="checkCodeServlet"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
<div><%=request.getAttribute("cc_error")==null?"":request.getAttribute("cc_error")%></div>
<div><%=request.getAttribute("login_error")==null?"":request.getAttribute("login_error")%></div>
</body>
</html>
loginServlet.ava获取登录页面的参数并处理
package com.lxg.session;
@WebServlet("/loginServlet")
public class LonginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String checkCode = req.getParameter("checkCode");
HttpSession session = req.getSession();
String checkCode_session = (String)session.getAttribute("checkCode_session");
session.removeAttribute("checkCode_session");
if(checkCode_session!=null && checkCode_session.equalsIgnoreCase(checkCode)){
if("zhangsan".equals(username)&&"123".equals(password)){
session.setAttribute("user",username);
resp.sendRedirect(req.getContextPath()+"/success.jsp");
}else{
req.setAttribute("login_error","用户名或密码错误");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}else{
req.setAttribute("cc_error","验证码不一致");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
}
4.Servlet之间的跳转
1.转发(forward)
转发是通过requestDispatcher对象的forward(httpServletRequest req,HttpServletResponse res)方法来实现的。
request.getRequestDispatcher("/servlet/LifeCycleServlet").forward(request,response);
其中getRequestDispatcher方法的参数,必须以“/”开头,表示web的根目录,比如要 跳转: ”http://locahost:8080/servlet/servet/LifeCycleServlet”, 则参数为”/servlet/LifeCycleServlet”.
2.重定向(redirect)
通过httpServlet的sendDirect(String location)方法。
5.获取初始化参数
- 在 web.xml中配置servlet时,可以配置一些初始化参数,在servlet可以通过servletConfig接口提供的接口获取这些参数。
在web.xml中配置init-param 参数:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>forezp</param-value>
</init-param>
</servlet>
在servlet中获取
public class HelloServlet extends HttpServlet {
@Override
public void init() throws ServletException {
super.init();
String name=this.getInitParameter("username");
System.out.println(name);
}
}
部署项目,访问helloServlet就可以看见在控制台打印了forezp
2.也可以配置一些全局的参数:context-param.
<web-app version="2.5" 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_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>haha</param-name>
<param-value>xixi</param-value>
</context-param>
</web-app>
获取方式:
servlet中通过getServletContext()获取servletContext对象,使用ServletContext的getInitParameter()方法获取制定参数名来获取参数。
ServletContext servletContext=getServletConfig().getServletContext();
String str=servletContext.getInitParameter("haha");
System.out.println(str);
6.servlet九大内置对象
|