3.SpringMVC響應

package com.gzcgxt.erp;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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("/hello")
/**
 * 
 * <p>Title: HelloController</p>
 * <p>Description: springMVC響應處理</p>
 * <p>Company: www.baidu.com</p> 
 * @author    劉詩華 微信:15390725037
 * @date    2019-7-16下午3:12:27
 * @version 1.0
 */
public class HelloController {
    
    /**
     * 1.經過Http對象
     * <p>Title: index</p>
     * <p>Description: </p>
     * @return
     */
    public void httpBean(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, Exception {
        request.setAttribute("name", "劉詩華");
        
        //請求轉發
        request.getRequestDispatcher("/test").forward(request, response);
        
        //請求重定向
        response.sendRedirect("/test");
    }
    
    /**
     * 2.經過 ModelAndView來返回響應
     * <p>Title: index</p>
     * <p>Description: </p>
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView index()
    {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("name","劉詩華");
        return mv;
    }
    
    /**
     * 3.返回String字符串,這裏要藉助 Model model這個接口來綁定數據響應
     * <p>Title: getString</p>
     * <p>Description: </p>
     * @return
     */
    @RequestMapping("/getString")
    public String getString(Model m)
    {
        m.addAttribute("name","劉詩華");
        //存放一個String類型的數據
        //則在前臺顯示 ${string} 數據類型小寫
        m.addAttribute("Hello My name is lsh");
        return "getString";
    }
  
  //第四種 返回json對象

     @RequestMapping("/index")
     @ResponseBodyjava

   public User getUser()   {    return new User(100,"lsh","123456");  }
}
相關文章
相關標籤/搜索