1.使用注释的布置
第一步:配置web.xml (就是DispatcherSerlvet 和一些基本配置)
第二步:编写springmvc.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">
<!--扫描器-->
<context:component-scan base-package="com.kuang.controller"/>
<!--不让视图解析器运行静态包 例如:css js-->
<mvc:default-servlet-handler/>
<!--自动注入 处理器映射器和处理器适配器-->
<mvc:annotation-driven/>
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
第三步:写controller文件
@Controller
public class HelloController {
// 实际路径
@GetMapping("/hehe")
public String hello(Model model){
model.addAttribute("msg","HelloSpringMVC-annotation");
// 返回的是你要转跳到哪个包 然后视图解析器接收 进行拼接
return "annotation";
}
}
第四步:运行
2.现在常用的注释的分类即使用
@Controller(还有三和他的作用一样 ,在spring学过但是我忘了,作用是区分层级)一旦被这个注释表是就代表的是:该类已被spring接管
@RequrstMapping :就是他的实际路径 属性:method (设置请求方式,不过后面直接有注解 所以就记一下 怕有sx用)
RequrstMapping 分为两种情况: 标识在类上和 方法上 标在类上就要带上他就好没啥的 例如:
@Controller
@RequestMapping("h1")
public class HelloController {
@RequestMapping("/nihao")
public String hello(int a,int b,Model model){
int sum=a+b;
model.addAttribute("msg","他们的和是:"+sum);
return "hehe";
}
}
那他的实际URL地址就是 /h1/nihao
可能出现的问题: 就是@RequertMapping (name="/nihao",methom=RequestMethod.GET ) 的时候,你传的值类型是,int 和 string的时候就会报错
@Get~~ @Post~~
3. RsetFu风格
RsetFu和传统的区别:
传统传值:路径?a=1&b=1&c=1
RsetFu传值:路径/值一/值二/值三
传统的写法
@Controller
public class HelloController {
@RequestMapping("/nihao")
public String hello(int a,int b,Model model){
int sum=a+b;
model.addAttribute("msg","他们的和是:"+sum);
return "hehe";
}
}
可能出现的问题 :没有传值
RsetFu方式:
@Controller
public class HelloController {
@RequestMapping("/nihao/{a}/{b}")
public String hello(@PathVariable int a,@PathVariable int b, Model model){
int sum=a+b;
model.addAttribute("msg","他们的和是:"+sum);
return "hehe";
}
}
@PathVariable 就是标明这个是一个路径变量 要想用的话就必须要使用这个注释
此时的传值的方式 就是: 路径/1/2
3.转发于重定向
转发
@GetMapping("/hello/{a}")
public String test1(Model model,@PathVariable int a){
int j=a;
System.out.println(j);
model.addAttribute("msg","ModelTest1");
return "hehe";
}
他有两种形式 : 一,就是什么都不加 如上图所示 。二,就是在return "forwod:路径"
重定向
@GetMapping("/t2")
public String test2(){
return "redirect:index.jsp";
}
就是加一个 redirect在前面就好