天天看點

java 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;

@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,HttpServletResponse response) throws ServletException, IOException{

request.setAttribute("msg", "周冬雨");

request.getRequestDispatcher("/index.jsp").forward(request, response);

}

3.開發中常用的方式

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

@RequestMapping("yy")

public String yy(Model model){

model.addAttribute("msg", "雙笙");

return "forward:/index.jsp";

}

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