<UserServlet> package com.zq.controller;
import java.io.IOException; import java.util.HashMap;
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 com.sun.javafx.collections.MappingChange.Map;
//注解:代替一些配置文件的配置 @WebServlet给前台jsp提供一个访问地址 //http://localhost:8088/MyWeb/user @WebServlet("/user") public class UserServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //业务逻辑代码 System.out.println("进来了"); //1、获取参数 //HttpServletRequest 里面有前台传来的参数 //HttpServletResponse 主要有个作用可以直接返回数据 String action = req.getParameter("action"); //null.equals //http://localhost:8088/Myweb/user? if(null!=action && action.equals("tologin")){//request跳转到某个页面 //从系统上的注销操作 req.setAttribute("msg","今天天气真好啊"); //也可以传任何对象 java.util.Map<String,String> map = new HashMap<String, String>(); map.put("name", "zq"); map.put("age", "22"); req.setAttribute("map", map); req.getRequestDispatcher("index.jsp").forward(req, resp); }
}
[@Override](https://my.oschina.net/u/1162528)
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}
<index.jsp> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>首页</title> </head> <body> <!-- 接受别人jsp传来的、servlet类传来的数据 --> <!-- 1、常用EL表达式 --> <span>${msg }</span> <span>${map.name}</span>
<!-- 2、麻烦 -->
<span><%=request.getAttribute("msg") %></span>
</body> </html>