常规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