@Controller //设置整体请求路径前缀 @RequestMapping("/hello") public class HelloController { //请求方式为-->localhost/hello/save @RequestMapping("/save") @ResponseBody public String save(){ return "{'module':'springmvc'}"; } //请求方式为-->localhost/hello/save @RequestMapping("/delete") @ResponseBody public String delete(){ return "{'module':'springmvc delete'}"; } }
@Controller public class HelloController { //请求方式为-->localhost/hello/save?name=输入值&age=输入值2 @RequestMapping("/save") @ResponseBody public String save(String name,int age){ return "name = "+ name+"\n"+"age = "+ age; } }
测试结果
java程序不变,post使用请求体发送表单
post请求中文乱码的情况(在Servlet容器内设置过滤器)
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{{SpringMVCConfig.class}}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter("UTF-8"); return new Filter[]{filter}; } }
@Controller public class HelloController { //请求方式为-->localhost/hello/save?name=输入值&age=输入值2 @RequestMapping("/save") @ResponseBody //将请求参数name映射到形参username上 //请求方式为-->localhost/hello/save?name=输入值&age=输入值2 public String save(@RequestParam("name")String username,int age){ return "name = "+ name+"\n"+"age = "+ age; } }
@Controller public class HelloController { //请求方式为-->localhost/hello/save?name=输入值&age=输入值2 @RequestMapping("/user") @ResponseBody //实体类:根据构造函数的形参名自动填充 public String save(User user){ System.out.println(user); return user.toString();; } }
public class User { private String username; private int age ; private Address address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", age=" + age + ", address=" + address + '}'; } }
public class Address { private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } @Override public String toString() { return "Address{" + "location='" + location + '\'' + '}'; } }
结果
@Controller public class HelloController { @RequestMapping("/array") @ResponseBody public String user(String[] hobby){ System.out.println(Arrays.toString(hobby)); return Arrays.toString(hobby); } }