springMVC響應(yīng)數(shù)據(jù)和結(jié)果視圖

1返回值分類

1.1** 字符串

  1. Controller方法返回字符串可以指定邏輯視圖的名稱,根據(jù)視圖解析器為物理視圖的地址
@RequestMapping(value="/hello")
public String sayHello() {
    System.out.println("Hello SpringMVC!!");
    // 跳轉(zhuǎn)到XX頁面
    return "success";
}
  1. 具體的應(yīng)用場景
@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 返回String
     * @param model
     * @return
     */
    @RequestMapping("/testString")
    public String testUser(Model model){
        System.out.println("testString方法執(zhí)行中......");
        // 模擬從數(shù)據(jù)庫中查詢出User對象
        User user = new User();
        user.setUsername("嘿嘿");
        user.setPassword("123");
        user.setAge(18);
        // model對象
        model.addAttribute("user",user);
        return "success";
    }
    

succes.jsp 頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>成功</title>
</head>
<body>
    <h3>成功</h3>
${user.username}<br/>
${user.age}

</body>
</html>

1.2**返回值是void

  1. 如果控制器的方法返回值編寫成void,執(zhí)行程序報404的異常,默認查找JSP頁面沒有找到。
  2. 默認會跳轉(zhuǎn)到@RequestMapping(value="/initUpdate") initUpdate的頁面。
  3. 可以使用請求轉(zhuǎn)發(fā)或者重定向跳轉(zhuǎn)到指定的頁面
/**
 * 無返回值
 * @return
 */
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println("testVoid方法執(zhí)行了......");
    // 編寫請求轉(zhuǎn)發(fā)的程序
   // request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

    // 重定向
    //response.sendRedirect(request.getContextPath() + "/index.jsp");

    // 設(shè)置中文亂碼
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    // 直接響應(yīng)
    response.getWriter().println("hello");
    return;
}

1.3返回值是ModelAndView對象

ModelAndView對象是Spring提供的一個對象,可以用來調(diào)整具體的JSP視圖

具體的代碼如下

/**
 * 返回ModelAndView對象
 * @return
 */
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
    System.out.println("testModelAndView方法執(zhí)行中......");
    // 創(chuàng)建 ModelAndView 對象
    ModelAndView mv = new ModelAndView();

    // 模擬從數(shù)據(jù)庫中查詢出User對象
    User user = new User();
    user.setUsername("嘿嘿");
    user.setPassword("123");
    user.setAge(18);
    // 把User對象存儲到ModelAndView對象中
    mv.addObject("user",user);

    // 設(shè)置跳轉(zhuǎn)到哪個頁面
    mv.setViewName("success");
    return mv;
}

success.jsp 頁面


<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>成功</title>
</head>
<body>
    <h3>成功</h3>
${user.username}<br/>
${user.age}
</body>
</html>

2 SpringMVC框架提供的轉(zhuǎn)發(fā)和重定向

  1. forward請求轉(zhuǎn)發(fā)

  2. redirect重定向

    controller方法返回String類型,想進行請求轉(zhuǎn)發(fā)也可以編寫成

/**
 * 使用關(guān)鍵字的方式進行請求轉(zhuǎn)發(fā)和重定向
 * @return
 */
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
    System.out.println("testForwardOrRedirect方法執(zhí)行中......");

    // 請求轉(zhuǎn)發(fā)
    // return "forward:/WEB-INF/pages/success.jsp";
    //重定向
    return "redirect:/index.jsp";
}

3 ResponseBody響應(yīng)json數(shù)據(jù)

導(dǎo)入jarbao

<!--json字符串和JavaBean對象互相轉(zhuǎn)換的過程中,需要使用jackson的jar包-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
</dependency>

3.1 在 springmvc 的配置文件中可以配置,靜態(tài)資源不過濾

DispatcherServlet會攔截到所有的資源,導(dǎo)致一個問題就是靜態(tài)資源(img、css、js)也會被攔截到,從而不能被使用。解決問題就是需要配置靜態(tài)資源不進行攔截,在springmvc.xml配置文件添加如下配置

  1. mvc:resources標簽配置不過濾
  2. location元素表示webapp目錄下的包下的所有文件
  3. mapping元素表示以/static開頭的所有請求路徑,如/static/a 或者/static/a/b
<!-- 設(shè)置靜態(tài)資源不過濾 -->
<!-- location 表示路徑,mapping 表示文件,**表示該目錄下的文件以及子目錄的文件 -->
<mvc:resources location="/css/" mapping="/css/**"/> <!-- 樣式 -->
<mvc:resources location="/images/" mapping="/images/**"/> <!-- 圖片 -->
<mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->

3.2 使用@RequestBody獲取請求體數(shù)據(jù)

<script src="js/jquery.min.js"></script>
<script>
    // 頁面加載,綁定單擊事件
    $(function () {
        $("#btn").click(function () {

            // 發(fā)送Ajax請求
            $.ajax({
                type: "GET",
                url: "user/testAjax",
                contentType:"application/json; charset=UTF-8",
                data:'{"username":"哈哈","password":"123","age":"20"}',
                dataType:"json",
                type:"post",
                success:function (data) {
                    // data服務(wù)器端響應(yīng)的json數(shù)據(jù)
                    alert(data.username);
                    alert(data.password);
                    alert(data.age);
                }
            });
        });
    });
    
<button id="btn">發(fā)送Ajax請求</button><br/>
@RequestMapping("/testAjax")
public void testAjax(@RequestBody String body) {
    System.out.println(body);
}

3.3 使用@RequestBody注解把json的字符串轉(zhuǎn)換成JavaBean的對象

使用@ResponseBody注解把JavaBean對象轉(zhuǎn)換成json字符串,直接響應(yīng)

<script src="js/jquery.min.js"></script>
<script>
    // 頁面加載,綁定單擊事件
    $(function () {
        $("#btn").click(function () {

            // 發(fā)送Ajax請求
            $.ajax({
                type: "GET",
                url: "user/testAjax",
                contentType:"application/json; charset=UTF-8",
                data:'{"username":"哈哈","password":"123","age":"20"}',
                dataType:"json",
                type:"post",
                success:function (data) {
                    // data服務(wù)器端響應(yīng)的json數(shù)據(jù)
                    alert(data.username);
                    alert(data.password);
                    alert(data.age);
                }
            });
        });
    });
    
<button id="btn">發(fā)送Ajax請求</button><br/>

/**
     * Ajax異步請求響應(yīng)
     * @ResponseBody 將響應(yīng)對象轉(zhuǎn)換成json字符串
     * @return
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法執(zhí)行了......");
        // 客戶端發(fā)送ajax的請求,傳的是json字符串,后端把json字符串封裝到user對象中
        System.out.println(user);
        // 作響應(yīng),模擬查詢數(shù)據(jù)庫
        user.setUsername("呵呵");
        user.setAge(30);
        // 做響應(yīng)
        return user;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容