Spring实战11——SpringMVC模型

1.Entity:学生类

public class Student {
	private String id;
	private String name;
	private int age;
	
	public Student() {
		super();
	}

	public Student(String id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	//getter and setter
}

2.service层,业务逻辑处理

接口与实现类

public interface StudentService {
	public List<Student> getStudents(int page, int count);//获取学生列表
}
@Service
public class StudentServiceImpl implements StudentService {

	@Override
	public List<Student> getStudents(int page, int count) {
		List<Student> list = new ArrayList<Student>();
		for(int i = (page-1)*count+1; i <= count*page; i++) {
			list.add(new Student(i + "", i + "", (int)(new Random().nextInt(25))));
		}
		
		return list;
	}

}

3.控制层,与模型

@Controller
public class StudentController {
    @Autowired
	private StudentService studentService;//自动注入
	
	@RequestMapping(value = "/students1", method = RequestMethod.GET)
	public String students(Model model) {

		/**
		 * model 实际上是一个Map,它会传递给视图,这样数据就能渲染到客户端。
		 * model.addAttribute(studentService.getStudents(1, 20))。
		 * 当调用addAttribute 方法并且不指定key 的时候,那么 key 会根据值的对象类型推断确定。
		 * 本例中因为是List<Student>,因此,键会推断为studentList。
		 */
		model.addAttribute("studentList", studentService.getStudents(1, 20));//添加到模型
		return "students";//返回视图名,添加前后缀
	}
	
	@RequestMapping(value = "/students2", method = RequestMethod.GET)
	public String students(HashMap<String, List<Student>> map) {

		map.put("student", studentService.getStudents(1, 20));//添加到模型
		return "students";//返回视图名
	}
	
	@RequestMapping(value = "/students", method = RequestMethod.GET)
	public List<Student> students() {
		/**
		 * 并没返回视图名称,也没显式地设定模型,而是返回Student 列表。
		 * 当处理器方法返回对象或集合时,这个值会放到模型中,模型的key 会根据其类型推断出,即List<Student> 的key 是studentList。
		 * 视图解析器解析mapping后加上前后缀,默认返回与mapping路径相同的jsp,即直接添加.jsp。
		 */
		return studentService.getStudents(1, 20);
	}
	
}

4.jsp页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page pageEncoding="UTF-8" isELIgnored ="false"%>
<html>
<head>
    <title>Title</title>

</head>
<body>
	<c:if test="${studentList != null}">
		<div>学生列表:</div>
	    <c:forEach items="${studentList }" var="stu">
	    	<li id="stu_<c:out value="stu.id" />">
	    		<div class="stuMessage">
	    			id:<c:out value="${stu.id }"></c:out>
	    		</div>
	    		<div>
	    			name:<span class="stuName"><c:out value="${stu.name }"></c:out></span>
	    		</div>
	    			age:<span class="stuAge"><c:out value="${stu.age }"></c:out></span>
	    	</li>
	    </c:forEach>
    </c:if>
    
</body>
</html>

猜你喜欢

转载自blog.csdn.net/pigqhf/article/details/89154445