6-3自由编程
来源:6-3 自由编程
慕粉4119499
2019-07-14 12:01:43
想问一下,最后这个是怎么完成的
如果返回值为false,将结果” 没有找到对应的单词解释”存储到session中,重定向到fail.jsp进行显示。
参考了其他的人的答案都是用的转发
package com.imooc.inquiry;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class inquiry
*/
@WebServlet("/inquiry")
public class inquiry extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public inquiry() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map map = new HashMap();
map.put("apple", "苹果");
map.put("apple1", "苹果1");
map.put("apple2", "苹果2");
String name = request.getParameter("danci");
if(map.containsKey(name)) {
request.setAttribute("name", map.get(name));
request.getRequestDispatcher("/success.jsp").forward(request,response);
}else {
HttpSession se = request.getSession();
se.setAttribute("name", "没有找到对应的单词解释");
request.getRequestDispatcher("/fail.jsp").forward(request, response);
}
}
}<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>
<%out.println(request.getAttribute("name")); %>
</h1>
</body>
</html><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%out.println(session.getAttribute("name")); %>
</body>
</html><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/myjsp/inquiry"> <input type="text" name = "danci" placeholder="请输入要查询的单词"> <input type="submit" value="提交"> </form> </body> </html>
1回答
同学将最后的转发改为重定向的方式返回页面就可以呢

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~