龙空技术网

Servlet总结十四:转发与重定向

小瓜瓜666 1482

前言:

目前各位老铁们对“servlet转发到其它web”都比较注重,看官们都想要了解一些“servlet转发到其它web”的相关知识。那么小编也在网上收集了一些有关“servlet转发到其它web””的相关文章,希望同学们能喜欢,兄弟们快快来了解一下吧!

1、跳转的方式

转发: forward

重定向: redirect

2、转发和重定向代码怎么完成

1、转发//请求转发到/b对应的Servletrequest.getRequestDispatcher("/b").forward(request,response);2、重定向response.sendRedirect(request.getContextPath() + "/b");

3、转发和重定向的区别?

相同点:都可以完成资源的跳转

不同点:

转发是request对象触发的,服务器内部进行转发

重定向是response对象触发的,要将重定向的路径相应给浏览器

转发是一次请求,浏览器地址栏上地址不变

重定向是两次请求,浏览器地址栏上的地址发生变化

重定向路径需要加项目名(webapp跟路径web目录)

转发是在本项目内部完成资源的跳转

重定向可以完成跨app跳转,例如可以跳转到

4、什么时候采用转发,什么时候采用重定向

1、大部分情况下都使用重定向

2、若想完成跨app跳转,必须采用重定向

若在上一个资源中向request范围中存储了数据,希望在下一个资源中从request范围中取出,必须使用转发

3、重定向可以解决浏览器的刷新问题

5、重定向解决页面刷新问题

public class Save extends HttpServlet {    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {        //解决中文乱码        request.setCharacterEncoding("UTF-8");        //获取表单数据        String usercode = request.getParameter("usercode");        String username = request.getParameter("username");        Connection conn = null;        PreparedStatement ps = null;        int row = 0;        try {            Class.forName("com.mysql.jdbc.Driver");            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaee", "root", "admin");            conn.setAutoCommit(false);            ps = conn.prepareStatement("insert into t_user(usercode,username) value(?,?)");            ps.setString(1,usercode);            ps.setString(2,username);            row = ps.executeUpdate();            conn.commit();        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (SQLException throwables) {            //如果发生异常,如果conn!=null,回滚数据            if(conn != null) {                try {                    conn.rollback();                } catch (SQLException e) {                    e.printStackTrace();                }            }            throwables.printStackTrace();        } finally {            //省略关闭        }        if(row ==1) {            //执行成功,跳转到成功页面            //1. 转发            //浏览器只进行一次请求,如果此时浏览器进行刷新,浏览器刷新的是最后一次请求,即提交表单的请求,            //此时多次刷新浏览器,那么就会请求多次,就会执行多次Servlet,            //就会多次连接数据库插入数据,导致数据重复插入            //request.getRequestDispatcher("/success.html").forward(request,response);            //2. 重定向            //服务器返回重定向的地址(success.html),浏览器就会请求新的地址,            //一共有两次请求:提交表单的请求和重定向的请求            //此时如果浏览器多次刷新,那么请求的也是重定向的success.html静态页面,            //不会因为刷新而导致多次提交表单            response.sendRedirect(request.getContextPath() + "/success.html");        }    }}

标签: #servlet转发到其它web