今日内容:

1. Servlet
2. Request

Servlet

1. 概念
2. 步骤
3. 执行原理
4. 生命周期
5. Servlet3.0注解配置
6. Servlet的体系结构
servlet--接口
|
GenericServlet---抽象类
|
HttpServlet---抽象类
* GenericServlet:将Servlet接口的其他方法做了默认空实现,只将service()方法作为抽象
* 将来定义Servlet类时,可以继承GenericServlet,实现service()方法即可 * HttpServlet:对http协议的一种封装,简化操作。
1. 定义类继承HttpServlet
2. 复写 了doGet/doPost方法
7. Servlet的相关配置
1. urlpartten:Servlet访问路径
1. 一个Servlet可以定义多个访问路径:@ WebServlet({"/d4","/dd4"})
2. 定义规则
1. /xxx:路径匹配
2. /xxx/xx:多层路径,目录结构
3. *.do:扩展名匹配
8. ServlerContext
1. WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
2. 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
3. 由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
4. 实例在servlet中创建文件是,不要直接创建,因为你直接创建的文件在tomcat的BIN目录下,可以通过servletContext.getRealPath(),获取当前项目在tomcat中的部署目录,在该目录下创建文件较好
* 比如:
* ServletContext servletContext = getServletContext();
String realPath = servletContext.getRealPath("hello.txt");
File file1 = new File(realPath);
boolean newFile1 = file1.createNewFile();
System.out.println(newFile1);
}

request

1. requset和response对象的原理
1. requset和response对象是服务器创建的,我们来使用他们
2. request对象是来获取请求消息的,response是类设置响应消息的
2. request对象继承体系结构、
ServletRequest ----接口
|
HttpServletRequest --接口
|
org.apache.catalina.connector.RequestFacade 类(tomcat)
3. request的功能:
1. 获取请求消息数据
1. 请求行数据
* get/day14/demo1?anme=xxx HTTP/1.1
* 方法
1. 获取请求方式:GET
* String getMethod()
2. (*)获取虚拟目录:/day14
* String getContextPath()
3. 获取资源路径(Servlet路径):/demo
* String getServletPath()
4. 获取get方式的请求参数:name=zhangsan
* String getQueryString()
5. (*)获取请求uri:/day14/demo1
* String getRequestURI(): /day14/demo1
* StringBuffer getRequestURL():http://localhost/day14/demo1
*
* URL:统一资源定位符:http://localhost/day14/demo1
* URI:统一资源标识符: /day14/demo1
6. 获取协议及版本:HTTP/1.1
* String getProtocol()
7. 获取客户机的IP地址:
* String getRemoteAddr()
2. 请求头数据
* 方法
1. String getHeader(String name):通过请求头获取去请求头值
2. Enumeration<String> getHeaderNames():获取所有的请求头名称
3. 请求体数据
* 请求体:只有POST请求方式,才有请求体,在请求体中封装了POST请求的请求参数
* 步骤:
1. 获取流对象
* BufferedReader getReader():获取字符输入流,只能操作字符数据
* ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据
* 在文件上传知识点后讲解
2. 再从流对象中拿数据 2. 其他功能
1. 获取请求参数通用方法:get和post都可以只用下面方法
1. String getParameter(String name):根据参数名称获取参数值 username=zs&password=123
2. String[] getParameterValues(String name):根据参数名称获取参数值的数组 hobby=xx&hobby=game
3. Enumeration<String> getParameterNames():获取所有请求的参数名称
4. Map<String,String[]> getParameterMap():获取所有参数的map集合 * 中文乱码问题:
* get方式:tomcat 8 已经将get方式乱码问题解决了
* post方式:会乱码
* 解决:在获取参数前,设置request的编码request.setCharacterEncoding("utf-8");
2. 请求转发:一种在服务器内部的资源跳转方式
1. 步骤:
1. 通过request对象获取请求转发器对象:RequestDispatcher getRequestDispatcher(String path);
2. RequeatDispatcher对象进行转发:forward(ServletRequest request,ServletResponse response)
2. 特点:
1. 浏览器地址栏路径不发生变化
2. 只能转发到当前服务器内部资源
3. 转发是一次请求的 3. 共享数据
* 域对象:一个有作用范围的对象,可以在范围内共享数据
* request域:代表一次请求的范围,一般用于请求转发的多个资源共享数据
* 方法
1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对
4. 获取ServletContext
* ServletContext getServletContext()

案例:用户登录

1. 案例需求
1. 编写login.html登录页面
username & password 两个输入框
2. 使用Druid数据库连接池技术,操作mysql,day14数据库中user表
3. 使用JdbcTemplate技术封装JDBC
4. 登录成功跳转到SuccessServlet展示:登录成功!用户名,欢迎您
5. 登录失败跳转到FailServlet展示:登录失败,用户名或密码错误
2. 代码:
1. 创建User类,setXxx,getXxx方法,导入jar包。包括三种jar包
2. * JDBC工具类 使用Durid连接池
*/
public class JDBCUtils {
private static DataSource ds ; static {
try {
//1.加载配置文件
Properties pro = new Properties();
//使用ClassLoader加载配置文件,获取字节输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//2.初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接池对象
*/
public static DataSource getDataSource(){
return ds;
} /**
* 获取连接Connection对象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
3. 创建类UserDao,提供login方法
package cn.itcast.dao; import cn.itcast.domain.User;
import cn.itcast.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate; /**
* 操作数据库中User表的类
*/
public class UserDao { //声明JDBCTemplate对象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); /**
* 登录方法
* @param loginUser 只有用户名和密码
* @return user包含用户全部数据,没有查询到,返回null
*/
public User login(User loginUser){
try {
//1.编写sql
String sql = "select * from user where username = ? and password = ?";
//2.调用query方法
User user = template.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword()); return user;
} catch (DataAccessException e) {
e.printStackTrace();//记录日志
return null;
}
}
}
4. 编写cn.itcast.web.servlet.LoginServlet类
package cn.itcast.web.servlet;
import cn.itcast.dao.UserDao;
import cn.itcast.domain.User;
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; @WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码
req.setCharacterEncoding("utf-8");
//2.获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.封装user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
//4.调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser); //5.判断user
if(user == null){
//登录失败 req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
//登录成功
//存储数据
req.setAttribute("user",user);
//转发
req.getRequestDispatcher("/successServlet").forward(req,resp);
} } @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
} 5. 编写FailServlet和SuccessServlet类
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取request域中共享的user对象
User user = (User) request.getAttribute("user");
if(user != null){
//给页面写一句话
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
}
} @WebServlet("/failServlet")
public class FailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给页面写一句话 //设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录失败,用户名或密码错误");
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
} 6. login.html中form表单的action路径的写法
* 虚拟目录+Servlet的资源路径 7. BeanUtils工具类,简化数据封装
* 用于封装JavaBean的
1. JavaBean:标准的Java类
1. 要求:
1. 类必须被public修饰
2. 必须提供空参的构造器
3. 成员变量必须使用private修饰
4. 提供公共setter和getter方法
2. 功能:封装数据
2. 概念:
成员变量:
属性:setter和getter方法截取后的产物
例如:getUsername() --> Username--> username
3. 方法:
1. setProperty()
2. getProperty()
3. populate(Object obj , Map map):将map集合的键值对信息,封装到对应的JavaBean对象中

最新文章

  1. dom 操作
  2. Spring中的自动装配
  3. C#技术漫谈之垃圾回收机制(GC)(转)
  4. 字符串与json之间的相互转化
  5. NSDate 获取明天、后天的日期
  6. OneProxy分库分表演示--楼方鑫
  7. mac 下周期调度命令或脚本
  8. java接口相关例题
  9. javascript 数组方法解析
  10. simpleImageTool又纯java图片水印、缩放工具
  11. 使用jdk8 stream 统计单词数
  12. loadrunner 关联函数web_reg_save_param
  13. [Charles]SSLHandshake: Received fatal alert: certificate_unknown
  14. 转://云和恩墨的两道Oracle面试题
  15. nginx 1.4.3能直接升到1.8.1吗
  16. CSS expression属性
  17. 《剑指offer》-斐波那契数列
  18. Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column &#39;information_schema.PROFILING.SEQ&#39; which is not functionally dependent on columns in GROUP BY clause; this
  19. Enterprise Library 4.1 参考源码索引
  20. 移动端图片轮播—swipe滑动插件

热门文章

  1. doT的高级用法及loadData的使用
  2. CF - 一直交换元素的规律
  3. Office系列(2)---提取Office文件(Word、PPT)中的所有图片
  4. transient简介
  5. unbuntu18.04安装启用splash
  6. C#图片采集软件 自动翻页 自动分类(收集美图必备工具)(一)
  7. 【实战】使用 Kettle 工具将 mysql 数据增量导入到 MongoDB 中
  8. cocos2dx,Layer锚点与scale缩放
  9. (转自360安全客)深入理解浏览器解析机制和XSS向量编码
  10. Dappy如何防止DNS黑客入侵