JavaEE Day04 servlet
Day04 servlet
目录
网页开发技术
静态网页开发技术:html
动态网页开发技术:servlet/jsp
服务器
- 性能优越的计算机(硬件)
- 操作系统(linux,windows)
- 服务器软件(存储和管理资源,提供外部访问方式)
- web应用程序(处理客户端请求)
服务器软件(应用服务器软件)
- IIS:microsoft公司,大型应用服务器,支持动态网页开发技术较多
- Weblogic:oracle公司,大型应用服务器,13种网页开发技术
- nginx:Web服务器,负载均衡(反向代理)
- apache:apache基金会,
- tomcat:apache服务器,支持servlet/jsp,占用资源较小,
tomcat服务器
开源免费的小巧的服务器软件
apache,sun,其他组织共同开发完成,支持最新的java技术,servlet、jsp动态网页开发技术。
下载和安装
下载
http://www.apache.org
http://archive.apache.org/dist/
安装
-
tomcat需要jdk支持,必须先配置java的边境变量,必须配置java_home,
-
解压tomcat压缩包
-
目录结构
bin:脚本,及启动时用到的类; lib:类库 conf:配置文件; logs:日志文件; webapps:webapp默认的部署目录 work:工作目录,存放jsp文件 temp:临时文件目录
启动tomcat
- startup.bat
- shutdown.bat
注意:尽量在命令行输入命令
访问资源
基本配置
主机映射:域名和ip映射
- windows:c:\wondows\System32\drivers\etc\hosts
- Linux:/etc/hosts
查看端口对应的pid
netstat -ano
windows杀死进程
taskkill /pid 7908
修改端口
conf/server.xml -> connector:port修改端口
放置资源并访问
web应用程序
创建web应用程序
eclipse集成tomcat

调出servers面板,点击创建服务,

双击该服务器 修改应用程序部署目录

启动服务器
创建应用程序
-
创建动态网页项目
-
next-》next->content root:应用程序部署在tomcat的根目录的名称
Content directory:应用程序的根目录
应用程序的配置文件
创建web.xml -
目录结构
- src:存放源文件
- webCountent:应用程序根目录(资源,html,css,js,视频….)
- web-inf:不能被外部直接访问,起文件保护作用;
- lib:第三方jar包
- Web.xml:应用程序配置文件
什么是servlet
- 运行与服务器端的java应用程序
- 实现servlet接口
- 接受客户端请求
- 返回给客户端响应(html)
创建servlet的步骤
- 创建类,实现servlet接口(Httpservlet:抽象类,实现了servlet接口)servlet接口 方法很多,不常用,我们一般继承httpservlet接口即可;
- 配置servlet访问路径
-
配置web.xml文件
<!-- 配置servlet访问路径 --> <servlet> <servlet-name>hello</servlet-name> <!-- 全限定名称 --> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <!-- 访问规则 1. /hello http://localhost:8080/javaweb_01/hello 2. /* http://localhost:8080/javaweb_01/aad 3. *.do http://localhost:8080/javaweb_01/adfa.do --> <url-pattern>/hello</url-pattern> </servlet-mapping> -
可以使用webServlet注解;
-
HttpServletRequest
请求对象(封装了请求报文);
获取请求参数
getParameter(name)
getParameterValues(name) 数组
域对象:可以存取数据(实现数据共享)
- 作用域:一次请求,请求次数
- 常见方法:
1. setAttribute(name,vaule)
2. getAttribute(name)
3. removeAttribute(name)
HttpServletResponse
响应对象(封装响应报文)
PrintWriterpw=resp.getWriter();
pw.println("seccess");
pw.close();
乱码问题的解决
原因:编码不一致
- get: tomcat8+:不会乱码; tomcat7-:乱码(
<Connector URIEncoding="UTF-8" />) - post: 设置请求编码为utf-8;
- 响应编码
resp.setCharacterEncoding("utf-8");
//设置浏览器显示方式
resp.setContentType("text/html;charset=utf-8");//以什么方式展开这个数据
Jsp
- Javaserver pages :运行于服务器端页面
- jsp格式:html+java
- 本质就是:servlet
页面跳转(servlet之间)
转发:
request.setAttribute("name", username);
request.getRequestDispatcher("success.jsp").forward(request, response);
重定向:
response.sendRedirect("success.jsp");
转发和重定向区别
- 转发:服务器端行为;客户端只发送一次请求,服务器端利用转发实现内部数据共享;地址栏没有变化。
- 重定向:客户端行为;客户端发送第一次请求,服务器端响应302的状态码以及新的url;客户端根据响应的新url再次发送请求;地址栏发生变化
域对象
request:一次请求
servletContext:application域,作用域整个应用程序
- 创建:应用程序被部署到服务器;
- 销毁:应用程序从服务器被移除或者服务器关闭
- 获取application域:getServletContext();
- 存储整个应用程序中共享数据(统计网站访问次数)
会话
客户端与服务器端一次长连接
会话跟踪技术
cookie:由服务器端产生并保存与客户端的一段文本;
创建cookie:
//创建cookie
Cookiecookie=newCookie("username",username);
//设置cookie有效时长,单位是秒;
//默认情况关闭浏览器消失,设置时长后,更具时长判断是否失效,而不会关心浏览器是否关闭
cookie.setMaxAge(10);
//响应回客户端
response.addCookie(cookie);
获取cookie:
Cookie[]cookies=request.getCookies();
Stringstr="";
if(cookies!=null){
for(Cookiecook:cookies){
if("username".equals(cook.getName())){
str=cook.getValue();
break;
}
}
}
Session:
服务器端为每个客户端创建独特的Session,并将sessionid响应并保存到cookie中;该客户端再次访问时,将携带sessionid寻找自身独特的session,实现数据的共享。
域对象:会话域对象,实现整个会话内的数据共享;
session失效场景
//有效时长:默认30分钟
//设置有效时长
session.setMaxInactiveInterval(3600*24);
//立即失效
//session.invalidate();
session的应用场景
- 自动登录
- 保存用户信息
- 用户登录验证
- 注销功能:
session.invalidate();
El
- Expression language:表达式语言
${name} - 获取域中的数据(只能获取域中数据,不在4个域中的数据都不能获取)
- 实现运算(算术,比较,逻辑,empty:判断为 空)
Jstl
- Apache Standard Taglib(JSTL),引用于jsp的标签库
- 下载和导入jstl的jar(所有的jar files)
- 导入jstl标签库到jsp页面
<%@tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c"%> - 在jsp页面使用标签
<%--判断:test支持使用el表达式--%>
<c:iftest="${score>=60}">
恭喜过关!
</c:if>
<%--多分支--%>
<c:choose>
<c:whentest="${score>=60}">
恭喜过关!
</c:when>
<c:otherwise>
下次努力!
</c:otherwise>
</c:choose>
<%--循环:items:需要遍历的集合(支持使用el表达式)var:元素名称--%>
<c:forEachitems="${eles}"var="str">
${str}
</c:forEach>
过滤器
- 实现请求和响应的过滤
- 编写类实现filter接口
- 配置filter过滤规则
全局编码过滤器
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(filterName = "filter.CharsetFilter",value = "/*")
public class CharsetFilter implements Filter {
// filter 销毁时调用
public void destroy() {
}
// 对请求和响应进行过滤
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
// 全局编码设置
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// System.out.println("接受到请求");
// 放行
chain.doFilter(req, resp);
// System.out.println("接受到响应");
}
// filter初始化时 (只执行一次)
public void init(FilterConfig config) throws ServletException {
}
}
获取网站点击此处的过滤器
package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Map;
@WebFilter(filterName = "showFilter",value = "/show.jsp")
public class showFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
Map<String,Integer> ipMap = (Map<String, Integer>) req.getServletContext().getAttribute("map");
// 获取客户端的ip地址
String ip = req.getRemoteAddr();
Integer count = ipMap.get(ip);
if(count == null){
ipMap.put(ip,1);
}else{
ipMap.put(ip,count+1);
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
监听器
- 监听request,session,application域的创建销毁以及属性变化;
- 编写类实现listener接口
- 配置监听器
属性监听器
package listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener()
public class MyApplicationAttributeListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// -------------------------------------------------------
// HttpSessionAttributeListener implementation
// -------------------------------------------------------
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is added to a session.
*/
// 属性添加
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is removed from a session.
*/
// 属性删除
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attibute
is replaced in a session.
*/
// 属性修改
}
}
application域监听器
package listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;
@WebListener()
public class MyApplicationListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
System.out.println("application域创建");
Map<String,Integer> ipMap = new HashMap<>();
sce.getServletContext().setAttribute("map",ipMap);
}
public void contextDestroyed(ServletContextEvent sce) {
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
System.out.println("application域销毁");
}
}


浙公网安备 33010602011771号