1. 程式人生 > 程式設計 >SpringMVC框架實現Handler處理器的三種寫法

SpringMVC框架實現Handler處理器的三種寫法

一、SpringMVC中的處理器

配置完SpringMVC的處理器對映器,處理介面卡,檢視解析器後,需要手動寫處理器。關於處理器的寫法有三種,無論怎麼寫,執行流程都是①處理對映器通過@Controller註解找到處理器,繼而②通過@RequestMapping註解找到使用者輸入的url。下面分別介紹這三種方式。

package com.gql.springmvc;
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;
/**
 * 類說明:
 * 處理器的三種寫法
 * @guoqianliang1998.
 */
@Controller
public class UserController {
 //1.SpringMVC開發方式
 @RequestMapping("/hello")
 public ModelAndView hello(){
 ModelAndView mv = new ModelAndView();
 mv.addObject("msg","hello world!");
 mv.setViewName("index.jsp");
 return mv;
 }
 
 //2.原生Servlet開發方式
 @RequestMapping("xx")
 public void xx(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
 request.setAttribute("msg","周冬雨");
 request.getRequestDispatcher("/index.jsp").forward(request,response);
 }
 
 //3.開發中常用
 @RequestMapping("yy")
 public String yy(Model model){
 model.addAttribute("msg","雙笙");
 return "forward:/index.jsp";//forward寫不寫都是轉發,redirect代表重定向.
 }
}

1.SpringMVC開發方式

 @RequestMapping("/hello")
 public ModelAndView hello(){
 ModelAndView mv = new ModelAndView();
 mv.addObject("msg","hello world!");
 mv.setViewName("index.jsp");
 return mv;
 }

2.Servlet原生開發方式

 @RequestMapping("xx")
 public void xx(HttpServletRequest request,response);
 }
 

3.開發中常用的方式

在return的字串中,forward寫不寫都是代表轉發,redirect則代表重定向。

 @RequestMapping("yy")
 public String yy(Model model){
 model.addAttribute("msg","雙笙");
 return "forward:/index.jsp";
 }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。