Maven整合SSM框架开发之Controller层开发

        前文已经介绍了根据客户具体需求实现service层的功能,而本文讲述的控制层则主要将service功能视图化,将实现的功能的结果显示出来。SpringMVC框架则是实现控制层的框架,该框架通过DispatchServlet找到相应的Controller,并将客户请求交给Controller,然后Controller进行调用业务逻辑组件,返回ModelAndView,接着调用视图解析器找到ModelAndView对应的视图,并将结果显示在客户端。以下是本文项目需要的Controller类:

package com.carson.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.carson.pojo.Book;
import com.carson.service.BookService;
import com.carson.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("")
public class BookUserController {
	@Autowired
	BookService bookService;

	@RequestMapping("listBook")
	public ModelAndView listBook(Page page){
		ModelAndView mav = new ModelAndView();
		PageHelper.offsetPage(page.getStart(),5);
		List<Book> cs= bookService.getBookList();
		int total = (int) new PageInfo<>(cs).getTotal();
		
		page.caculateLast(total);
		
		// 放入转发参数
		mav.addObject("cs", cs);
		// 放入jsp路径
		mav.setViewName("listbook");
		return mav;
	}
}

        然后编写对应的jsp文件,包括主页文件index.jsp和上述Controller类返回的ModelAndView对应的listbook.jsp文件

index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1><a href="listBook">showbook</a>
</center>
</body>
</html>

listbook.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	<table align='center' border='1' cellspacing='0'>
	    <tr>
	        <td>id</td>
	        <td>user_id</td>
	        <td>name</td>
	    </tr>
	    <c:forEach items="${cs}" var="c" varStatus="st">
	        <tr>
	            <td>${c.id}</td>
	            <td>${c.user_id}</td>
	            <td>${c.name}</td>
	        </tr>
	    </c:forEach>
	</table>
	<div style="text-align:center">
		<a href="?start=0">首  页</a>
		<a href="?start=${page.start-page.count}">上一页</a>
		<a href="?start=${page.start+page.count}">下一页</a>
		<a href="?start=${page.last}">末  页</a>
	</div>
 </div>
        以上便是Controller层的开发以及其对应的视图文件的编写。这主要利用了SpringMVC的前端控制器DispatcherServlet的作用,将请求与控制层关联,并将返回的ModelAndView对象与对应的视图相关联,从而整个过程都是由SpringMVC框架进行管理,而无需通过硬编码耦合来实现关联。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值