文章目录
- SpringMVC
-
- [1. 工作原理](#1. 工作原理)
- 2.使用
- [3. 常用注解](#3. 常用注解)
- [4. 转发与重定向](#4. 转发与重定向)
- [5. REST风格](#5. REST风格)
- [6. SSM整合](#6. SSM整合)
SpringMVC
1. 工作原理
SpringMVC 框架的优点
优点:
- 基于 MVC 架构,功能分工明确。解耦合。
- 容易理解,上手快;使用简单。就可以开发一个注解的 SpringMVC 项目,SpringMVC 也是轻量级的,jar 很小。不依赖的特定的接口和类。
- 作为 Spring 框架一部分,能够使用 Spring 的 IoC 和 Aop。方便整合Strtus,MyBatis,Hiberate, JPA 等其他框架。
- SpringMVC 强化注解的使用,在控制器,Service,Dao 都可以使用注解。方便灵活。使用@Controller 创建处理器对象,@Service 创建业务对象,@Autowired 或者@Resource 在控制器类中注入 Service, Service 类中注入Dao。
2.使用
引入jar文件
xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--引入json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
创建spring-mvc.xml
xml
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<!--扫描包-->
<context:component-scan base-package="com.hz.controller"/>
<!--开启mvc注解-->
<mvc:annotation-driven/>
<!--释放静态资源 html,图片,js文件-->
<mvc:default-servlet-handler/>
创建controller层
java
@Controller
public class UserController {}
在web.xml中配置前端控制器并读取spring-mvc.xml
xml
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在controller中编写多个servlet请求
java
@RequestMapping(value = "/userLogin",method = RequestMethod.POST)
public ModelAndView userLogin(@RequestParam(value = "uname",defaultValue = "瑶瑶") String uname,@RequestParam(value = "upwd",defaultValue = "123")String upwd)
{
ModelAndView modelAndView= new ModelAndView();
modelAndView.getModel().put("uname",uname);
modelAndView.getModel().put("upwd",upwd);
modelAndView.setViewName("/views/main.jsp");
return modelAndView;
}
@RequestMapping(value = "/loginUser1",method = RequestMethod.POST)
public String loginUser1(User user ,Model model){
model.addAttribute("uname",user.getUsername());
model.addAttribute("upwd",user.getPassword());
return "/views/main.jsp";
}
@RequestMapping(value = "/loginUser4",method = RequestMethod.POST)
public String loginUser4(Map<String,Object> map,User user){
map.put("uname",user.getUsername());
map.put("upwd",user.getPassword());
return "/views/main.jsp";
}
创建视图解析器
xml
<!--//视图渲染器 (简化页面路径) return "页面名字"-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
设置编码过滤器
xml
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3. 常用注解
@Controller
标注一个普通的JavaBean成为可以处理请求的控制器
@RequestMapping
通过请求URL进行映射
java
@RequestMapping("/user")//标识在类上
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/userLogin",method = RequestMethod.POST) //方法上
public String userLogin(String uname, String upwd, HttpSession session){
...
}
method:
RequestMethod.GET 必须以GET方式进入 @GetMapping
RequestMethod.POST 必须以POST方式进入 @PostMapping
params:
{ "param1=value1" , "param2" , "!param3" }
请求参数的映射条件,指定请求的URL地址需要带那些参数
@RequestParam
参数传递
java
public ModelAndView index(
@RequestParam(value = "uname",required = false,defaultValue = "zhangsan")
String uname){}
//value:属性名,如:xxxx?name1=...
//required:是否必须 false为否
//defaultValue:默认值
@ModelAttribute
java
@RequestMapping(value="/ts1")
public String index1(@ModelAttribute("user") User user){
user.setUser_name("张三");
System.out.println(user.getUser_name());
return "user";
}
@SessionAttributes
java
//只能定义到类上,作用是将指定的Model中的键值对添加到session中
//@SessionAttributes(value = {"aa","bb"})
//根据类型存储只要是String
//@SessionAttributes(types= String.class)
//根据User类型存储属性
//@SessionAttributes(types=User.class)
@SessionAttributes(types={User.class},value = {"aa","bb"})
@Controller
public class orderController {
...
}
@ResponseBody
java
@ResponseBody //返回JSON数据 一般用于方法上
@RequestMapping("/loginUser1")
public MassageJson<User> loginUser1(){
User user=new User();
user.setUsername("张三");
user.setPassword("123456");
return new MessageJson<>("200","请求成功",user);
}
对象中添加:实体类实现序列化
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
表示属性为null不返回
@RestController
标注该类中所有的方法都返回JSON 用于类中。无须在写@Controller
@DateTimeFormat
java
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
//用户对象属性,控制入参时日期类型转换
private Date user_login_endtime;
@RequestHeader
获取请求头中的参数
java
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.POST)
public User index(@RequestHeader(value = "token",defaultValue = "1",required =
false) int tokenid){
......
}
@JsonFormat
返回JSON数据时日期类型处理
java
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date user_login_endtime;
参数传递
ModelAndView
java
@RequestMapping(value = "/show",method = RequestMethod.GET)
public ModelAndView show(){
ModelAndView modelAndView=new ModelAndView("main.jsp","username","血量会");
return modelAndView;
}
Model
java
@RequestMapping(value = "/loginUser1",method = RequestMethod.POST)
public String loginUser1(User user ,Model model){
//以Map方式进行存储,用于向作用域中存值
model.addAttribute("aa",user.getUsername());
model.addAttribute("bb",user.getPassword());
return "main.jsp";
}
Map
java
@RequestMapping(value = "/loginUser4",method = RequestMethod.POST)
public String loginUser4(Map<String,Object> map,User user){
//以Map方式进行存储,用于向作用域中存值
map.put("aa",user.getUsername());
map.put("bb",user.getPassword());
return "/main.jsp";
}
4. 转发与重定向
java
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
public String addUser(User user){
int i=userService.addUser(user);
if(i==1){
//转发 return "forward:页面";
return "/index.jsp";
}else{
//重定向
return "redirect:/addUser.jsp";
}
}
5. REST风格
java
@RequestMapping(value="/ts1/{user_id}.html")
public String index1(@PathVariable("user_id") Long user_id)
{
System.out.println("id======"+user_id);
return "user";
}
请求路径为:.../ts1/参数.html
如:..../ts1/1.html或..../ts1/10.html
6. SSM整合
引入jar文件
xml
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--引入json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
创建controller类
@Controller 标识此类为控制器类
@RequestMapping 设置请求路径
@RequestParam 接收用户传入参数