zoukankan      html  css  js  c++  java
  • javaweb面试一

    1、forward与redirect区别,说一下你知道的状态码,redirect的状态码是多少?

    状态码 说明
    200  客户端请求成功
    302 请求重定向,也是临时跳转,跳转的地址通过Location指定
    400 客户端请求有语法错误,不能被服务器识别
    403 服务器收到请求,但是拒绝提供服务
    404 请求的资源不存在
    500 服务器发生不可预期的错误
    503 由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个Retry-After起头用以标明这个延迟时间。如果没有给出这个Retry-After信息,那么客户端应当以处理500(Server Internal Error)响应的方式处理它。注意:503状态码的存在并不意味着必须在服务器过载的时候使用它。某些服务器只不过是希望拒绝某些客户端的连接。

     

    forward和redirect 都是用于信息资源之间的相互转发,不过他们是两种不同的转发法方式。

    a).forward:直接转发方式,客户端或者浏览器只发送一次请求,Servlet把请求转发给Servlet、HTML、JSP或其它信息资源,由第2个信息资源响应该请求,两个信息资源共享同一个request对象。

      在Servlet编程中,使用接口RequestDispatcher的forward(ServletRequest, ServletResponse)方法,同时还有另外一个方法是include(ServletRequest request, ServletResponse response),用于包含另一个Servlet的资源;定义如下:

      

    public interface RequestDispatcher {
        
        // Forwards a request from a servlet to another resource (servlet, JSP file,or HTML file) on the server.
        public void forward(ServletRequest request, ServletResponse response)
                throws ServletException, IOException;
    
        //  Includes the content of a resource (servlet, JSP page, HTML file) in the response.
        public void include(ServletRequest request, ServletResponse response)
                throws ServletException, IOException;
    
    }

                   

        RequestDispatcher 中两种方法的区别

     

    b).redirect:间接转发方式,服务器端在响应第一次请求的时候,让浏览器再向另外一个URL发出请求,从而达到转发的目的。它本质上是两次HTTP请求,对应两个request对象。状态码是302.

      在Servlet编程中,使用 HttpServletResponse 的 sendRedirect 方法,

    public interface HttpServletResponse extends ServletResponse {
        
        // Sends a temporary redirect response to the client using the specified redirect location URL.
        public void sendRedirect(String location) throws IOException;
    }

    2、servlet生命周期,是否单例,为什么是单例。

      Servlet并不是单例,只是容器让它只实例化一次,变现出来的是单例的效果而已。

       

    (1)加载和实例化

      当Servlet容器启动或客户端发送一个请求时,Servlet容器会查找内存中是否存在该Servlet实例,若存在,则直接读取该实例响应请求;如果不存在,就创建一个Servlet实例。

    (2) 初始化

      实例化后,Servlet容器将调用Servlet的init()方法进行初始化(一些准备工作或资源预加载工作)。

    (3)服务

      初始化后,Servlet处于能响应请求的就绪状态。当接收到客户端请求时,调用service()的方法处理客户端请求,HttpServlet的service()方法会根据不同的请求 转调不同的doXxx()方法。

    (4)销毁

      当Servlet容器关闭时,Servlet实例也随时销毁。其间,Servlet容器会调用Servlet 的destroy()方法去判断该Servlet是否应当被释放(或回收资源)。

    3、说出Servlet的生命周期,并说出Servlet和CGI的区别。

    4、Servlet执行时一般实现哪几个方法?

    1.  public void init(ServletConfig config) throws ServletException;
    2.  public ServletConfig getServletConfig();
    3.  public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
    4.  public String getServletInfo();
    5.  public void destroy();
    public interface Servlet {
    
        /**
         * Called by the servlet container to indicate to a servlet that the servlet
         * is being placed into service.
         *
         */
        public void init(ServletConfig config) throws ServletException;
    
        /**
         *
         * Returns a {@link ServletConfig} object, which contains initialization and
         * startup parameters for this servlet. The <code>ServletConfig</code>
         * object returned is the one passed to the <code>init</code> method.
         *
         * @return the <code>ServletConfig</code> object that initializes this
         *         servlet
         *
         * @see #init
         */
        public ServletConfig getServletConfig();
    
        /**
         * Called by the servlet container to allow the servlet to respond to a
         * request.
         *
         * <p>
         * This method is only called after the servlet's <code>init()</code> method
         * has completed successfully.
         */
        public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException;
    
        /**
         * Returns information about the servlet, such as author, version, and
         * copyright.
         *
         */
        public String getServletInfo();
    
        /**
         * Called by the servlet container to indicate to a servlet that the servlet
         * is being taken out of service. This method is only called once all
         * threads within the servlet's <code>service</code> method have exited or
         * after a timeout period has passed. After the servlet container calls this
         * method, it will not call the <code>service</code> method again on this
         * servlet.
         */
        public void destroy();
    }
    View Code 源码定义

    5、阐述一下阐述Servlet和CGI的区别?

      Servlet 线程处理请求,CGI 对每个请求创建进程。

    6、说说Servlet接口中有哪些方法?

    public interface Servlet {
    
        /**
         * Called by the servlet container to indicate to a servlet that the servlet
         * is being placed into service.
         *
         */
        public void init(ServletConfig config) throws ServletException;
    
        /**
         *
         * Returns a {@link ServletConfig} object, which contains initialization and
         * startup parameters for this servlet. The <code>ServletConfig</code>
         * object returned is the one passed to the <code>init</code> method.
         *
         * @return the <code>ServletConfig</code> object that initializes this
         *         servlet
         *
         * @see #init
         */
        public ServletConfig getServletConfig();
    
        /**
         * Called by the servlet container to allow the servlet to respond to a
         * request.
         *
         * <p>
         * This method is only called after the servlet's <code>init()</code> method
         * has completed successfully.
         */
        public void service(ServletRequest req, ServletResponse res)
                throws ServletException, IOException;
    
        /**
         * Returns information about the servlet, such as author, version, and
         * copyright.
         *
         */
        public String getServletInfo();
    
        /**
         * Called by the servlet container to indicate to a servlet that the servlet
         * is being taken out of service. This method is only called once all
         * threads within the servlet's <code>service</code> method have exited or
         * after a timeout period has passed. After the servlet container calls this
         * method, it will not call the <code>service</code> method again on this
         * servlet.
         */
        public void destroy();
    }
    View Code 源码定义 五个方法

    7、Servlet 3中的异步处理指的是什么?

    参考地址: https://www.cnblogs.com/davenkin/p/async-servlet.html

    异步处理调用示例:

    @WebServlet(urlPatterns = {"/async"}, asyncSupported = true)
    public class AsyncServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
     
        @Override
        public void doGet(HttpServletRequest req, HttpServletResponse resp) 
                throws ServletException, IOException {
            // 开启Tomcat异步Servlet支持
            req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
     
            final AsyncContext ctx = req.startAsync();  // 启动异步处理的上下文
            // ctx.setTimeout(30000);
            ctx.start(new Runnable() {
     
                @Override
                public void run() {
                    // 在此处添加异步处理的代码
     
                    ctx.complete();
                }
            });
        }
    }

    8、如何在基于Java的Web项目中实现文件上传和下载?

    传统方式:在Servlet中并没有提供文件上传、下载的API,因此我们一般都引入三方组件实现功能,推荐Apache的commons-fileupload,commons-io。

         具体做法是 在前端代码中将需要上传文件的表单类型设置为 enctype="multipart/form-data" ,选择文件的组件为 <input type="file" name="file1">,在Servlet中 使用 Apache 包中的组件接收文件。

    Servlet3:在Servlet3中异常简单,前端还是不变,但是接收文件的Servlet只需要加上注解 @MultipartConfig 即可,然后调用 request.getParts() 即可获取所有文件上传的组件并接收文件。

    示例参考: 

     
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
        Photo file: <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </form>
    //  @MultipartConfig 常用属性maxFileSize单个文件大小,location 文件的临时保存位置,maxRequestSize  文件上传最大请求数
    @MultipartConfig(maxFileSize=1000,location = "filePath",maxRequestSize= 2)
    @WebServlet("/uploadFile")
    public class UploadServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter out = resp.getWriter();
    
            String path = this.getServletContext().getRealPath("/savePath");
            // 可以用request.getPart()方法获得名为photo的上传附件
            // 也可以用request.getParts()获得所有上传附件(多文件上传)
            // 然后通过循环分别处理每一个上传的文件
            Part part = req.getPart("file");
    
            if (part.getSubmittedFileName() != null) {
                String fileName = part.getSubmittedFileName();
    
                part.write(path + "/" + fileName);
    
                out.write("上传文件成功");
            } else {
                out.write("上传文件失败");
            }
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doGet(req, resp);
        }
    
    }
    View Code 文件上传处理

    9、服务器收到用户提交的表单数据,到底是调用Servlet的doGet()还是doPost()方法?

      表单提交的方式是 post 方式,因此经过Servlet的service() 方法处理后,将调用doPost() 方法。

    10、Servlet中如何获取用户提交的查询参数或表单数据?

    在ServletRequest 接口中定义了若干方法接收用户的查询参数。常用的方法有:

        public String getParameter(String name);

        public Enumeration<String> getParameterNames();

        public String[] getParameterValues(String name);

        public Map<String, String[]> getParameterMap();

    11、Servlet中如何获取用户配置的初始化参数以及服务器上下文参数? 

    // 获取服务器上文的参数
    req.getServletContext().getAttribute("sttributeName");

    // 获取用户配置的参数
    req.getServletContext().getInitParameter("paramName");

    12、讲一下redis的主从复制怎么做的?

    13、redis为什么读写速率快性能好?

    14、redis为什么是单线程?

    15、缓存的优点?

    16、aof,rdb,优点,区别?

    17、redis的List能用做什么场景?

    18、说说MVC的各个部分都有那些技术来实现?如何实现?

    M:mode,数据模型层,主要负责系统分层中对数据的操作部分,基于DAO模式,我知道的有MyBatis,Hibernate。

    V:view,视图解析层,业务逻辑将数据处理完成后,需要展示给前端用户。Jsp, theamleaf

    C:controller,请求控制层,针对用户的每个业务请求,都有相应的方法或者Servlet进行处理,通过调用业务逻辑处理和数据操作,返回给用户一个展示数据的页面。SpringMVC,Struts

    此外还有具体的业务逻辑处理层,使用Spring Ioc 和 aop 处理对象之间的依赖关系和逻辑。

    19、什么是DAO模式?

    Data Access Object,主要实现了对数据持久化的操作(数据库的CRUD),DAO模式则是人们大量实践的经验总结,约定俗成,DAO组成主要有:

    Database Connection: 数据库的连接和关闭的响应操作。

    Pojo :主要是对象的属性,setter/getter方法,这样的每一个pojo对象对应了数据库中的一条记录

    Dao: 对数据库操作的接口方法定义,包括CRUD操作;

    DaoImpl: 对Dao接口定义的具体实现,粒度为每张的表的各种CRUD操作,包括批量,单个,联表操作等。但是不实现数据库的连接和关闭。

    Proxy: 代理类,负责数据库的连接和关闭。

    Factory:获取一个DAO对象完成对数据库的相应操作。

    20、请问Java Web开发的Model 1和Model 2分别指的是什么?

      参考地址: https://www.breakyizhan.com/javamianshiti/2591.html

    Model 1是以页面为中心的Java Web开发,使用JSP+JavaBean技术将页面显示逻辑和业务逻辑处理分开,JSP实现页面显示,JavaBean对象用来保存数据和实现业务逻辑。Model 2是基于MVC(模型-视图-控制器,Model-View-Controller)架构模式的开发模型,实现了模型和视图的彻底分离,利于团队开发和代码复用,如下图所示:

    21、你的项目中使用过哪些JSTL标签?

    22、使用标签库有什么好处?如何自定义JSP标签?(JSP标签)

  • 相关阅读:
    数组指针的一个易错点
    jQuery on()方法
    php 前一天或后一天的日期
    用jQuery监听浏览器窗口的变化
    jquery获取json对象中的key小技巧
    JQuery操作元素的属性与样式及位置
    用JQuery操作元素的style属性
    如何删除jsPlumb连接
    jsPlumb.jsAPI阅读笔记(官方文档翻译)
    Jquery empty() remove() detach() 方法的区别
  • 原文地址:https://www.cnblogs.com/ytuan996/p/10589697.html
Copyright © 2011-2022 走看看