maven 项目添加spring mvc 支持

1.先打开pom.xml文件

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


 UTF-8
 4.1.5.RELEASE

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

  
     
       org.springframework  
       spring-webmvc  
       ${spring.version}  
     
     
     
       org.springframework  
       spring-jdbc  
       ${spring.version}  
     
     
     
       org.springframework  
       spring-context  
       ${spring.version}  
     
     
     
       org.springframework  
       spring-aop  
       ${spring.version}  
     
     
     
       org.springframework  
       spring-core  
       ${spring.version}  
     
     
     
       org.springframework  
       spring-test  
       ${spring.version}  
     
    
2.修改web.xml文件
  
  
  Archetype Created Web Application  
    
      
    
    
    dispatcher  
    org.springframework.web.servlet.DispatcherServlet  
    1  
    
    
    
    dispatcher  
    /  
    
  
      
      
        encodingFilter  
        org.springframework.web.filter.CharacterEncodingFilter  
          
            encoding  
            UTF-8  
          
          
            forceEncoding  
            true  
          
      
      
        encodingFilter  
        /*  
      
    
    
  
3.在WEB-INF下添加dipatcher-servlet.xml

  
    
    
      
          
              
          
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
          
          
          
          
          
      
      
 
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 users = new ArrayList();
        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 {
     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");  
       
     private final List availableCharsets;  
    
     private boolean writeAcceptCharset = true;  
    
     public UTF8StringHttpMessageConverter() {  
         super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);  
         this.availableCharsets = new ArrayList(Charset.availableCharsets().values());  
     }  
    
     /** 
      * Indicates whether the {@code Accept-Charset} should be written to any outgoing request. 
      * 

    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}. * *

    By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses. * * @return the list of accepted charsets */ protected List 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中添加(参考上边代码)
   ```
     
         
             
         
   
   ```

#####6.到此spring mvc集成到此完毕

你可能感兴趣的:(maven 项目添加spring mvc 支持)