6-3自由编程
来源:6-3 自由编程
RobinZang
2019-09-27 17:20:21
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>请输入要查询的单词</title> </head> <body> <form action="/JspPracCode/direct/check"> <input name="word" placeholder="请输入要查询的单词"/> <input type="submit" value="查询"><br/> </form> </body> </html>
package com.imooc.servlet.driect; import java.io.IOException; import java.io.PrintWriter; 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 CheckLoginServlet */ @WebServlet("/direct/check") public class CheckLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CheckLoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf8"); response.setContentType("text/html;charset=utf-8"); // 接收请求发来的参数 String word = request.getParameter("word"); Map<String,String> fruit=new HashMap<String,String>(); fruit.put("apple", "苹果"); fruit.put("banana", "香蕉"); fruit.put("orange", "橘子"); if(fruit.containsKey(word)) { request.setAttribute("value",fruit.get(word)); request.getRequestDispatcher("/success.jsp").forward(request,response); } else { HttpSession session = request.getSession(); session.setAttribute("str", "没有找到对应的单词解释!"); response.sendRedirect("/JspPracCode/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> <% String value = (String)request.getAttribute("value"); String html = "<h1 style='color:blue'>" + value + "</h1>"; response.getWriter().println(html); %> </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 str = (String) session.getAttribute("str"); String html = "<h1 style='color:red'>" + str + "</h1>"; response.getWriter().println(html); %> </body> </html>
1回答
同学你好,复制运行贴出代码,运行效果没有问题,很棒呐,继续加油~
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~