JavaWeb04_Servlet应用初步

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb04_Servlet应用初步相关的知识,希望对你有一定的参考价值。

JavaWeb04_Servlet应用初步

获取上下文对象

方法一:重写init()方法,通过ServletConfig对象获得:

public ServletContext context;
@Override
public void init(ServletConfig config) throws ServletException { 
    context = config.getServletContext();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    context.setAttribute("key", "小王");
}  

方法二:

ServletContext context = this.getServletContext();  

注意,一旦重写了init()方法,就不能通过这种方式获取上下文对象!!

获取网站访问次数的简单实现

public class ServletContext2 extends HttpServlet{
public ServletContext context;
    public int numb;

    @Override
    public void init(ServletConfig config) throws ServletException {  
        context = config.getServletContext();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String number = (String) context.getAttribute("num");
        if(number == null){
            numb = 1;
        }else{
            numb = Integer.parseInt(number)+1;
        }
        System.out.println("当前网站访问次数:"+numb);

        context.setAttribute("num", numb+"");   
    }
}  

页面跳转的方法:

方法一:

response.sendRedirect("/JavaWeb03/main.html");  

方法二:

response.setStatus(302);
response.setHeader("location", "/JavaWeb03/main.html");  

方法三:

response.setHeader("refresh", "3; /JavaWeb03/main.html" );  

Write or print?

//print 和 write 都是输出内容到客户端
//共同点:两者都不会刷新页面,都是在原来基础上继续增加内容,这两个方法都是重写了抽象类里面的write方法
//区别:print 方法可以将各种数据类型都转化为字符串进行输出,write 方法只能输出字符、字符串、字符数组等

PrintWriter out = response.getWriter();

out.print("123");
out.write(123);

out.write("123");
out.write(123);   //无法输出  

两种方式输出内容到html:

方式一:getWriter();

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html; charset=utf-8");
    response.setCharacterEncoding("utf-8");

    PrintWriter out = response.getWriter();

    out.print("<html>");
    out.print("<head><title>今天中午吃什么</title></head>");
    out.print("<body><p>THIS IS P</p></body>");     
    out.print("</html>");

    out.print("吃屎吧");  

方式二:getOutputStream();

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("utf-8");

    //如果:输出二进制文件?
    OutputStream out = response.getOutputStream();

    String str = "今天天气还可以";
    byte[] by = str.getBytes("utf-8");
    out.write(by);

    out.write((1+"").getBytes());       
}  

如何实现文件下载?

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("utf-8");

    //文件下载:设置响应头
    response.setHeader("Content-type", "image/jpeg; charset=utf-8");
    response.setHeader("Content-Disposition", "attachement; filename=BeautifulGirls");
                        //Disposition:配置        attachement:附件

    //获取到文件的物理路径:getRealPath 获取文件的路径    可以将虚拟路径转化为物理路径(绝对路径)
    String path = this.getServletContext().getRealPath("/img/13.jpg");
    System.out.println(path);

    //通过二进制流将图片读取出来
    int len=0;
    byte[] by = new byte[1024];    //一次读取1024字节

    //通过文件的输入流获取文件
    InputStream in = new FileInputStream(new File(path));    //文件读取到内存中去

    //创建一个文件输出流,将内容输出到客户端
    OutputStream out = response.getOutputStream();
    while((len = in.read(by)) > 0){        //read(by)  表示一次读取上面定义的1024字节,也可以一个字节一个字节读:read()
        //输出到客户端
        out.write(by,0,len);
    }
    //关闭流
    in.close();
    out.close();
}

以上是关于JavaWeb04_Servlet应用初步的主要内容,如果未能解决你的问题,请参考以下文章

JavaWeb02_servlet和web容器

java web入门-servlet初步

JAVAWEB学习笔记13_servlet

新入职如何快速去了解一个Javaweb项目!

如何快速去了解一个Javaweb项目?

JavaWeb学习之Servlet----ServletConfig获取配置信息ServletContext的应用(转)