• SpringMVC 接受前端传递的数据


    1、新建User.java

    package pojo;
    
    public class User {
    	private String name;
    	private String pwd;
    	private String sex;
    	
    	public String getName() {
    		return name;
    	}
    	
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    	public String getPwd() {
    		return pwd;
    	}
    	
    	public void setPwd(String pwd) {
    		this.pwd = pwd;
    	}
    
    	public String getSex() {
    		return sex;
    	}
    
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    	
    	
    }
    

    2、TestParamController.java文件

    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import pojo.User;
    
    @Controller
    @RequestMapping("/param")
    public class TestParamController {
    	
    	
    	/**
    	 * produces 设置返回参数的编码格式 可以设置返回数据的类型以及编码,可以是json或者xml
    	 *  @ResponseBody 将java对象转为json格式的数据
    	 */
    	
    	private static Logger logger = LogManager.getLogger(TestParamController.class.getName());
    	
    	/**
    	 * 普通方式,请求的参数名和Controller方法的参数一致
    	 * @param name
    	 * @param pwd
    	 * @return
    	 */
    	@RequestMapping(value = "/add", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUser(String name, String pwd) {
    		logger.debug("name:" + name + ",pwd:"+pwd);
    		return "name:" + name + ",pwd:" + pwd;
    	}
    	
    	/**
    	 * 对象方式,请求的参数名和Controller方法中的对象的参数一致
    	 * @param user
    	 * @return
    	 */
    	@RequestMapping(value = "/addByObject", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUserByObject(User user) {
    		logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
    		return "name:" + user.getName() + ",pwd:" + user.getPwd();
    	}
    	
    	/**
    	 * 自定义方法参数名-当请求参数名与方法参数名不一致时
    	 * @param u_name
    	 * @param u_pwd
    	 * @return
    	 */
    	@RequestMapping(value = "/addByDifName", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUserByDifName(@RequestParam("name") String u_name, @RequestParam("pwd")String u_pwd){
    	    logger.debug("name:" + u_name + ",pwd:" + u_pwd);
    	    return "name:" + u_name + ",pwd:" + u_pwd;
    	}
    	
    	/**
    	 * 通过HttpServletRequest接收
    	 * @param request
    	 * @return
    	 */
    	@RequestMapping(value = "/addByHttpServletRequest", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUserByHttpServletRequest(HttpServletRequest request){
    	    String name = request.getParameter("name");
    	    String pwd = request.getParameter("pwd");
    	    logger.debug("name:" + name + ",pwd:" + pwd);
    	    return "name:" + name + ",pwd:" + pwd;
    	}
    	
    	/**
    	 *@PathVariable获取路径中的参数接收
    	 * @param name
    	 * @param pwd
    	 * @return
    	 */
    	@RequestMapping(value = "/add/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUserByPathVariable(@PathVariable String name, @PathVariable String pwd){
    	    logger.debug("name:" + name + ",pwd:" + pwd);
    	    return "name:" + name + ",pwd:" + pwd;
    	}
    	
    	/**
    	 * @RequestBody-JSON方式接收
    	 * @param user
    	 * @return
    	 */
    	@RequestMapping(value = "/addByObjectJSON", produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUserByObjectJSON(@RequestBody User user){
    	    logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
    	    return "name:" + user.getName() + ",pwd:" + user.getPwd();
    	}
    	
    	/**
    	 * RequestBody-JSON List对象方式
    	 * @param users
    	 * @return
    	 */
    	@RequestMapping(value = "/addByListJSON", produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUsersByListJSON(@RequestBody List<User> users){
    	    StringBuilder sb = new StringBuilder("{");
    	    if(null != users){
    	        for(User user : users){
    	            sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
    	        }
    	    }
    	    sb.append("}");
    	    logger.debug(sb.toString());
    	    return sb.toString();
    	}
    	
    	
    	/**
    	 * RequestBody-JSON Map对象方式
    	 * @param users
    	 * @return
    	 */
    	@RequestMapping(value = "/addByMapJSON", produces = {"application/json;charset=UTF-8"})
    	@ResponseBody
    	public String addUsersByMapJSON(@RequestBody Map<String, User> users){
    
    	    StringBuilder sb = new StringBuilder("{");
    
    	    if(null != users){
    	        Iterator it = users.keySet().iterator();
    	        while(it.hasNext()){
    	            User user = users.get(it.next());
    	            sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
    	        }
    
    	    }
    	    sb.append("}");
    	    logger.debug(sb.toString());
    	    return sb.toString();
    	}
    	
    	
    	
    	
    }
    

    3、pom.xml文件

    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
        
      <display-name>Archetype Created Web Application</display-name>
      
      <servlet>
          <servlet-name>dispatcher</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <init-param>
                 <param-name>contextConfigLocation</param-name>
              <param-value>classpath:springContext.xml</param-value>
          </init-param>
          <load-on-startup>1</load-on-startup>
      </servlet>
      
      <servlet-mapping>
          <servlet-name>dispatcher</servlet-name>
          <url-pattern>/</url-pattern>
      </servlet-mapping>
      
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springContext.xml</param-value>
      </context-param>
      
      <context-param>
        <param-name>log4jConfiguration</param-name>
        <param-value>classpath:log4j2.xml</param-value>
    </context-param>
      
      <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      
    </web-app>
    

    4、依次使用postman进行测试

    5、另外这里对 http://localhost:8080/SpringReceive/param/addByObjectJSON.action 的测试需要注意,我在实验的过程中出现了415错误,找了许多解决,最终下面的方法解决

    (1)需要在修改pom.xml

    <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.6</version>
            </dependency>
     
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.9.6</version>
            </dependency>
     
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.9.6</version>
            </dependency>
    

    (2)修改SpringContext.xml文件,加入

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <!-- 设置返回字符串编码 -->
                    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                        <property name = "supportedMediaTypes">
                            <list>
                                <value>text/html;charset=UTF-8</value>
                                <value>application/json;charset=UTF-8</value>
                            </list>
                        </property>
                    </bean>
                    <!-- json转换器 -->
                    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                        <property name="supportedMediaTypes">
                            <list>
                                <value>text/html;charset=UTF-8</value>
                                <value>application/json;charset=UTF-8</value>
                            </list>
                        </property>
                    </bean>
                </list>
            </property>
        </bean>
    

    (3)解决

    参考:

    前端向后端传递数据:https://www.cnblogs.com/mjs154/p/11667796.html

    415错误解决:https://blog.csdn.net/weixin_39841589/article/details/82056337

  • 相关阅读:
    oracle之 关闭透明大页
    Mac下使用sublime Text打开隐藏目录
    win下gosublime配置ctag
    Qless 相关知识
    Redis 的 Lua 脚本支持
    HTTP TCP UDP Socket 关系的几个经典图
    golang rpc 简单范例
    golang fatal error: all goroutines are asleep
    JSON 解析的可抛弃
    golang label breaks
  • 原文地址:https://www.cnblogs.com/wylwyl/p/13276516.html
Copyright © 2020-2023  润新知