Spring MVC Controller 要點

今天看到一篇講解 Spring MVC Controller 的文章,比較詳細,順道翻譯下。java

在 Spring MVC 中,咱們寫一個 Controller 類來處理客戶端的請求。在 Controller 中處理相關的業務流程與業務邏輯而且經過 Spring 的 dispatcher servlet 返回對應的結果輸出。這就是一個典型的 request response 週期。 ##1.使用 @Controller 註解web

建立一個 Controller 類。在這個 Controller 來處理多個不一樣的提交.示例: import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;spring

@Controller
public class HomeController {
 
    @RequestMapping("/")
    public String visitHome() {
 
        // do something before returning view name
 
        return "home";
    }
}

當應用訪問路徑爲根目錄(/)時 進入這個方法apache

注意: 在Spring的配置文件中加入以下配置:api

<annotation-driven />

也能夠設置上 Controller 的掃描路徑瀏覽器

<context:component-scan base-package="net.codejava.spring" />

使用 @Controller 註解,你能夠提交多個表單到這個類中處理這些不一樣請求:spring-mvc

@Controller
public class MultiActionController {
 
    @RequestMapping("/listUsers")
    public ModelAndView listUsers() {
 
    }
 
    @RequestMapping("/saveUser")
    public ModelAndView saveUser(User user) {
 
    }
 
    @RequestMapping("/deleteUser")
    public ModelAndView deleteUser(User user) {
 
    }
}

你的提交路徑能夠爲 /listUsers, /saveUser 和 /deleteUser緩存

##2.實現 Controller 接口mvc

另外一個建立 Controller 的方法就是實現 Controller 接口,示例:app

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class MainController implements Controller {
 
    @Override
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("Welcome main");
        return new ModelAndView("main");
    }
}

實現這個接口必須重寫 handleRequest() 這個方法。這樣才能被 spring 的 dispatcher servlet 捕獲。當一個方法進來,request 的 Url 須要匹配以下的 Spring 配置:

<bean name="/main" class="net.codejava.spring.MainController" />

這種方法的缺點就是沒法處理多個不一樣的提交請求。

##3.Extending the AbstractController Class

能夠簡單的處理 Http 請求方法類型(GET/POST),管理頁面的緩存設置,便是否容許瀏覽器緩存當前頁面;管理執行流程在會話(Session)上的同步。實例: import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
 
public class BigController extends AbstractController {
 
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        System.out.println("You're big!");
        return new ModelAndView("big");
    }
}

Spring 中的配置:

<bean name="/big" class="net.codejava.spring.BigController">
    <property name="supportedMethods" value="POST"/>
</bean>

##4. 經過 URL 映射處理提交。

這個就是咱們常常用到的了。

@RequestMapping("/login")

當請求Url 匹配以上的路徑 login 就會進入到這個 Controller 中。示例:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class UserController {
 
    @RequestMapping("/listUsers")
    public String listUsers() {
        return "ListUsers";
    }
 
    @RequestMapping("/saveUser")
    public String saveUser() {
        return "EditUser";
    }
 
    @RequestMapping("/deleteUser")
    public String deleteUser() {
        return "DeleteUser";
    }
}

@RequestMapping 這個註解也能夠設置多個相同的操做的url 提交到同一個方法中 ,示例:

@RequestMapping({"/hello", "/hi", "/greetings"})

##5 指定http請求方式

經過 @RequestMapping 註解的參數,指定方法處理指定的http請求。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class LoginController {
 
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String viewLogin() {
        return "LoginForm";
    }
 
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin() {
        return "Home";
    }
}

能夠看到,以上的url相同,指定的提交方式不一樣,會經過提交方式進入不一樣的方法。

##6.請求參數的映射處理:

能夠經過 @RequestParam 來接收表單參數提交併處理示例:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String doLogin(@RequestParam String username,
                      @RequestParam String password) {
 
}

會 binds 提交的 username 以及 password 參數。get的url 會是這個樣子:

http://localhost:8080/spring/login?username=scott&password=tiger

下面是幾個常見數據處理示例:

@RequestParam int securityNumber//自動轉化爲int型
@RequestParam("SSN") int securityNumber//提交的參數與定義不一樣
@RequestParam(required = false) String country//非必須的接收參數
@RequestParam(defaultValue = "18") int age//設置參數默認值
doLogin(@RequestParam Map<String, String> params)//將提交全部信息放如map中

//使用HttpServletRequest 和 HttpServletResponse
@RequestMapping("/download")
public String doDownloadFile(
        HttpServletRequest request, HttpServletResponse response) {
 
    // access the request
 
    // access the response
 
    return "DownloadPage";
}

##7.返回 Model 以及 View

將數據處理封裝以後返回視圖層。

//返回登陸頁面:loginForm
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewLogin() {
    return "LoginForm";
}

//封裝數據返回視圖層
@RequestMapping("/listUsers")
public ModelAndView listUsers() {
 
    List<User> listUser = new ArrayList<>();
    // get user list from DAO...
 
    ModelAndView modelView = new ModelAndView("UserList");
    modelView.addObject("listUser", listUser);
 
    return modelView;
}

//將數據裝入model 返回視圖層
@RequestMapping(method = RequestMethod.GET)
public String viewStats(Map<String, Object> model) {
    model.put("siteName", "CodeJava.net");
    model.put("pageviews", 320000);
 
    return "Stats";
}


//重定向到一個頁面
// check login status....
if (!isLogin) {
    return new ModelAndView("redirect:/login");
}
// return a list of Users

##8.驗證表單提交。 Spring 能夠簡單的綁定數據到 一個 bean 中並經行校驗。示例:

@Controller
public class RegistrationController {
 
    @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
    public String doRegister(
        @ModelAttribute("userForm") User user, BindingResult bindingResult) {
 
        if (bindingResult.hasErrors()) {
            // form validation error
 
        } else {
            // form input is OK
        }
 
        // process registration...
 
        return "Success";
    }
}

這裏給出一篇問下 詳細說明了 BindingResult 的處理 Spring MVC Form Validation Example with Bean Validation API

##9.處理上傳表單: Spring 使用 Apache Commons FileUpload 做爲上傳的處理。示例:

@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public String handleFileUpload(
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
 
 
    for (CommonsMultipartFile aFile : fileUpload){
 
        // stores the uploaded file
        aFile.transferTo(new File(aFile.getOriginalFilename()));
 
    }
 
 
    return "Success";
}
相關文章
相關標籤/搜索