以下为4种返回数据的方式,听说第三种最为常用。
控制器:
package com.lin.controller;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class ReturnDataServlet {
//参数返回第一种方式 HttpServletRequest
@RequestMapping("/add1.do")
public String add1(HttpServletRequest req){
String username = req.getParameter("username");//这段代码传回的username中文乱码,但是加上ModelView就不会了
String password = req.getParameter("password");
String str = username + "----" + password;
System.out.println(str);
req.setAttribute("up", str);
return "index";
}
//参数返回第二种方式ModelAndView
@RequestMapping("/add2.do")
public ModelAndView add2(){
ModelAndView mav = new ModelAndView("index");
mav.addObject("username", "老哥");
mav.addObject("password", "稳");
return mav;
}
//参数返回第三种方式Model
@RequestMapping("/add3.do")
public String add3(Model model){
model.addAttribute("username", "老铁");
model.addAttribute("password", "稳");
return "index";
}
//参数返回第四种方式 Map
@RequestMapping("/add4.do")
public String add4(Integer password,Map map){
System.out.println(map.get("password"));
map.put("username", "老司机");
map.put("password", "稳");
return "index";
}
}
前端index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="user/add1.do">
username:<input type="text" name="username"/><br>
password:<input type="text" name="password"/><br>
<input type="submit" value="方式一"/>
</form>
<h3>${up }</h3>
<hr>
<form action="user/add2.do">
<input type="submit" value="方式二"/>
</form>
<hr>
<form action="user/add3.do">
<input type="submit" value="方式三"/>
</form>
<hr>
<form action="user/add4.do">
<input type="submit" value="方式四"/>
</form>
<h3>${username }---${password }</h3>
<hr>
</body>
</html>
其他的配置和过滤器与前面的是一样。