springmvc后端响应给前端

controller
package com.bh.controller;

import com.bh.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

@Controller
public class ShowController {
    /*
    * 方式1:原始方式
    * */
  /*  @RequestMapping("/show1.do")
    public String show1(HttpServletRequest request, HttpServletResponse response){
        String username="tom";
        String password="123";
        request.setAttribute("userName",username);
        request.setAttribute("pwd",password);
        return "/result1.jsp";
    }*/

    /*
    * 方式2: 使用ModelMap
     *
    * */
/*    @RequestMapping("/show2.do")
    public String show2(ModelMap mod){
        mod.put("userName","tom1");
        mod.put("pwd","4444");

        return "result1.jsp";
    }*/


    /*
    * 方式3:使用ModelAndView
    * */

    /*@RequestMapping("/show3.do")
    public ModelAndView show3(){
        HashMap<String,String> rstMap = new HashMap<>();
        rstMap.put("userName","jerry");
        rstMap.put("pwd","45612");
        ModelAndView mv = new ModelAndView("result1.jsp", rstMap);
        return mv;
    }*/



    /*
    *
     * 方式4: 使用@ModelAttribute
 注意: 只要有@ModelAttribute注解的话,
 那么这个Contgroller里面所有的url的方法都会先执行
这个加了注解的方法
    * */

    @RequestMapping("/show4.do")
    public String show4(){
        System.out.println("start========");
        System.out.println("end=============");

        return "/result1.jsp";
    }

    @ModelAttribute(value = "u1")
    public User getUser(){
        User u1 = new User();
        u1.setUsername("tom");
        u1.setPassword("123456a?");

        return u1;
    }
}

User
package com.bh.po;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

result1.jsp
<%@ page import="com.bh.po.User" %><%--
  Created by IntelliJ IDEA.
  User: liangkuan
  Date: 2023/6/5
  Time: 19:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
username:<%=request.getAttribute("userName")%><br>
password:<%=request.getAttribute("pwd")%><br>

<%--方式四--%>
<p><%=((User)request.getAttribute("u1")).getUsername()%></p>
<p><%=((User)request.getAttribute("u1")).getPassword()%></p>
</body>
</html>

posted @ 2023-06-07 14:46  liangkuan  阅读(40)  评论(0)    收藏  举报