1、dictionary.jsp跳转至DictionaryServlet
@WebServlet("/dictionary")
public class DictionaryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> map = new HashMap<>(10);
map.put("苹果","apple");
map.put("香蕉","banana");
map.put("桃子","peach");
String word= request.getParameter("word");
if(map.containsKey(word)){
request.setAttribute("answer",map.get(word));
request.getRequestDispatcher("/success.jsp").forward(request,response);
}else{
HttpSession session = request.getSession();
session.setAttribute("answer","没有找到对应的单词解释");
//重定向的路径设置与转发不同 不是/fail.jsp
response.sendRedirect("fail.jsp");
}
}
}
2、success.jsp
//或者使用EL表达式
${requestScope.get(“answer”)}或
${requestScope.answer}
<html>
<head>
<title>$Title$</title>
</head>
<body>
//或者使用EL表达式
${requestScope.get("answer")}
<%
//内置request、out对象
String answer = request.getAttribute("answer").toString();
out.println(answer);
%>
</body>
</html>
3、 fail.jsp( //重定向的路径设置与转发不同 不是/fail.jsp)
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%
//内置request、out
out.println(request.getSession().getAttribute("answer").toString());
%>
</body>
</html>
附注:
EL:1、${} 不需要<%%>
2、使用toString方法
3、作用域page、request、session、context
4、内置param.参数名(即getParamater)