Servlet重定向

Servlet重定向/转发

就一行代码

resp.sendRedirect("/response/image");
//也可以跳转去jsp文件
resp.sendRedirect("/response/success.jsp");


不过要注意添加项目名,不然默认会跳转到localhost:8080/image

url栏搜索red,重定向效果图

可以看到url发生改变,跳转到了image类

提交form表单,使用转发效果图

//转发
req.getRequestDispatcher("/success.jsp").forward(req,resp);

当前内容是success.jsp的内容克url栏显示的还是login页

表单提交测试
  • 先在pom.xml中导入jsp包
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.3</version>
    <scope>provided</scope>
</dependency>

  • 在jsp文件新建表单
pageContext.request.contextPath//这里代表当前项目路径
<form action="${pageContext.request.contextPath}/login" method="get">
    用户名: <input type="text"name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit">
</form>
  • 去Request类中重写doGet方法和doPost方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("收到请求");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
}

sout是为了测试是否获取的请求

刚开始又遇到服务器输出乱码问题,检查jdk版本没问题

然后去虚拟机选项那添加

-Dfile.encoding=utf-8

就正常显示了

posted on 2023-01-06 23:12  lsyorha  阅读(25)  评论(0编辑  收藏  举报