标签:控制器 RequestMapping SpringMVC h1 Controller 方法 public
Controller控制器
- 控制器提供访问应用程序的行为,有接口实现和注解实现两种方法。
- 控制器负责解析用户的请求并将其转换为一个模型。
- 在Spring MVC中一个控制器类可以包含多个方法
- 在Spring MVC中,对于Controller的配置方式有很多种
接口实现
1.创建controller类
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView mv = new ModelAndView();
//传递数据
mv.addObject("msg","ControllerTest1");
//跳转界面
mv.setViewName("test");
return mv;
}
}
2.创建springmvc-config.xml
<?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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
</beans>
3.写前端界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>
4.执行
说明:接口实现Controller是一个较老的方法,不推荐!!
缺点:一个控制器中只能有一个方法,如果要多个方法需要定义多个Controller。
注解实现
见上一篇:SpringMVC-annotation
@RequestMapping
- @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法,可用于类上或方法上。
1.用于方法上
@Controller
public class HelloController {
@RequestMapping("/h1")
public String test(Model model){
//传递数据
model.addAttribute("msg","hello HelloController");
//跳转页面
return "hello";
}
}
访问路径:http://localhost:8080 / 项目名 / h1
2.用于类上和方法上
@Controller
@RequestMapping("hhh")
public class HelloController {
@RequestMapping("/h1")
public String test(Model model){
//传递数据
model.addAttribute("msg","hello HelloController");
//跳转页面
return "hello";
}
}
访问路径:http://localhost:8080 / 项目名/ hhh/h1 , 需要先指定类的路径再指定方法的路径;
标签:控制器,RequestMapping,SpringMVC,h1,Controller,方法,public 来源: https://blog.csdn.net/qq_42665745/article/details/112852361
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。