6-3 自由编程
来源:6-3 自由编程
慕田峪209283
2020-02-16 11:33:51
package com.imooc.user.hash;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
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 HashServlet
*/
@WebServlet("/hash/check")
public class HashServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HashServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HashMap<String,String> map = new HashMap<String,String>();
map.put("apple", "苹果");
map.put("banana", "香蕉");
map.put("orange", "橙");
String skey = request.getParameter("skey");
boolean flag = map.containsKey(skey);
if(flag) {
String value = map.get(skey);
request.setAttribute("value", value);
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else {
HttpSession session = request.getSession();
session.setAttribute("error", "没有找到对应的单词解释!");
response.setContentType("text/html;charset=utf-8");
response.sendRedirect("/user_advance/fail.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>
<form action="/user_advance/hash/check">
<input type="text" name="skey" placeholder="请输入要查询的单词"/>
<input type="submit" value="查询"/>
</form>
</body>
</html>
<%@ 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("value");
out.println("<h1 style=color:blue>" + value+ "</h1>");
%>
</body>
</html>
<%@ 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 error =(String) session.getAttribute("error");
out.println("<h1 style=color:red>" + error + "</h1>");
%>
</body>
</html>
1回答
好帮手慕珊
2020-02-16
同学,你好!程序运行效果正确,符合作业要求,完成得非常好!建议代码中添加适当的注释,便于后期维护。继续加油!祝学习愉快!