maven 项目添加spring mvc 支持

1.先打开pom.xml文件

在project根标签下添加如下标签

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <spring.version>4.1.5.RELEASE</spring.version>
</properties>

再在dependencies标签下添加如下标签

<!-- spring begin -->  
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-webmvc</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
     
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-jdbc</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
     
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-context</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
     
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-aop</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
     
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-core</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
     
   <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-test</artifactId>  
       <version>${spring.version}</version>  
   </dependency>  
   <!-- spring end --> 
2.修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xmlns="http://java.sun.com/xml/ns/javaee"   
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   
        version="3.0">  
  <display-name>Archetype Created Web Application</display-name>  
    
      
  <!-- spring MVC的核心就是DispatcherServlet,使用springMVC的第一步就是将下面的servlet放入web.xml  
        servlet-name属性非常重要,默认情况下,DispatchServlet会加载这个名字-servlet.xml的文件,如下,就会加载  
        dispather-servlet.xml,也是在WEN-INF目录下。  
   -->  
  <servlet>  
    <servlet-name>dispatcher</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  
  <!-- 设置dispatchservlet的匹配模式,通过把dispatchservlet映射到/,默认servlet会处理所有的请求,包括静态资源 -->  
  <servlet-mapping>  
    <servlet-name>dispatcher</servlet-name>  
    <url-pattern>/</url-pattern>  
  </servlet-mapping>  
  
    <!-- 字符集过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</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>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    
    
</web-app>  
3.在WEB-INF下添加dipatcher-servlet.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:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans.xsd  
            http://www.springframework.org/schema/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context.xsd"  
    default-lazy-init="true">  
    
    <!-- 注意下边的代码是为了解决返回中文乱码的问题的 -->
    <mvc:annotation-driven>  
        <mvc:message-converters>  
            <bean class="com.wl.web.util.UTF8StringHttpMessageConverter" />  
        </mvc:message-converters>  
    </mvc:annotation-driven>  
      
    <!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 -->  
    <!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 -->  
    <mvc:resources location="/*.html" mapping="/**.html" />  
    <mvc:resources location="/css/*" mapping="/css/**" />  
    <mvc:resources location="/js/*" mapping="/js/**" />  
    <mvc:resources location="/images/*" mapping="/images/**" />  
      
    <!-- 添加注解驱动 -->  
    <mvc:annotation-driven />  
    <!-- 默认扫描的包路径 -->  
    <context:component-scan base-package="com.wl.web" />  
      
    <!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View -->  
    <!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp -->  
    <mvc:view-controller path="/" view-name="index" />  
    <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">  
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>  
        <!-- 配置jsp路径前缀 -->  
        <property name="prefix" value="/"></property>  
        <!-- 配置URl后缀 -->  
        <property name="suffix" value=".jsp"></property>  
    </bean>  
      
</beans> 
4.在com.wl.web目录下创建控制器(注意这个包可以是你自己创建的)Controller代码样例如下
/**
 * 用户信息控制类
 * @author wangliang
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
    //produces = {"application/json;charset=UTF-8"}
    @RequestMapping(value="/detail", method=RequestMethod.GET)
    private @ResponseBody String getUserByUid(@RequestParam(value="uid") String uid) {
        
        if(uid == null || "".equals(uid)){
            return ResponseUtils.generFailedJsonStr(1, "uid 不能为空");
        } else {
            UserInfo info = new UserInfo();
            info.setUid(uid);
            info.setName("用户" + uid);
            info.setAge(new Random().nextInt(40));
            
            String resp = ResponseUtils.generSuccJsonStr(JSONObject.parseObject(JSON.toJSONString(info)));
            System.out.println(resp);
            return resp;
        }
    }
    
    @RequestMapping(value="/list", method=RequestMethod.GET)
    private @ResponseBody String getUserList() {
        List<UserInfo> users = new ArrayList<UserInfo>();
        for (int i = 0; i < 10; i++) {
            UserInfo info = new UserInfo();
            
            info.setUid(String.valueOf(i + 1));
            info.setName("用户" + (i + 1));
            info.setAge(new Random().nextInt(40));
            users.add(info);
        }
        
        JSONObject data = new JSONObject();
        data.put("list", JSONArray.parse(JSON.toJSONString(users)));
        
        String resp = ResponseUtils.generSuccJsonStr(data);
        System.out.println(resp);
        return resp;
    }
    
    
}
5.访问如下

http://localhost:8080/demo/user/list
http://localhost:8080/demo/user/detail?uid=1

6.遇到的坑
  • 坑1 @RequestMapping(value="/detail", method=RequestMethod.GET)把value="/detail" 写成name="/detail" 导致报错,主要是对API有些忘记了,是我个人的问题
  • 坑2 返回值乱码问题
    这里有两种解决方案
    • 1.@RequestMapping(value="/detail",method=RequestMethod.GET, "application/json;charset=UTF-8")
    • 2.重写AbstractHttpMessageConverter方法
    public class UTF8StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");  
       
     private final List<Charset> availableCharsets;  
    
     private boolean writeAcceptCharset = true;  
    
     public UTF8StringHttpMessageConverter() {  
         super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);  
         this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());  
     }  
    
     /** 
      * Indicates whether the {@code Accept-Charset} should be written to any outgoing request. 
      * <p>Default is {@code true}. 
      */  
     public void setWriteAcceptCharset(boolean writeAcceptCharset) {  
         this.writeAcceptCharset = writeAcceptCharset;  
     }  
    
     @Override  
     public boolean supports(Class<?> clazz) {  
         return String.class.equals(clazz);  
     }  
    
     @Override  
     protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {  
         Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());  
         return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));  
     }  
    
     @Override  
     protected Long getContentLength(String s, MediaType contentType) {  
         Charset charset = getContentTypeCharset(contentType);  
         try {  
             return (long) s.getBytes(charset.name()).length;  
         }  
         catch (UnsupportedEncodingException ex) {  
             // should not occur  
             throw new InternalError(ex.getMessage());  
         }  
     }  
    
     @Override  
     protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {  
         if (writeAcceptCharset) {  
             outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());  
         }  
         Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());  
         FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));  
     }  
    
     /** 
      * Return the list of supported {@link Charset}. 
      * 
      * <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses. 
      * 
      * @return the list of accepted charsets 
      */  
     protected List<Charset> getAcceptedCharsets() {  
         return this.availableCharsets;  
     }  
    
     private Charset getContentTypeCharset(MediaType contentType) {  
         if (contentType != null && contentType.getCharSet() != null) {  
             return contentType.getCharSet();  
         }  
         else {  
             return DEFAULT_CHARSET;  
         }  
     }  
    

}


   然后在dispatcher-servlet.xml中添加(参考上边代码)
   ```
   <mvc:annotation-driven>  
       <mvc:message-converters>  
           <bean class="com.wl.web.util.UTF8StringHttpMessageConverter" />  
       </mvc:message-converters>  
   </mvc:annotation-driven>
   ```

#####6.到此spring mvc集成到此完毕
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容