首页 > 编程语言 > 详细

SpringMVC 接受前端传递的数据

时间:2020-07-09 22:15:36      阅读:80      评论:0      收藏:0      [点我收藏+]

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 的测试需要注意

(1)需要在修改SpringContext.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    
    <context:component-scan base-package="controller" />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

修改之后的文件为

<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    
    <context:component-scan base-package="controller" />
    
    <mvc:annotation-driven />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

  

参考:https://www.cnblogs.com/mjs154/p/11667796.html

SpringMVC 接受前端传递的数据

原文:https://www.cnblogs.com/wylwyl/p/13276516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!