文章目录
一、基本操作
响应请求的方式
序号 | 响应方式 | 说明 |
---|---|---|
1 | 不响应 | void+@ResponseBody注解 |
2 | ModelAndView | 通过setViewName方法 |
3 | 直接指定响应页面 | 返回值为String类型,返回结果指定跳转地址 |
4 | 重定向 | 跳转地址前加redirect前缀即可 |
5 | HttpServletRequest和HttpServletResponse | 形参中声明这两个变量。然后通过相关api跳转 |
1、ModelAndView方式
/**
*基于注解的自定义Controller
* @author Administrator
*
*/
@Controller
@RequestMapping("/hello")
// http://../项目名称/hello
public class SpringController {
/**
* 服务端响应页面
* ModelAndView
* @return
*/
@RequestMapping("/h1")
public ModelAndView hello1(){
System.out.println("---Spring1----");
ModelAndView m=new ModelAndView();
// 加'/'表示绝对路劲 不加表示相对路径
m.setViewName("/index.jsp");
return m;
}
}
2、服务器不响应结果给客户端
/**
* 服务端不响应结果给客户端
* void+@ResponseBody
* @return
*/
@RequestMapping("/f1")
@ResponseBody
public void fun1(){
System.out.println("---f1----");
}
返回一个字符串
/**
* 服务端响应字符串给客户端
*
* @return
*/
@RequestMapping("/f2")
@ResponseBody
public String fun2(){
System.out.println("---f2----");
return "String";
}
4、返回一个页面
绝对路径
/**
* 服务器响应一个页面 绝对路径
*
* @return
*/
@RequestMapping("/f3")
public String fun3(){
System.out.println("---f3----");
return "/index.jsp";
}
相对路径
/**
* 服务器响应一个页面 相对路径
*
* @return
*/
@RequestMapping("/f4")
public String fun4(){
System.out.println("---f4----");
return "index.jsp";
}
404报错 相对路径找的是hello文件夹下的index.jsp文件
5、加前缀和后缀
视图解析器里的成员变量
配置视图解析器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 开启扫描 -->
<context:component-scan base-package="com.sxt.controller"/>
<!-- 开启SpringMVC注解的方式 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置视图解析器地址 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置前后缀 -->
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
重定向(加一个redirect)
@RequestMapping("/f5")
public String fun5(){
System.out.println("---f5----");
//默认的是服务器端调整,如果需要重定向的话加redirect:前缀
return "redirect:/index.jsp";
}
HttpServletRequest和HttpServletResponse
/**
* 传统的方式
* @param req
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping("/f6")
public void fun6(HttpServletRequest req,HttpServletResponse response) throws ServletException, IOException{
System.out.println("-----f6--------");
req.getRequestDispatcher("/index.jsp").forward(req, response);
}