一、SpringMVC入门![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c059d5efed9d7687d25fd7789ee69c03.png#pic_center)
实战:
前端获得值:
<%@ page isELIgnored="false" %>
<html>
<body>
<h2>Hello World!</h2>
${requestScope.user.name}
</body>
</html>
controller:
model、map、对象等不同参数下的测试:
package com.imooc.controller;
import com.imooc.entity.Goods;
import com.imooc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator.
*/
@RequestMapping("/AnnotationHandler")
@Controller
public class AnnotationHandler {
@RequestMapping("/ModelTest")
public String ModelTest(Model model){
User user = new User();
user.setName("Tom");
model.addAttribute("user",user);
return "index";
}
@RequestMapping("/MapTest")
public String MapTest(Map<String,User> map){
User user = new User();
user.setName("Jerry");
map.put("user",user);
return "index";
}
@RequestMapping("/ModelAndViewTest")
public ModelAndView ModelAndViewTest(){
User user = new User();
user.setName("Cat");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user",user);
modelAndView.setViewName("index");
return modelAndView;
}
@RequestMapping("/add")
public ModelAndView add(Goods goods){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("goods",goods);
modelAndView.setViewName("show");
return modelAndView;
}
}
springxml:
<?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"
xsi:schemaLocation="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.xsd">
<context:component-scan base-package="com.imooc.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
二、SpringMVC数据绑定
实战
springxml:
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<context:component-scan base-package="com.imooc"></context:component-scan>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置前缀-->
<property name="prefix" value="/"></property>
<!--配置后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
基本类型、数组类型绑定:
@Controller
public class DataBindController {
@Autowired
private CourseDAO courseDAO;
@RequestMapping(value = "/baseType")
@ResponseBody //直接返回 无需前端页面
public String baseType(@RequestParam(value = "id") int id){
return "id:"+id;
}
//url:http://localhost:8080/baseType?id=2
//显示:id:2
@RequestMapping(value = "/packageType")
@ResponseBody
public String packageType(@RequestParam(value = "id") Integer id){
return "id:"+id;
}
//url:http://localhost:8080/baseType?id=2
//显示:id:2
//url:http://localhost:8080/baseType?id
//显示:id:null
@RequestMapping(value = "/arrayType")
@ResponseBody
public String arrayType(String[] name){
StringBuffer sbf = new StringBuffer();
for (String item:name){
sbf.append(item).append(" ");
}
return sbf.toString();
}
// url:http://localhost:8080/arrayType?name=abc&name=3
//显示:abc 3
对象类型绑定(部分代码):
实体类:
public class Course {
private int id;
private String name;
private double price;
private Author author;
...
}
前端页面:
add.jsp:
文本框的name属性与实体类对应!
controller:
@Controller
public class DataBindController {
@Autowired
private CourseDAO courseDAO;
@RequestMapping(value = "/pojoType")
public ModelAndView pojoType(Course course){
courseDAO.add(course);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("courses",courseDAO.getAll());
return modelAndView;
}
}
集合类型绑定(List、Set、Map)(部分代码):
实体类:
//List
public class CourseList {
private List<Course> courses;
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
//Map
public class CourseMap {
private Map<String,Course> courses;
public void setCourses(Map<String, Course> courses) {
this.courses = courses;
}
public Map<String, Course> getCourses() {
return courses;
}
}
//Set
public class CourseSet {
private Set<Course> courses = new HashSet<Course>();
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public Set<Course> getCourses() {
return courses;
}
public CourseSet(){
courses.add(new Course());
courses.add(new Course());
}
}
前端页面:
同样的,name属性要与实体类一一对应。
addList.jsp:
addMap.jsp:
addSet.jsp:
controller:
@Controller
public class DataBindController {
@Autowired
private CourseDAO courseDAO;
@RequestMapping(value = "/listType")
public ModelAndView listType(CourseList courseList){
for(Course course:courseList.getCourses()){
courseDAO.add(course);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("courses",courseDAO.getAll());
return modelAndView;
}
@RequestMapping(value = "/mapType")
public ModelAndView mapType(CourseMap courseMap){
for(String key:courseMap.getCourses().keySet()){
Course course = courseMap.getCourses().get(key);
courseDAO.add(course);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("courses",courseDAO.getAll());
return modelAndView;
}
@RequestMapping(value = "/setType")
public ModelAndView setType(CourseSet courseSet){
for (Course course:courseSet.getCourses()){
courseDAO.add(course);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("courses",courseDAO.getAll());
return modelAndView;
}
}
JSON类型:
前端页面json.jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
var course = {
"id":"8",
"name":"SSM框架整合",
"price":"200"
};
$.ajax({
url:"jsonType",
data:JSON.stringify(course),
type:"post",
contentType:"application/json;charse=UTF-8",
dataType:"json",
success:function(data){
alert(data.name+"---"+data.price);
}
})
})
</script>
<body>
</body>
</html>
controller:
@RequestMapping(value = "/jsonType")
@ResponseBody
public Course jsonType(@RequestBody Course course){
course.setPrice(course.getPrice()+100);
return course;
}
三、SpringMVC—RESTful风格
实战:
@GetMapping @PostMapping @PutMapping @DeleteMapping分别对应只能处理get、post、put、delete形式的操作。
package com.imooc.controller;
import com.imooc.dao.CourseDAO;
import com.imooc.entity.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by Administrator.
*/
@Controller
public class CourseController {
@Autowired
private CourseDAO courseDAO;
/**
* 添加课程
*/
@PostMapping(value = "/add")
public String add(Course course){
courseDAO.add(course);
return "redirect:/getAll";
}
/**
* 查询全部课程
* @return
*/
@GetMapping(value = "/getAll")
public ModelAndView getAll(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("courses",courseDAO.getAll());
return modelAndView;
}
/**
* 通过id查询课程
*/
@GetMapping(value = "/getById/{id}")
public ModelAndView getById(@PathVariable(value = "id") int id){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("edit");
modelAndView.addObject("course",courseDAO.getById(id));
return modelAndView;
}
/**修改课程
*
*/
@PutMapping(value = "/update")
public String update(Course course){
courseDAO.update(course);
return "redirect:/getAll";
}
/**
* 删除课程
*/
@DeleteMapping(value = "/delete/{id}")
public String delete(@PathVariable(value = "id") int id){
courseDAO.deleteById(id);
return "redirect:/getAll";
}
}
springxml:
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<mvc:annotation-driven >
<!-- 四种Http协议的消息转换器 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置自动扫描 -->
<context:component-scan base-package="com.imooc"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--处理中文乱码-->
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--对客户端请求的静态资源如图片、JS文件等的请求交由默认的servlet进行处理-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<!--对四种请求进行过滤的springMVC过滤器-->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
四、SpringMVC 拦截器
对于登录拦截操作过滤器实战(仅有拦截器操作的代码):
定义拦截器操作:
package com.imooc.core;
import com.imooc.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = (User)request.getSession().getAttribute("session_user");
if(user==null) {
// System.out.println("1:keketip--login====preHandle===>");
response.sendRedirect(request.getContextPath()+"/login");
return false;
}
return true;//会终止所有的请求
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// System.out.println("3:-----keketip==--login==postHandle===>");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// System.out.println("4--->keketip=--login===afterCompletion===>");
}
}
springxml:
<?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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 配置自定义扫描包 -->
<context:component-scan base-package="com.imooc.web"></context:component-scan>
<!-- 拦截器的注册 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="com.imooc.core.LogInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<!--<mvc:mapping path="/user/search"/>
<mvc:mapping path="/user/updatepwd"/>
<mvc:mapping path="/user/updateheaderPic"/>-->
<!--<mvc:mapping path="/user/*"></mvc:mapping>-->
<mvc:mapping path="/user/**"></mvc:mapping>
<!--exclude-mapping在所有拦截中进行排除,一般在通配符会有意义。-->
<mvc:exclude-mapping path="/user/updatepwd"></mvc:exclude-mapping>
<mvc:exclude-mapping path="/user/updatebackground/*"></mvc:exclude-mapping>
<bean class="com.imooc.core.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- 映射物理路径 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>