先在springmvc-servlet.xml文件作如下配置(注解開發controller)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- scan the package and the sub package --> <context:component-scan base-package="com.eco.controllor"/> <!-- configure the InternalResourceViewResolver視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!-- 前綴 --> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 后綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
然后來看看,在有無視圖解析器的情況下,轉發和重定向的實現
@Controller//定義這是一個控制器 public class CController { @RequestMapping("/hello1")//瀏覽器訪問路徑 public ModelAndView hello1() { ModelAndView mv = new ModelAndView(); mv.addObject("msg", "world");//msg可以用el表達式在下面的頁面寫出來 mv.setViewName("01.jsp");//沒有視圖解析器到根目錄的jsp //mv.setViewName("hello");//有視圖解析器到web-inf下的jsp return mv; } @RequestMapping("/hello2") public String hello2() { return "hello";//轉發:使用視圖解析器就轉到web-inf下的jsp //return "redirect:hello1";//重定向:視圖解析器到hello1,然后hello1轉到web-inf下的hi.jsp //return "hello.jsp";//轉發:不使用視圖解析器轉到根目錄下的jsp //return "forward:01.jsp";//轉發:不使用視圖解析器根目錄下的jsp //return "redirect:01.jsp";//重定向:不使用視圖解析器根目錄下的jsp } @RequestMapping("/hello3") public void hello3(HttpServletRequest req,HttpServletResponse resp) throws Exception{
req.setAttribute("a", "就是我");//a可以用el表達式在下面的頁面寫出來
req.getRequestDispatcher("01.jsp").forward(req, resp);//請求轉發到根目錄下的jsp--不需要視圖解析器
//resp.sendRedirect("01.jsp");//請求重定向到根目錄下的jsp--不需要視圖解析器 } }
看完頁面跳轉,下面再來看看數據的處理(表單)
@RequestMapping("/hello4") //http://localhost:8080/webmvc/hello4?name=eco public String hello4(String name){ System.out.println(name); return "hello"; } @RequestMapping("/hello5") //http://localhost:8080/webmvc/hello5?name=eco&pwd=112313 //User類的成員變量和域名稱一樣 public String hello5(User user){ System.out.println(user); return "hello"; } @RequestMapping("/hello6") //http://localhost:8080/webmvc/hello6?name=eco public String hello6(String name,Model model){ model.addAttribute("username", name);//這個username可以在下面的jsp頁面用el表達式寫出來 System.out.println(name); return "hello"; }