首頁 > 軟體

SSM框架的註解&組態檔的優劣取捨

2020-06-16 17:03:13

常規SSM範例

探索SSM理論的前提,應該是在對框架基礎的運作方式有一定了解,以下是個人Android後台專案,用SSM框架快速搭建,以下是程式碼,主要 觀察結構

程式碼結構:

  • model實體類
  • Idao抽象介面
  • Iservice抽象介面
  • daomapping資料庫具體操作的組態檔
  • service服務類
  • controller控制器類

Article.java

package com.linuxidc.model;

import java.util.Date;

public class Article {
    private Integer id;

    private String title;

    private String author;

    private Date date;

    private Integer zan;

    private Integer pinglun;

    private Integer fenxiang;

    private String tag1;

    private String tag2;

    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author == null ? null : author.trim();
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Integer getZan() {
        return zan;
    }

    public void setZan(Integer zan) {
        this.zan = zan;
    }

    public Integer getPinglun() {
        return pinglun;
    }

    public void setPinglun(Integer pinglun) {
        this.pinglun = pinglun;
    }

    public Integer getFenxiang() {
        return fenxiang;
    }

    public void setFenxiang(Integer fenxiang) {
        this.fenxiang = fenxiang;
    }

    public String getTag1() {
        return tag1;
    }

    public void setTag1(String tag1) {
        this.tag1 = tag1 == null ? null : tag1.trim();
    }

    public String getTag2() {
        return tag2;
    }

    public void setTag2(String tag2) {
        this.tag2 = tag2 == null ? null : tag2.trim();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }
}

ArticleMapper.java

package com.linuxidc.dao;

import java.util.List;

import com.linuxidc.model.Article;

public interface ArticleMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Article record);

    int insertSelective(Article record);

    Article selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Article record);

    int updateByPrimaryKeyWithBLOBs(Article record);

    int updateByPrimaryKey(Article record);

    List<Article> getAll();

    List<Article> getTitleList(String tag);
}


ArticleMapping.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.linuxidc.dao.ArticleMapper" >
  <resultMap id="BaseResultMap" type="com.linuxidc.model.Article" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="author" property="author" jdbcType="VARCHAR" />
    <result column="date" property="date" jdbcType="TIMESTAMP" />
    <result column="zan" property="zan" jdbcType="INTEGER" />
    <result column="pinglun" property="pinglun" jdbcType="INTEGER" />
    <result column="fenxiang" property="fenxiang" jdbcType="INTEGER" />
    <result column="tag1" property="tag1" jdbcType="VARCHAR" />
    <result column="tag2" property="tag2" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.linuxidc.model.Article" extends="BaseResultMap" >
    <result column="content" property="content" jdbcType="LONGVARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, title, author, date, zan, pinglun, fenxiang, tag1, tag2
  </sql>
  <sql id="Blob_Column_List" >
    content
  </sql>
  
   <select id="getAll" resultMap="BaseResultMap">
  select * from article_t order by date desc 
  </select>
  
   <select id="getTitleList" resultMap="BaseResultMap" parameterType="java.lang.String" >
   select * from article_t where tag1= #{tag,jdbcType=VARCHAR} or tag2= #{tag,jdbcType=VARCHAR}
  </select>

  
  <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from article_t
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from article_t
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.linuxidc.model.Article" >
    insert into article_t (id, title, author, 
      date, zan, pinglun, 
      fenxiang, tag1, tag2, 
      content)
    values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{author,jdbcType=VARCHAR}, 
      #{date,jdbcType=TIMESTAMP}, #{zan,jdbcType=INTEGER}, #{pinglun,jdbcType=INTEGER}, 
      #{fenxiang,jdbcType=INTEGER}, #{tag1,jdbcType=VARCHAR}, #{tag2,jdbcType=VARCHAR}, 
      #{content,jdbcType=LONGVARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.linuxidc.model.Article" >
    insert into article_t
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="title != null" >
        title,
      </if>
      <if test="author != null" >
        author,
      </if>
      <if test="date != null" >
        date,
      </if>
      <if test="zan != null" >
        zan,
      </if>
      <if test="pinglun != null" >
        pinglun,
      </if>
      <if test="fenxiang != null" >
        fenxiang,
      </if>
      <if test="tag1 != null" >
        tag1,
      </if>
      <if test="tag2 != null" >
        tag2,
      </if>
      <if test="content != null" >
        content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="title != null" >
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="author != null" >
        #{author,jdbcType=VARCHAR},
      </if>
      <if test="date != null" >
        #{date,jdbcType=TIMESTAMP},
      </if>
      <if test="zan != null" >
        #{zan,jdbcType=INTEGER},
      </if>
      <if test="pinglun != null" >
        #{pinglun,jdbcType=INTEGER},
      </if>
      <if test="fenxiang != null" >
        #{fenxiang,jdbcType=INTEGER},
      </if>
      <if test="tag1 != null" >
        #{tag1,jdbcType=VARCHAR},
      </if>
      <if test="tag2 != null" >
        #{tag2,jdbcType=VARCHAR},
      </if>
      <if test="content != null" >
        #{content,jdbcType=LONGVARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.linuxidc.model.Article" >
    update article_t
    <set >
      <if test="title != null" >
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="author != null" >
        author = #{author,jdbcType=VARCHAR},
      </if>
      <if test="date != null" >
        date = #{date,jdbcType=TIMESTAMP},
      </if>
      <if test="zan != null" >
        zan = #{zan,jdbcType=INTEGER},
      </if>
      <if test="pinglun != null" >
        pinglun = #{pinglun,jdbcType=INTEGER},
      </if>
      <if test="fenxiang != null" >
        fenxiang = #{fenxiang,jdbcType=INTEGER},
      </if>
      <if test="tag1 != null" >
        tag1 = #{tag1,jdbcType=VARCHAR},
      </if>
      <if test="tag2 != null" >
        tag2 = #{tag2,jdbcType=VARCHAR},
      </if>
      <if test="content != null" >
        content = #{content,jdbcType=LONGVARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.linuxidc.model.Article" >
    update article_t
    set title = #{title,jdbcType=VARCHAR},
      author = #{author,jdbcType=VARCHAR},
      date = #{date,jdbcType=TIMESTAMP},
      zan = #{zan,jdbcType=INTEGER},
      pinglun = #{pinglun,jdbcType=INTEGER},
      fenxiang = #{fenxiang,jdbcType=INTEGER},
      tag1 = #{tag1,jdbcType=VARCHAR},
      tag2 = #{tag2,jdbcType=VARCHAR},
      content = #{content,jdbcType=LONGVARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.linuxidc.model.Article" >
    update article_t
    set title = #{title,jdbcType=VARCHAR},
      author = #{author,jdbcType=VARCHAR},
      date = #{date,jdbcType=TIMESTAMP},
      zan = #{zan,jdbcType=INTEGER},
      pinglun = #{pinglun,jdbcType=INTEGER},
      fenxiang = #{fenxiang,jdbcType=INTEGER},
      tag1 = #{tag1,jdbcType=VARCHAR},
      tag2 = #{tag2,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

ArticleController.java

package com.linuxidc.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

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

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.linuxidc.model.Article;
import com.linuxidc.model.News;
import com.linuxidc.model.NewsCom;
import com.linuxidc.model.User;
import com.linuxidc.service.IArticleService;
import com.linuxidc.service.INewsComService;
import com.linuxidc.service.INewsService;
import com.linuxidc.service.IUserService;
import net.sf.json.JSONObject;

/**
 * @author linuxidcBaby
 * 鍒ゆ柇鎵嬫満鍙鋒槸鍚﹀凡緇忚娉ㄥ唽
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    
    @RequestMapping("/getAllArticle")
    public String getAll(HttpServletRequest request,Model model){
        List<Article> article = this.articleService.getAll();
        model.addAttribute("news", JSON.toJSONStringWithDateFormat(article,"yyyy-MM-dd HH:mm"));
        return "showNews";
    }
    
    @RequestMapping("/getTitleList")
    public String getTitleList(HttpServletRequest request,Model model){
        String tag= request.getParameter("tag");
        List<Article> article = this.articleService.getTitleList(tag);
        model.addAttribute("news", JSON.toJSONStringWithDateFormat(article,"yyyy-MM-dd HH:mm"));
        return "showNews";
    }
    
}

IArticleService.java

package com.linuxidc.service;

import java.util.List;

import com.linuxidc.model.Article;
import com.linuxidc.model.News;

public interface IArticleService {

    public List<Article> getAll();

    public List<Article> getTitleList(String tag);
}

ArticleService.java

package com.linuxidc.serviceImpl;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import com.linuxidc.dao.ArticleMapper;
import com.linuxidc.dao.NewsMapper;
import com.linuxidc.model.Article;
import com.linuxidc.model.News;
import com.linuxidc.service.IArticleService;
import com.linuxidc.service.INewsService;

@Service("articleService")  
public class ArticleServiceImpl implements IArticleService{
    @Resource
    private ArticleMapper articleMapper;

    @Override
    public List<Article> getAll() {
        return this.articleMapper.getAll();
        
    }

    @Override
    public List<Article> getTitleList(String tag) {
        // TODO Auto-generated method stub
        return this.articleMapper.getTitleList(tag);
    }
    
}

Junit測試類(不算在結構內,實際應該是頁面存取controller)

package com.linuxidc.test;

import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.linuxidc.model.News;
import com.linuxidc.service.INewsService;

@RunWith(SpringJUnit4ClassRunner.class)//琛ㄧず緇ф壙浜哠pringJUnit4ClassRunner綾?
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})

public class Test{
    private static Logger logger = Logger.getLogger(TestMyBatis.class);
    
    @Resource
    private INewsService newsService = null;
    
    @Test
    public void test1() {
        
        List<News> newsList = newsService.getAllNews();
        // System.out.println(user.getUserName());
        // logger.info("鍊鹼細"+user.getUserName());
        logger.info(JSON.toJSONStringWithDateFormat(newsList,"MM-dd:HH:mm:ss"));
    }
}




四個組態檔

  • jdbc組態檔
  • log4j組態檔
  • Spring與SpringMvc整合的組態檔
  • Spring與mybatis整合的組態檔


jdbc.properties

db-driver=com.mysql.jdbc.Driver
db-url=jdbc:mysql://localhost:3306/appdb?useUnicode=yes&characterEncoding=UTF8
db-username=root
db-password=root


log4j.properties

log4j.rootLogger=INFO,Console,File

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out

log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB

log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n

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:p="http://www.springframework.org/schema/p"
    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-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="com.linuxidc.controller" />
    <!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />   <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>
    <!-- 定義跳轉的檔案的前字尾 ,檢視模式設定-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的設定我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- 組態檔上傳,如果沒有使用檔案上傳可以不用設定,當然如果不配,那麼組態檔中也不必引入上傳元件包 -->
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 預設編碼 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 檔案大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />  
        <!-- 記憶體中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
    </bean> 

</beans>

spring-mybaits.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:p="http://www.springframework.org/schema/p"
    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-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.linuxidc" />
    <!-- 引入組態檔 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <!-- 資料來源  使用阿里Druid資料來源  也可以用其它資料來源 -->  
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
        <property name="driverClassName" value="${db-driver}" />  
        <property name="url" value="${db-url}" />  
        <property name="username" value="${db-username}" />  
        <property name="password" value="${db-password}" />  
        <property name="maxActive" value="20" />    
        <property name="initialSize" value="1" />    
        <property name="maxWait" value="60000" />    
        <property name="minIdle" value="1" />    
    
        <property name="timeBetweenEvictionRunsMillis" value="3000" />    
        <property name="minEvictableIdleTimeMillis" value="300000" />    
    
        <property name="validationQuery" value="SELECT 'x' FROM DUAL" />    
        <property name="testWhileIdle" value="true" />    
        <property name="testOnBorrow" value="false" />    
        <property name="testOnReturn" value="false" />    
        <!-- mysql 不支援 poolPreparedStatements-->    
        <property name="poolPreparedStatements" value="true" />  
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />    
    
        <!-- 開啟Druid的監控統計功能 -->    
        <property name="filters" value="stat" />    
    </bean>  

    <!-- spring和MyBatis完美整合,不需要mybatis的設定對映檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath:com/linuxidc/mapping/*.xml"></property>
    </bean>

    <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.linuxidc.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    

</beans>

整體來說Spring+SpringMVC+Mybatis的開發模式是非常適合快速搭建專案的,甚至比簡單的Servlet來得快多了。

  • 省去了與資料庫互動的書寫
  • 各層程式碼也是直接生成的,可參考 Mybatis/SSM程式碼生成教學

接下去只記錄其他一些情況,和常見疑問,以及spring相關理論的實際含義。




applicationContext.xml和註解的優劣取捨

講xml之前,首先得梳理下歷史遺留問題:IOC是什麼,幹嘛用的?

簡言回答之:IOC的意思是控制反轉,落實到具體就是使用.xml進行設定。
好處在於:

  • 資源集中管理,實現資源的可設定和易管理。
  • 降低了使用資源雙方的依賴程度,也就是我們說的耦合度。

再通俗點說:

  • 第一點,全部的類都可以在組態檔中進行裝配,一個類可能有多種裝配好的範例(嚴格說不叫範例,叫範例的詳細設定),好處:這些範例可以被不斷參照,而不需要再去new,建構函式,set屬性等等操作。還有就是類的程式碼少了,清晰簡潔,只需要專注對一個組態檔進行修改
  • 第二點,各個類之間的相互參照操作少了,耦合降低了,比如我喜歡吃水果,今天吃蘋果,於是我在1000個類的eat函數中書寫了Fruit fruit= new Apple();結果我明天要吃橘子,原先的做法是開啟1000個檔案,將那句程式碼改成Fruit fruit = new Orange(); 累還不說,你電腦記憶體夠麼?IDE不崩潰嗎?有了IOC,只需要在.xml檔案中設定<bean id="fruit" class="……/Orange">

隨著歷史的發展,由於各種局限性,舊事物總是被新事物所取代(人越來越懶)上面這種方式缺點也很明顯,書寫一個bean太長了!所以就出現了註解@Resource,只需在屬性宣告上面寫上,這樣一個bean,就被注入了,但是!這樣和直接new區別大嗎?不大!當然,也失去了那2個好處。所以對於實體類,註解用處不明顯

現在,你可能回想:前者情況下組態檔好用,後者情況下註解好用,那我該選哪個?可不可以既當婊子又立牌坊?答案是可以的,就是混合使用註解和組態檔,但是!註解必須放到第二層及之後才能用,第一層必須宣告檔案路徑:

ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
FruitBox fruitBox = ac.getBean("fruitBox");//此時,fruitBox跟orange,apple只是從屬關係,而不是繼承關係了

Box內水果屬性註解格式:

//這種做法其實本末倒置,因為註解就是為了解決組態檔書寫問題的
@Autowired
@Qualifier("fruit")//.xml中要設定一個bean,類是Orange或Apple
private Fruit fruit;//照樣需要一個水果父類別統一接收,不寫預設類名

正確做法
@Autowired
private Orange fruit;

所以第一層並不能享受到注解的便利。當然,舉這個吃水果例子是不恰當的,因為水果實際並沒有附屬於任何東西,強行加一層外殼,最終增加的是內層幾條註解的工作量,新增及參照外殼bean的操作量並沒有減少!如果是 學生的課本 會比較合適。
也就是說對於@resource或@autowired,註解本身的便利是犧牲了靈活性的,同理,想要靈活性必須犧牲便利。所以需要特殊設定的bean用註解不合適!註解適用於new一個簡單的範例,再無其他。
但是,對於controller和service,註解的好處就體現出來了,原本需要分別繼承controller抽象類和service抽象類,重寫各種函數,現在只需要加上@controller和@service,spring就能認出來這兩種類,不再需要重寫任何函數,省事的同時程式碼也清爽了。

Controller的多種返回型別

  • ModelAndView
  • Model
  • ModelMap
  • Map
  • View
  • String
  • void

ModelAndView

@RequestMapping("/article")
    public ModelAndView getView() { 
        String message = "view";
        return new ModelAndView("view", "message", message);//指定返回的頁面名稱,也可以通過setViewName()方法指定
    }

Map

@RequestMapping("/demo2/show") 
    public Map<String, String> getMap() { 
        Map<String, String> map = new HashMap<String, String>(); 
        map.put("key1", "value-1"); 
        map.put("key2", "value-2"); //在jsp頁面中可直通過${key1}獲得到值, map.put()相當於request.setAttribute方法。

        return map; 
    } 

String
指定返回的檢視頁面名稱。如果方法還宣告了註解@ResponseBody ,則會直接將返回值輸出到頁面

@RequestMapping("/getAllArticle")
public String getAll(HttpServletRequest request,Model model){
        List<Article> article = this.articleService.getAll();
        model.addAttribute("news", JSON.toJSONStringWithDateFormat(article,"yyyy-MM-dd HH:mm"));//引數可在jsp頁面獲得
        return "showNews";//返回showNews.jsp
    }

json

@RequestMapping("/getAllArticle")
public String getAll(){
        List<Article> article = this.articleService.getAll();
        return JSON.toJSONStringWithDateFormat(article,"yyyy-MM-dd HH:mm"));
        }
    }

void
如果返回值為空,則響應的檢視頁面對應為存取地址

@RequestMapping("/index")
    public void index() {
        return; //對應的邏輯檢視名為"index"
    }




Controller中url的幾種風格

RequestMapping()

普通的url

這種是最簡單的url對映,可以接收到localhost:8080/contextName/hello這樣的請求

@RequestMapping("/hello")
    public @ResponseBody String test() {
        return "hello!";
    }

多個普通的url路徑
RequestMapping可以同時指定多個url,對映到同一個應答邏輯中:

@RequestMapping(value={"/multi1","/multi2","/test/multi"})
    public @ResponseBody String multiUrl() {
        return "test multi url";
}

基於路徑變數的URL對映
這種URL對映可以直接在路徑上指定變數,通過@PathVariable可以獲得物件。

//基本的URL模板對映
@RequestMapping(value="/user1/{name}")
public @ResponseBody String basicUrl1(@PathVariable String name){
    return "hello"+name;
}
@RequestMapping(value="/user2/{name}/test")
public @ResponseBody String basicUrl2(@PathVariable String name){
    return "hello"+name+"test";
}
@RequestMapping(value="/user1/{name}/test/{age}")
public @ResponseBody String basicUrl3(@PathVariable String name,@PathVariable int age){
    return "hello"+name+" age"+age;
}

本文永久更新連結地址http://www.linuxidc.com/Linux/2017-11/148246.htm


IT145.com E-mail:sddin#qq.com