6-3 编程题
来源:6-3 自由编程
JakePrim
2020-01-13 17:03:37
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/request-struc/work/test" method="get"> <input type="text" name="key"> <input type="submit" value="查询"> </form> </body> </html>
请求的servlet如下: 需要注意重定向和请求转发的路径问题
@WebServlet("/work/test")
public class WorkTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private HashMap<String, String> map;
/**
* @see HttpServlet#HttpServlet()
*/
public WorkTestServlet() {
super();
map = new HashMap<String, String>();
map.put("apple", "苹果");
map.put("mac", "苹果笔记本电脑");
map.put("window", "Windows电脑");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String key = request.getParameter("key");// 获取请求参数
if (map.containsKey(key)) {
request.setAttribute("key", map.get(key));
//请求转发的方式
System.out.println(map.get(key));
request.getRequestDispatcher("/success.jsp").forward(request, response);//请求转发不需要 context-path
} else {
HttpSession session = request.getSession();
session.setAttribute("msg", "没有找到对应的单词解释");
response.sendRedirect("/request-struc/error.jsp");//注意重定向需要 context-path
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String value = (String)request.getAttribute("key"); %>
<h1 style="color: blue;"><%=value %></h1>
</body>
</html>error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% String msg = (String)session.getAttribute("msg"); %>
<h1 style="color: red;"><%=msg %></h1>
</body>
</html>1回答
同学你好,代码完成的不错,没有问题,继续努力!
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!