目录
1.springmvc的简介和配置
什么是springmvc?
Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。
导入pom依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
2.Springmvc之helloworld实现
第一个springMVC程序:HelloWorld
配置文件配置:
1.扫描base-package
[ 定义注解扫描,开启注解扫描,开启动态扫描]
2.配置视图解析器
本地资源视图解析器:internalResourceViewResolver
springmvc-servlet.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" xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 通过context:component-scan元素扫描指定包下的控制器-->
<!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.zking.oa"/><!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
<!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
<mvc:annotation-driven></mvc:annotation-driven><!--3) ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean><!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<mvc:resources location="/images/" mapping="/images/**"/>
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
</beans>
做静态资源映射
修改web.xml
<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_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 读取Spring上下文的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener><!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- @version $Id: applicationContext.xml 561608 2007-08-01 00:33:12Z vgritsenko $ -->
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="applicationContext-mybatis.xml"></import>
</beans>
HelloController:
package com.xbb.ssm.controller;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* 被controller标记的类 会交给 spring 进行管理
* @Controller
* @Service
* @Repository
* @Component
* 以上四个都代表 当前类 交给Spring容器进行管理
*/
@Controller
public class HelloController {
// 自定义mvc:浏览器发送请求 http://localhost:8080/hello.action?methodName=hello
// springmvc:浏览器发送请求 http://localhost:8080/helloReq
// 此处是下面的简写版
@RequestMapping("/helloReq")
public String hello(){
System.out.println("hello springmvc...");
// /hello.jsp
return "hello";
}
@RequestMapping("/hello2")
public ModelAndView hello2(HttpServletRequest req){
ModelAndView mv=new ModelAndView();
mv.setViewName("hello");
mv.addObject("msg","success");
return mv;
}
}
hello.jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 17:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
</body>
</html>
运行效果:
3.CRUD之常用注解及返回值
BookController
package com.xbb.ssm.controller;
import com.xbb.ssm.biz.BookBiz;
import com.xbb.ssm.model.Book;
import com.xbb.ssm.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @RequestMapping 加在 类上面,称窄化路径,其实相当于包的概念
*/
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookBiz bookBiz;
// http://localhost:8080/book/list
@RequestMapping
// @GetMapping=@RequestMapping(value = "/list",method = RequestMethod.GET)
// @PostMapping
// @DeleteMapping
// @PutMapping
public String hello(HttpServletRequest req){
System.out.println("hello springmvc...");
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
Map map=new HashMap();
String bname = req.getParameter("bname");
map.put("bname",bname);
List<Map> maps = this.bookBiz.listPager(map, pageBean);
req.setAttribute("lst",maps);
return "hello";
}
@RequestMapping("/add")
public String add(Book book){
this.bookBiz.insertSelective(book);
return "redirect:/book/list";
}
@RequestMapping("/edit")
public String edit(Book book){
this.bookBiz.insertSelective(book);
return "redirect:/book/list";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable("bid") Integer bid){
this.bookBiz.deleteByPrimaryKey(bid);
return "redirect:/book/list";
}
}
index.jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 21:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/book/list?bname=圣墟">查询所有</a>
<a href="${pageContext.request.contextPath}/book/add?bid=2&bname=sb&price=9.9">增加</a>
<a href="${pageContext.request.contextPath}/book/edit?bid=2&bname=suibian&price=9.8">修改</a>
<a href="${pageContext.request.contextPath}/book/del/2">删除</a>
</body>
</html>
hello.jsp:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/16
Time: 17:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Title</title>
</head>
<body>
SpringMVC 你好
${msg}
<hr>
${lst}
<c:forEach items="${lst}" var="l">
${l.bid}:${l.bname}<hr>
</c:forEach>
</body>
</html>
运行效果: