转载

SpringMVC入门学习---数据的处理

#HelloController.java
@RequestMapping("/hello")
public String hello(String name) {
	System.out.println(name);
	return "index.jsp";
}
复制代码

注:我们不需要配置视图解析器

我们在浏览器输入 http://localhost:8080/02springweb_annotation/hello.do?name=asd ,在控制台上我们会看到输出了 asd

b)提交的参数名和处理方法的参数名不一致

那么当我们在提交的参数名和处理方法的参数名不一样的时候,怎么解决。

#HelloController.java
@RequestMapping("/hello")
public String hello(@RequestParam("uname")String name) {
	System.out.println(name);
	return "index.jsp";
}
复制代码

c)提交一个对象

创建一个实体类User

#User.java
package com.xgc.entity;

public class User {
	private String name;
	private int id;
	private String pwd;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", id=" + id + ", pwd=" + pwd + "]";
	}
}
复制代码

HelloController.java

@RequestMapping("/user")
public String user(User user) {
	System.out.println(user);
	return "index.jsp";
}
复制代码

当我们输入 http://localhost:8080/02springweb_annotation/user.do?name=zxc&pwd=123 的时候,在控制台上会输出 User [name=zxc, id=0, pwd=123]

2.将数据显示到UI层

a)ModelAndView--需要视图解析器

public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
	ModelAndView mv=new ModelAndView();
	mv.addObject("msg","hello springmvc");
	mv.setViewName("hello");
	return mv;
}
复制代码
原文  https://juejin.im/post/5cd59bd1f265da03a54c3979
正文到此结束
Loading...