请求和响应对象 内容和要求: (1)(考察知识点HttpServletRequest对象的应用) 完成解决请求参数的中文乱码问题任务代码的编写。 (2)(考察知识点请求转发) 请按照以下要求编写程序: 1)编写一个名称为ForwardServlet的Servlet类,在类中向request对象中增加一些信息(班级和姓名),然后使用forward()方法将请求转发到ResultServlet类中。 2)编写一个名称为ResultServlet的Servlet类,在类中获取request对象中增加的信息并输出。 3)在web.xml中添加完两个Servlet的映射后,启动服务器,使用浏览器访问ForwardServlet,查看显示结果。
时间: 2024-02-28 19:54:07 浏览: 70
完美解决Get和Post请求中文乱码的问题
5星 · 资源好评率100%
以下是代码实现:
ForwardServlet.java:
```java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ForwardServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 往 request 对象中增加信息
request.setAttribute("name", "张三");
request.setAttribute("class", "一班");
// 请求转发
request.getRequestDispatcher("/ResultServlet").forward(request, response);
}
}
```
ResultServlet.java:
```java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResultServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取 request 对象中的信息
String name = (String)request.getAttribute("name");
String className = (String)request.getAttribute("class");
// 输出信息
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>ResultServlet</title></head>");
out.println("<body>");
out.println("<h1>姓名:" + name + "</h1>");
out.println("<h1>班级:" + className + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
```
web.xml:
```xml
<web-app>
<servlet>
<servlet-name>ForwardServlet</servlet-name>
<servlet-class>ForwardServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ResultServlet</servlet-name>
<servlet-class>ResultServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ForwardServlet</servlet-name>
<url-pattern>/ForwardServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ResultServlet</servlet-name>
<url-pattern>/ResultServlet</url-pattern>
</servlet-mapping>
</web-app>
```
在浏览器中访问 ForwardServlet,即可看到输出的结果。
阅读全文