美文网首页
maven 项目添加spring mvc 支持

maven 项目添加spring mvc 支持

作者: wangliang0209 | 来源:发表于2016-10-14 16:32 被阅读0次
    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集成到此完毕

    相关文章

      网友评论

          本文标题:maven 项目添加spring mvc 支持

          本文链接:https://www.haomeiwen.com/subject/hbzgyttx.html