一、简单使用注解版
使用注解,减少了很多代码,以后开发会经常用到。
项目结构
web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个SpringMVC的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--服务器启动的时候就启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- "/"匹配所有的请求不包括.jsp。"/*"匹配所有的请求包括.jsp -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
配置文件springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描包,让指定包下的注解生效,有IoC容器统一管理 -->
<context:component-scan base-package="com.shengjava.web"/>
<!--开启注解扫描-->
<mvc:annotation-driven/>
<!--在web开发中,我们一般存在静态资源css,js,img。。。-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
JSP页面test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>test.jsp</title>
</head>
<body>
${msg}
${m}
</body>
</html>
HelloController类
@GetMapping("/hello")注解,代表的是get请求的路径。还有@PostMapping代表post请求的路径。如果是@RequestMapping,则get和post都可以访问到。
使用的是Model和ModelMap,可以进行模型数据的绑定,然后直接return需要跳转的页面(该页面位置是由,springmvc-servlet.xml中的视图解析器下配置的前缀和后缀拼接而成的)。此时可以使用el表达式直接显示出绑定在Model和ModelMap中的数据。
这里因为return时就是直接到页面了,所以不需要用ModelAndView。常用的是Model。
对比:
- Model:只有几个方法只适合用于储存数据,简化了新手对它操作和理解。
- ModelMap:继承了LinkedMap,除了实现了自身的一些方法,同样的继承L inkedMap的方法和特性;
- ModelAndView:可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model m, ModelMap mp) {
// 模型数据(可以使用这两个,ModelAndView不能使用了)
m.addAttribute("m", "hello Spring MVC");
mp.put("msg", "hello Spring MVC");
// 视图数据
return "test";
}
}
部署tomcat运行,页面中会输出:
hello Spring MVC hello Spring MVC
二、RESTful风格
1.概念
RestFul就是一个资源定位及资源操作的风格,不是标准也不是协议,只是一种风格,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
2.功能
资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET使用不同方法对资源进行操作。分别对应:添加、删除、修改、查询
传统操作资源:通过不同的参数来实现不同的效果
http://127.0.0.1/item/query.action?page=1&count=10 查询 GET(查询第1页的10条数据)
使用RestFul风格
http://127.0.0.1/item/1/10 查询 GET(使用RestFul风格)
3.使用
在Spring MVC中可以使用@PatnVariable注解,让方法参数的值对应绑定到一个URL模板变量上。
在上面案例的controller包下新增一个类RestfulController。
当用get方式访问/restful01/aaa/bbb则会返回aaabbb。如果get访问/restful02/1/2则返回3.
@Controller
public class RestfulController {
/** 注解@ResponseBody将返回的数据转换成json格式 */
@ResponseBody
@GetMapping("/restful01/{s1}/{s2}")
public String restful01(@PathVariable String s1, @PathVariable String s2) {
return s1+s2;
}
@ResponseBody
@GetMapping("/restful02/{n1}/{n2}")
public String restful02(@PathVariable int n1, @PathVariable int n2) {
return "" + (n1 + n2);
}
}
4.注解
Spring MVC的@RequestMapping注解能够处理HTTP请求的方法,比如GET,PUT,POST,DELETE以及PATCH。这个注解可以设置http请求的方法,例如,@RequestMapping(method = RequestMethod.XXX)
所有的地址请求默认都会是HTTP GET类型的。
方法级别的注解有如下几个:组合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@XXXMapping是一个组合注解
相当于@RequestMapping(method = RequestMethod.XXX)的一个快捷方式,通常使用这个!
三、请求转发与重定向
1.请求转发
Spring MVC在配置了视图解析器后,默认情况下controller的方法return就是请求转发。
如下代码:代表访问/hello,然后是转发到test。
@GetMapping("/hello")
public String hello(Model m, ModelMap mp) {
return "test";
}
2.重定向
如果return时,前面加上"redirect:"则时重定向。
如下代码:代表访问/hello,然后重定向到了test路径
@GetMapping("/hello")
public String hello(Model m, ModelMap mp) {
return "redirect:test";
}
四、其他常用注解
1.接受请求参数
我们接受html页面传来的请求信息。可以直接在方法的参数中设置(参数名要和html传来的参数名一致),Spring MVC会帮我们注入值。
例如,访问/addUser?username=zhangsan&password=123456
如下代码:后台可以获取到用户的请求信息,并且可以打印出传入的参数。返回到页面显示的值为"{msg=success}"。
推荐前端接受的参数前面加上@RequestParam注解,@RequestParam注解如果什么都不加,那么参数名默认就是变量名。如果设置为@RequestParam(“password”),那么参数password从前端获取的属性值则为注解括号中的值。
@ResponseBody
@GetMapping("/addUser")
public String addUser(@RequestParam String username, @RequestParam("password") String password) {
System.out.println("前端输入的参数:username:" + username + " password:" + password);
return "add success";
}
如果前台传来的是一个对象。例如,用户注册有很多个字段,那么我们的参数中可以页设置为一个对象,如下形式例如:
@ResponseBody
@GetMapping("/addUser")
public String addUser(User u) {
return "add success";
}
相关
我的该分类的其他相关文章,请点击:【Spring + Spring MVC + MyBatis】文章目录