获取参数

1. 无注解下获取参数

无注解下,要求参数名与HTTP请求的参数名一致

@Controller
public class MyController {
    @RequestMapping("/hello")
    @ResponseBody
    public Object sayHello(String name,Integer age,String str){
        Map<String,Integer> map=new HashMap<>();
        map.put(name,age);
        sout(str);
        return map;
    }

请求URL:http://localhost:8080/hello?name=LiHua&age=20即可返回,由于str默认为空,因此没传入也可以

2. 用@RequestParam获取

若传入参数与URL中不同,如http://localhost:8080/hello?minzi=LiHua&nianling=20

@Controller
public class MyController {
    @RequestMapping("/hello")
    @ResponseBody
    public Object sayHello(
        @RequestParam("minzi") String name,
        @RequestParam("nianling") Integer age,
        @RequestParam(value="s",required=false) String str){}
}

注意str参数中加了required=false,允许没传入,否则会报错

3. 获取JSON

通过@RequestBody接收前端传入的JSON参数

@Controller
public class MyController {
    @RequestMapping("/hello")
    @ResponseBody
    public Object sayHello(@RequestBody User user){}
}

若返回JSON,使用 @ResponseBody

4. 通过URL传递

如果URL为RestFul风格,如http://localhost:8080/user/#id/#age,可使用@PathVariable

@Controller
public class MyController {
    @GetMapping("/user/{name}/{age}")
    @ResponseBody
    public Object sayHello(@PathVariable("name") String name, @PathVariable("age") Integer age){
        Map<String,Integer> map=new HashMap<>();
        map.put(name,age);
        return map;
    }
}

image-20210716151702500

5. 传递格式化参数

通过DateTimeFormatNumberFormat进行转换

先在jsp中设置时间和金额,用于传递

<body>
    <form action="${pageContext.request.contextPath}/commit/" method="post">
        <table>
            <tr>
                <td>请输入日期(yyyy-MM-dd)</td>
                <td>
                        <input type="text" name="date" value="2021-07-16" />
                </td>
            </tr>
            <tr>
                <td>请输入金额(#,###.##)</td>
                <td>
                        <input type="text" name="number" value="12,345.678"/>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="right">
                    <input type="submit" value="提交">
                </td>
            </tr>
        </table>

    </form>
</body>

Controller中对传递的参数进行格式化接收:

@Controller
public class MyController {
    @GetMapping("/user/")
    public Object sayHello(){
        return "hello";
    }
    @PostMapping("/commit/")
    @ResponseBody
    public Object format(
            @DateTimeFormat(iso= DateTimeFormat.ISO.DATE) Date date,
            @NumberFormat(pattern = "#,###.###") Double number)throws ParseException {
        Map<String,Object> map=new HashMap<>();
        map.put("date",date);
        map.put("number",number);
        return map;
    }
}

image-20210716161613450

提交后结果:{“date”:1626393600000,“number”:12345.678}

**注意:**通过post传入中文时,会发生乱码,在web.xml中加入

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceRequestEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>forceResponseEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

返回参数

1. 返回 ModelAndView

一般如果不是前后端分离,通常会返回ModelAndView

@Controller
@RequestMapping("/user")
public class HelloController {
    @RequestMapping("/hello")
    public ModelAndView hello() {
        //视图名,通过视图解析器定位到视图
        ModelAndView mv = new ModelAndView("hello");
        //往视图中添加属性
        mv.addObject("username", "javaboy");
        return mv;
    }
}

2. 通过Servlet API

确保pom文件中添加了Servlet依赖

//服务端跳转
@RequestMapping("/hello2")
public void hello2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setAttribute("msg","hello");
    req.getRequestDispatcher("/jsp/hello.jsp").forward(req,resp);//服务器端跳转
}
//重定向
@RequestMapping("/hello3")
public void hello3(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.sendRedirect("/hello.jsp");
}
//返回字符串或JSON
@RequestMapping("/hello4")
public void hello4(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    out.write("hello javaboy!");
    out.flush();
    out.close();
}

3. 通过Spring MVC

//返回视图名
@RequestMapping("/hello5")
public String hello5(Model model) {
    model.addAttribute("username", "javaboy");//这是数据模型
    return "hello";//表示去查找一个名为 hello 的视图
}
//服务端跳转
@RequestMapping("/hello5")
public String hello5() {
    return "forward:/jsp/hello.jsp";
}
//重定向
@RequestMapping("/hello5")
public String hello5() {
    return "redirect:/user/hello";
}

注意:用@ResponseBody返回中文字符串时,可能会乱码,在produces中加上utf-8即可

@RequestMapping(value = "/hello5",produces = "text/html;charset=utf-8")
@ResponseBody
public String hello5() {
    return "Java 语言程序设计";
}