[Javaweb 02] Servlet,Context,req,resp

Servlet


1. Servlet


1. Servlet简介

sun公司开发动态web技术,把实现了servlet接口的Java程序叫Servlet

方式:

  • 编写一个实现Servlet接口的类
  • 把开发好的Java类部署到web服务器中

2. HelloServlet

  1. 构建普通Maven项目,建立module子模块;

  2. 父项目中,会多

    <modules>
        <module>helloServlet-01</module>
    </modules>
    
  3. 子项目中会多parent的标签声明,子项目可以使用父项目的所有依赖。

  4. 创建(先看servlet接口的源代码分析)

    1. Servlet接口---->GenericServlet抽象类实现--->HttpServlet抽象类继承--->自定义类

    2. 在类中实现doGet(), 编写输出流,resq.getWrite(), 对象.print()

    3. 注册servlet

        <!--添加一个servlet名,添加这个名字所对于的class文件路径-->
        <servlet>
          <servlet-name>hello</servlet-name>
          <servlet-class>com.roy.hello.HelloServlet</servlet-class>
        </servlet>
        <!--添加servlet映射路径,添加servlet名,添加在浏览器中访问时所需要输入的路径后缀-->
        <servlet-mapping>
          <servlet-name>hello</servlet-name>
          <url-pattern>/hello</url-pattern>
        </servlet-mapping>
      
  5. 项目中生成的target目录:包含运行后打包生成的war包,其中.war为压缩,项目名为.war解压后的包

3. Servlet原理

tomcat做了中间所有的事情,只用实现中间的业务就可以了

4. Mapping问题

servlet-mapping中,可以一对一个url, 可以一对多个url, 可以/* 超过index的优先级

mapping优先级问题:如果在servlet-mapping标签中定义了具体的路径,也定义了/*路径,则具体路径优先级高

/hello路径--hello页面,

/*路径--error页面,

浏览器访问/hello,则会走hello页面

2. ServletContext

web容器启动时,Tomcat会对每个web程序都创建一个ServletContext对象,代表当前的web应用

获得context对象: this.getServletContext

1. 共享数据

ServletContext对象在每一个servlet程序之上, 所以获取都是用this获取

模拟:servlet1程序写String进ServletContext对象中,servlet2程序读

  //servlet1的doget()
ServletContext context = this.getServletContext();
String name = "www";
context.setAttribute("name", name);
//servlet2 doget()
ServletContext servletContext = this.getServletContext();
String name = (String) servletContext.getAttribute("name");
resp.setContentType("text/html");//设置页面显示为html
resp.setCharacterEncoding("utf-8");//设置页面加载的编码方式
PrintWriter writer = resp.getWriter();
writer.print(name);

//需要在web.xml中配置servlet和servlet-mapping

2. 获取参数

context = this.getServletContext;
context.getInitParamater(string);//string是写在web.xml中<context-param>标签中键值对的键, 返回string类型

3. 请求转发

(转发只有一次请求,重定向两次请求)

context = this.getServletContext;
context.getRequestDispatcher("/servel01");//参数为项目下的另一个servlet-mapping的路径

4. 读取资源文件

在resource路径下放置的properties,和.java文件同样被打包到target下的web-INF的classes类路径下。

当properties在java文件夹下时,需要在maven的pom.xml文件下配置resources标签,标签包含directory,resource,included配置

获取文件流的方式:通过context对象将资源转换为流,this.getServletContext().getResourceAsStreaming();,其中参数为资源目录,

资源目录中为/WEB-INF/..., 其中,第一个/表示当前项目的目录,不能省略

Properties对象,需要new创建,Properties prop = new Properties();

思路:1. 获得流,2. 新建Properties对象,3. Properties对象加载流, 4. 获取Properties的key给String或其他对象 5. 输出

InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
prop.load(is);

String un = prop.getProperty("username");
String psw = prop.getProperty("psw");
System.out.println(un+" " + psw);
PrintWriter writer = resp.getWriter();
writer.print(un+" " + psw);

3. HttpServletResponse

1. 基本分类

方法中,基本分为,设置状态码, 设置响应头信息,设置向浏览器发送的信息

传输的信息中

ServletOutputStream getOutputStream() throws IOException;//传输流用
PrintWriter getWriter() throws IOException;//传输中文字符串用

2. 文件下载

  1. 获得文件地址,2. 获得文件名称,3. 设置浏览器头信息, 4. 读入写出流
  2. URLEncoder类,方法encode()用于设置编码方式
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = "F:\\IJ_project_repositories\\servlet-maven-01\\servlet-02\\target\\classes\\1.JPG";
    String fileName = path.substring(path.lastIndexOf("\\")+1);
    //设置响应信息
    resp.setHeader("Content-disposition","attachment;filename"+fileName);
    //如果出现中文问题,设置编码方式
    URLEncoder.encode(fileName, "utf-8");

    FileInputStream fis = new FileInputStream(path);
    ServletOutputStream os = resp.getOutputStream();
    int len;
    byte[] buffer = new byte[1024];
    while((len = fis.read(buffer)) !=-1){
        os.write(buffer, 0, len);
    }
    os.close();
    fis.close();
}

3. 设置响应头信息

通过resp.setHead()去设置所有的响应头属性(参数都是键值对)

4. 重定向

应用常见:用户登录界面

resp.sendRedirect("/项目名称/其他页面");//目录需要在最前面添加项目目录(分析运行后的URL): 即  /项目名称/其他页面

重定向的实现(分析报文):

  1. 设置响应状态码为302, 2. 设置响应头的属性Location为重定向的地址

    resp.setHeader("Location", "/project/servletmapping");
    resp.setStatus(302);
    

和转发:

相同点:都能实现页面跳转

不同点:URL是改变还是不改变(转发不改变,重定向改变,重定向有两个报文 )

请求转发,307, 重定向 302

4. HttpServletRequest

1. 获取前端传递的参数,请求转发

目前接收出现中文乱码问题的解决:

在doGet()方法中设置:

req.setCharacterEncoding("utf-8");//接收和响应都设置编码格式
resp.setCharacterEncoding("utf-8");

代表客户端的一个请求,通过各种get方法,可以获得请求的所有信息。

常用两个方法:

  1. 获取指定的前端参数: req.getParameter(String s)
  2. 获得指定参数(多选框的参数):req.getParameterValues(String s)

请求转发:

req.getRequestDispatcher("/anotherpage.jsp").forward(req, resp);
posted @ 2021-11-27 17:33  Roy2048  阅读(126)  评论(0)    收藏  举报