controller层
@RequestMapping(value = "/emps")
public String GetEmployees(@RequestParam(value = "pn",
defaultValue ="1")Integer pn , Model model){
PageHelper.startPage(pn,8);
List<Employee> employeeslist = employeeService.GetEmployees();
PageInfo page = new PageInfo(employeeslist,7);
model.addAttribute("pageinfo",page);
return "list";
}
测试类
spring配置文件和springmvc配置文件的位置如下图
package test.juint;
import cn.orz.bean.Employee;
import com.github.pagehelper.PageInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration //加上这个注解才能注入WebApplicationContext
@ContextConfiguration(locations = { "classpath:beans.xml","classpath:springmvc.xml" })
public class MvcTest {
MockMvc mocmvc;
@Autowired
WebApplicationContext context;
@Before
public void initMockMvc() {
mocmvc = MockMvcBuilders.webAppContextSetup(context).
build();
}
@Test
public void TestPage() throws Exception {
MvcResult result = mocmvc.perform(MockMvcRequestBuilders.
get("/emps")
.param("pn", "2")).andReturn();
MockHttpServletRequest request = result.getRequest();
PageInfo pageinfo = (PageInfo) request.getAttribute("pageinfo");
System.out.println("当前页码"+pageinfo.getPageNum());
System.out.println("-----"+pageinfo.toString());
String result2 = mocmvc.perform(MockMvcRequestBuilders.
get("/emps")
.param("pn", "2")).andReturn().getResponse().getContentAsString();
System.out.println("返回的json值"+result2 );
}
}
1、以上代码注意一下几点(否则会出错)
@WebAppConfiguration //加上这个注解才能注入WebApplicationContext
2、servlet必须大于3.0.0,否则会报错
在pom.xml文件中引入3.1.0版本的javax.servlet
<!-- jsp-servlet -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
完结。