天天看點

怎樣使用SpringMVC控制頁面

為什麼要使用springMVC?

很多應用程式的問題在于處理業務資料和顯示業務資料的視圖的對象之間存在緊密耦合。通常,更新業務對象的指令都是從視圖本身發起的,使視圖對任何業務對象更改都有高度敏感性。而且,當多個視圖依賴于同一個業務對象時是沒有靈活性的。

Spring Web MVC是一種基于Java的實作了Web MVC設計模式的請求驅動類型的輕量級Web架構,即使用了MVC架構模式的思想,将web層進行職責解耦,基于請求驅動指的就是使用請求-響應模型,架構的目的就是幫助我們簡化開發,Spring Web MVC也是要簡化我們日常Web開發的。

springMVC優勢

1、清晰的角色劃分:前端控制器(DispatcherServlet)、請求到處理器映射(HandlerMapping)、處理器擴充卡(HandlerAdapter)、視圖解析器(ViewResolver)、處理器或頁面控制器(Controller)、驗證器( Validator)、指令對象(Command  請求參數綁定到的對象就叫指令對象)、表單對象(Form Object 提供給表單展示和送出到的對象就叫表單對象)。

2、分工明确,而且擴充點相當靈活,可以很容易擴充,雖然幾乎不需要;

3、由于指令對象就是一個POJO,無需繼承架構特定API,可以使用指令對象直接作為業務對象;

4、和Spring 其他架構無縫內建,是其它Web架構所不具備的;

5、可适配,通過HandlerAdapter可以支援任意的類作為處理器;

6、可定制性,HandlerMapping、ViewResolver等能夠非常簡單的定制;

7、功能強大的資料驗證、格式化、綁定機制;

8、利用Spring提供的Mock對象能夠非常簡單的進行Web層單元測試;

9、本地化、主題的解析的支援,使我們更容易進行國際化和主題的切換。

10、強大的JSP标簽庫,使JSP編寫更容易。

………………還有比如RESTful風格的支援、簡單的檔案上傳、約定大于配置的契約式程式設計支援、基于注解的零配置支援等等。

架構圖

怎樣使用SpringMVC控制頁面
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <filter>
      <filter-name>characterFilter</filter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
      <filter-name>characterFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 加載springMVC的配置檔案 -->
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
  </servlet>
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>      

使用xml檔案配置

classpath下的springmvc.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
      
      <!-- 配置映射處理器  BeanNameUrlHandlerMapping  預設-->
      <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
      <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
          <property name="mappings">
              <props>
                  <prop key="/index.do">helloController</prop>
                  <prop key="/qwe.do">helloController</prop>
              </props>
          </property>
      </bean>
      
      <bean id="helloController" name="/hello.do" class="cn.bdqn.controller.HelloController"></bean>
      <!-- 配置處理器擴充卡  預設-->
      <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
      <!-- 視圖解析器 InternalResourceViewResolver -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!-- 字首 -->
              <property name="prefix" value="/jsp/"></property>
              <!-- 字尾 -->
              <property name="suffix" value=".jsp"></property>
      </bean>
</beans>      
 cn.bdqn.controller.HelloController.java
package cn.bdqn.controller;

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 HelloController implements Controller{
    //傳回一個視圖
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("mesg", "教育改變生活"); // application.setAtr...
        mv.setViewName("hello");
        return mv;
    }
}      
hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <div>${mesg }</div>
</body>
</html>      

使用注解配置

 classpath下的spring-mvc.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
      <context:component-scan base-package="cn.bdqn"></context:component-scan>
      <!-- 注解一鍵配置 -->
      <mvc:annotation-driven></mvc:annotation-driven>
      
      <!-- 視圖解析器 InternalResourceViewResolver -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!-- 字首 -->
              <property name="prefix" value="/jsp/"></property>
              <!-- 字尾 -->
              <property name="suffix" value=".jsp"></property>
      </bean>
</beans>      
cn.bdqn.pojo.User
package cn.bdqn.pojo;

public class User {
    private Integer age;  //年齡
    private String uname;  //姓名
    private String location;  //地區
    private String sex;  //性别
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "User [age=" + age + ", uname=" + uname + ", location="
                + location + ", sex=" + sex + "]";
    }
    
    
}      
form檔案夾下的form1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/form/rePojo.do" method="post">
        姓名:<input name="uname"/><br/>
        年齡:<input name="age" /><Br/>
        位址:<select name="location">
                <option>北京</option>
                <option>合肥</option>
             </select><br/>
        性别:<input type="radio" name="sex" value="男"/>男
        <input type="radio" name="sex" value="女"/>女<br/>
        <input type="submit" value="送出"/>
    </form>
</body>
</html>      
cn.bdqn.controller.FormController.java
package cn.bdqn.controller;

import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bdqn.pojo.User;

@Controller
@Scope("prototype")
@RequestMapping("/form")
public class FormController {
    @RequestMapping(value="/rePojo.do")
    public String rePojo(User user,Model model){ //從頁面擷取user參數 , 添加Model參數
        model.addAttribute(user);  //使用此方法将參數傳入頁面
        System.out.println(user);
        return "index";  //發送到index.jsp頁面      
}  
}      
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    姓名----${user.uname}<br/>
    年齡----${user.age}<br/>
    地區----${user.location}<br/>
    性别----${user.sex}<br/>
</body>
</html>      

轉載于:https://www.cnblogs.com/wxbblogs/p/7263734.html