前置知识:
Spring
Mybatis
学习视频:https://www.bilibili.com/video/BV1aE41167Tu?spm_id_from=333.999.0.0
SpringMVC执行流程
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.3version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.1.3-b06version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
//Hello.java
public class Hello extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if(method.equals("add")){
req.setAttribute("msg","执行了add方法");
}
if(method.equals("delete")){
req.setAttribute("msg","执行了delete方法");
}
req.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<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">
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.kuang.servlet.Helloservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
web-app>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${msg}
MVC模式做的事:
文档
Typical context hierarchy in Spring Web MVC
Single root context in Spring Web MVC
Spring的web框架围绕
DispatcherServlet
设计,DispatcherServlet
将请求分发到不同的处理器
以请求为驱动,围绕一个中心Servlet(DispatcherServlet)分派请求及提供其他功能,DispatcherServlet继承自HttpServlet基类
用户发出请求,前置控制器DispatcherServet
接受请求,并根据配置信息拦截相应请求
DispatcherServlet 调用处理器映射器 HandlerMapping
,根据url找对应的处理器 HandlerExecution
,并返回给 DispatcherServlet
HandlerExecution
表示具体的控制器
HandlerAdapter
表示处理器适配器,其 按照特定的规则去执行Handler ,适配Controller
Handler让具体的Controller执行
Controller将具体的执行信息封装为 ModelAndView
实例 返回给 HandlerAdapter
addObject(attributeName:"",attributeValue:"");
将数据以键值对方式封装为ModelsetViewName(viewName:"");
方法 设置视图层 ViewHandlerAdapter
将 ModelAndView
实例 传递给 DispatcherServlet
DispatcherServlet 调用 视图解析器ViewResolver
来解析 HandlerAdapter
传递的 逻辑视图名,
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
视图解析器VierResolver
根据配置信息加前后缀变为 真实视图路径
并传给 DispatcherServlet
DispatcherServlet
根据视图解析器解析返回的结果,调用具体的视图,最终视图呈现给用户
服务器端程序只有识别到war类型的压缩包才能部署
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
package com.kuang.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//封装对象,放在ModelAndView中。Model
mv.addObject("msg","HelloSpringMVC!");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
return mv;
}
}
<bean id="/hello" class="com.kuang.controller.HelloController"/>
<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"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FrontController {
/*
* @RequestMapping ——incoming Request 请求名
* param ——model
* return ——view
* */
@RequestMapping("/hello1")
public String hello1(Model model){
model.addAttribute("msg","Hello SpringMVC annotation!");
return "hello1";//被视图解析器处理
}
@RequestMapping("/hello2")
public String hello2(Model model){
model.addAttribute("msg","Hello SpringMVC annotation!");
return "hello2";//被视图解析器处理
}
}
@Component
@Service
@Controller
@Repository
@RequestMapping
Restful是一个资源定位及资源操作的风格
- 安全
- 简洁
- 有层次
- 更易于实现缓存机制
传统传参:通过链接中的参数判断操作类型
localhost:8090/method?flag= &
restful风格:通过 请求方式 实现不同类型操作
localhost:8090/method/1/2/3/4
参数列表中的参数用@PathVariable
注解,对应URI的参数
/*
* @RequestMapping("method/{}/{}")
* restful风格的参数名必须和参数列表的参数同名才可绑定
* */
@RequestMapping("add/{a}/{b}")
public String deliverParam(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("result",a+b);
return "result";
}
@[请求方式]Mapping(“[restful]”)
<==>
@RequestMapping(value="[restful]",method=RequestMethod.[请求方式])
@RequestMapping(value = "add/{a}/{b}",method = RequestMethod.GET)
public String deliverParam(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("result","通过GET add:result="+(a+b));
return "result";
}
@PostMapping("add/{a}/{b}")
public String deleverParam(@PathVariable int a,@PathVariable int b,Model model){
model.addAttribute("result","通过post方式 add:result="+(a+b));
return "result";
}
提交数据:localhost:8090/hello?name=kuangshen
处理方法
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
提交数据:localhost:8090/hello?username=kuangshen
处理方法 @RequestParam("[域名称]")
@RequestParam
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
要求提交的表单域和对象的属性名一致
假设传递的是一个对象,逐一匹配对象中的字段名
public class User{
private int id;
private String name;
private int age;
}
提交数据
localhost:8090/hello?id=1&age=15&name=kuangshen
处理方法
@RequestMapping("/user")
public String hello(User user){
System.out.println(user);
return "hello";
}
Model:只适用于存储数据,简化了对于Model 对象的操作和理解
ModelMap:继承了LinkedMap,除了实现自身的一些方法,同时继承LinkedMap
ModelAndView:可以在存储数据的同时,进行设置返回的逻辑视图,进行控制展示层的跳转
@PostMapping("add/{a}/{b}")
public String deleverParam(@PathVariable int a,@PathVariable int b,Model model){
model.addAttribute("result","通过post方式 add:result="+(a+b));
return "result";
}
@PostMapping("add/{a}/{b}")
public String deleverParam(@PathVariable int a,@PathVariable int b,ModelMap modelMap){
modelMap.addAttribute("result","通过post方式 add:result="+(a+b));
return "result";
}
public class ControllerTest1 implements Controller{
public ModelAndView handlerRequest(HttpServletRequest req,HttpServletResponse res){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
设置ModelAndView对象,根据view的名称和视图解析器跳到指定的页面
页面:{视图解析器前缀} + viewName + {视图解析器后缀}
HttpServletResponse进行输出
@RequestMapping("/jump")
public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().println("print");
}
HttpServletResponse重定向
@RequestMapping("/jump/dir")
public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect("/03_annotationHello/index.jsp");
}
HttpServletResponse实现请求转发
@RequestMapping("/jump/req")
public void test(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/form.jsp").forward(request,response);
}
重定向
@RequestMapping("/mvcjump/res")
public String test2(Model model){
model.addAttribute("msg","MVC Jump,sendRedirect");
return "redirect:/index.jsp";
}
请求转发
@RequestMapping("/mvcjump/req")
public String test1(Model model){
model.addAttribute("msg","MVC Jump,request dispatcher");
return "forward:/WEB-INF/jsp/form.jsp";
}
form表单传递的编码是
ISO8859
,一旦传递就会出现乱码,所以需要过滤器Filter
对请求的参数进行预处理
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
<filter>
<filter-name>encodingfilter-name>
<filter-class>com.kuang.filter.EncodingFilterfilter-class>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/url-pattern>
filter-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
JSON:JavaScript Object Notation 纯文本类型
轻量级数据交换格式——与XML相比
<!--js对象-->
var 变量名 = {key:value,key:value}
基本数据类型,数组,对象
var student = {lastName:"张三",age:18}
<!--转换方法-->
JSON = JSON.stringify(var)
var = JSON.parse(JSON)
前后端分离:
后端部署后端:提供接口,提供数据
JSON
前端独立部署:渲染后端的数据
JSON本质上就是一个字符串
@RequestMapping("/j1")
@ResponseBody //不会走视图解析器,直接返回一个JSON字符串
public String test(Model model){
User user = new User("啊1",12,"男");
return user.toString();
}
@RestController
使控制器转化为接口,直接返回JSON//@Controller
@RestController
public class Json {
@RequestMapping(value = "/j1")
//@ResponseBody //不会走视图解析器,直接返回一个JSON字符串
}
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.8version>
dependency>
public String writeValueAsString(Object value)
throws com.fasterxml.jackson.core.JsonProcessingException
@RequestMapping("/j1")
@ResponseBody //不会走视图解析器,直接返回一个JSON字符串
public String test(Model model) throws JsonProcessingException {
//Jackson ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
User user = new User("啊1",12,"男");
User user1 = new User("啊2",12,"男");
User user2 = new User("啊3",12,"男");
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
list.add(user2);
String str = objectMapper.writeValueAsString(list);
return str;
}
设置响应体内容的类型
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
@RequestMapping("/j2")
public String test2() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//自定义日期格式
//ObjectMapper 解析后的默认时间格式为:TimeStamp
return objectMapper.writeValueAsString(sdf.format(new Date()));
}
@RequestMapping("/j2")
public String test2() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//自定义日期格式
//ObjectMapper 解析后的默认时间格式为:TimeStamp
return objectMapper.writeValueAsString(new Date());
}
public class JSONUtils {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
objectMapper.setDateFormat(sdf);
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
阿里开发的专用于java开发的包,方便的实现json与JavaBean对象的相互转换,实现js对象与json的转换
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.60version>
dependency>
问题:
java.sql.SQLException: No suitable driver
解决:
将mysql-connector-java-8.0.16.jar,放到 JAVA_HOME目录下的jre\lib\ext目录下
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.16version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.1.3-b06version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.3version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.3version>
dependency>
dependencies>
一些不在 resources文件夹下的配置文件,默认是不会被编译的,所以需要配置静态资源路径,讲这些文件添加到解析目录中
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
public interface BooksMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBooksById(@Param("bookId") int id);
//更新书信息
int updateBook(Books books);
//查找一本书
Books selectBookById(@Param("bookId") int id);
//查找全部书
List<Books> selectAllBooks();
}
<mapper namespace="com.kuang.mapper.BooksMapper">
<insert id="addBook" parameterType="books">
insert into mybatis.ssmBuild
(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail});
insert>
<delete id="deleteBooksById">
delete from mybatis.ssmBuild where bookID=#{bookId};
delete>
<update id="updateBook" parameterType="books">
update mybatis.ssmBuild
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
update>
<select id="selectBookById">
select * from mybatis.ssmBuild where bookID=#{bookId};
select>
<select id="selectAllBooks" resultType="books">
select * from mybatis.ssmBuild;
select>
mapper>
/*BooksService.java*/
public interface BooksService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBooksById(int id);
//更新书信息
int updateBook(Books books);
//查找一本书
Books selectBookById(int id);
//查找全部书
List<Books> selectAllBooks();
}
/*BooksServiceImpl.java*/
public class BooksServiceImpl implements BooksService{
//service层调用dao层
private BooksMapper booksMapper;
public void setBooksMapper(BooksMapper booksMapper) {
this.booksMapper = booksMapper;
}
@Override
public int addBook(Books books) {
return booksMapper.addBook(books);
}
@Override
public int deleteBooksById(int id) {
return booksMapper.deleteBooksById(id);
}
@Override
public int updateBook(Books books) {
return booksMapper.updateBook(books);
}
@Override
public Books selectBookById(int id) {
return booksMapper.selectBookById(id);
}
@Override
public List<Books> selectAllBooks() {
return booksMapper.selectAllBooks();
}
}
#db.properties
mysqlDriver=com.mysql.cj.jdbc.Driver
mysqlUrl=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
root=root
rootPassword=2017002231
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.kuang.pojo"/>
typeAliases>
configuration>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="spring-mapper.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
beans>
保证所有的spring配置文件属于同一Applicationcontext下,属于同一context下的资源可以被直接识别
<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:property-placeholder location="db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="dataSourceName" value="${mysqlDriver}"/>
<property name="jdbcUrl" value="${mysqlUrl}"/>
<property name="user" value="${root}"/>
<property name="password" value="${rootPassword}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.kuang.mapper"/>
bean>
beans>
<context:property-placeholder location="db.properties"/>
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="dataSourceName" value="${mysqlDriver}"/>
<property name="jdbcUrl" value="${mysqlUrl}"/>
<property name="user" value="${root}"/>
<property name="password" value="${rootPassword}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.kuang.mapper"/>
bean>
<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.kuang.service"/>
<bean id="booksServiceImpl" class="com.kuang.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pc_tx" expression="execution(* com.kuang.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc_tx"/>
aop:config>
beans>
<context:component-scan base-package="com.kuang.service"/>
<bean id="booksServiceImpl" class="com.kuang.service.BooksServiceImpl">
<property name="booksMapper" ref="booksMapper"/>
bean>
自动装配booksMapper
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="datasource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pc_tx" expression="execution(* com.kuang.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc_tx"/>
aop:config>
<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">
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<context:component-scan base-package="com.kuang.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
bean>
beans>
/*BooksController.java*/
@Controller
@RequestMapping("/book")
public class BooksController {
@Autowired
@Qualifier("booksServiceImpl")
private BooksService booksService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = booksService.selectAllBooks();
model.addAttribute("list",list);
return "allBook";
}
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
@RequestMapping("/addBook")
public String addBook(Books book){
System.out.println(book);
booksService.addBook(book);
return "redirect:/book/allBook";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${it.bookID}|《${it.bookName}》
${it.bookCounts}
${it.detail}
——————————————————————————————————————————
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
/*BooksController.java*/
@RequestMapping("/toUpdateBook")
public String toupdateBook(int id,Model model){
Books book = booksService.selectBookById(id);
model.addAttribute("book",book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books book){
booksService.updateBook(book);
return "redirect:/book/allBook";
}
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable int id){
booksService.deleteBooksById(id);
return "redirect:/book/allBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
修改书籍信息
//BooksServiceImpl.java
@Override
/* Transaction Test
* 新增后删除
* */
public int op() {
Books newBook = new Books("Transaction Test",100,"TransactionTest");
booksMapper.addBook(newBook);
booksMapper.errorDeleteBook(14);
return 0;
}
<delete id="errorDeleteBook">
deletes from ssmBuild.books
where bookID=#{bookId};
delete>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.4version>
dependency>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pc_tx" expression="execution(* com.kuang.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc_tx"/>
aop:config>
<tx:annotation-driven transaction-manager="c3transactionManager"/>
@Transactional(readOnly=false, propagation=Propagation.REQUIRED)
AJAX:Asynchronous JavaScript And XML 异步JavaScript和XML
页面不刷新获取服务器相应的数据
XmlHttpRequest发起请求
服务器收到请求,调用相应的Servlet进行处理,生成相应的响应信息
XmlHttpRequest接收数据
<!-- JS原生AJAX -->
var xhr = new XMLHttpRequest();//创建xhr对象
xhr.open("GET","路径","true");//建立连接
xhr.send();通过地道传输数据
//监听xhr的状态
xhr.onReadyStateChange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("").innerHTML = xhr.responseText;
}
}
$('#uid').click(function(){
<!-- jquery封装AJAX -->
$.get(url, [data], [callback], [type])
//[type]一般不写
$.get("${ctp}/getInfo",{待发送的数据对象},function([存储回调数据的变量]){})
//参数用法是一样的,一个发的是POST请求,一个是GET请求
$.post(url, [data], [callback], [type])
若[type]为“json”,则jquery会自动转化为JSON对象
$.ajax({
url:"路径",
type:"GET"/"POST",//请求方式
data:{},//发送的数据
success:function(data){},
dataType:"json",//指定返回数据的类型
error:function(a,b){}//指定响应失败的处理函数
});
//禁用默认行为
return false;
})
//API
@RestController
public class AjaxController {
@RequestMapping("/ajax1")
public String ajax1(String name){
System.out.println("userName=>"+name);
if("AuspiceTian".equals(name)){
return "true";
}else{
return "false";
}
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
HTML+css+js
ES6:import、require
@RequestMapping("/ajax2")
public List<Pojo> ajax2(){
List<Pojo> list = new ArrayList<Pojo>();
list.add(new Pojo("狂神说Java",1,"男"));
list.add(new Pojo("狂神说前端",1,"女"));
list.add(new Pojo("狂神说Spring",1,"男"));
return list;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
名称
年龄
性别
过滤器
拦截器
SpringMVC框架,只有使用了SpringMVC框架的工程才能使用
拦截器只会拦截访问控制器的方法,如果访问的是jsp/html/css/image/js则不会进行拦截
自带静态资源过滤
拦截器是AOP思想的具体应用 环绕(AroundAdvice)+方法执行后(AfterAdvice)
只要实现了HandlerInterceptor即为拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.kuang.config.MyInterceptor"/>
mvc:interceptor>
mvc:interceptors>
public class MyInterceptor implements HandlerInterceptor {
/*
* return true:执行下一个拦截器,放行
* return false:拦截请求,返回首页
* */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("============所有页面的拦截器==========");
response.sendRedirect(request.getContextPath()+"/index.jsp");
return false;
}
/*
* 主要用作日志功能
* */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("==============日志功能============");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("================清理日志=============");
}
}
前端表单要求:
只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.3version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
注意!!!这个bena的id必须为:multipartResolver , 否则上传文件会报400的错误!
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
bean>
CommonsMultipartFile 的 常用方法:
package com.chen.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@Controller
public class FileController {
//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file ,HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//文件输出流
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
}
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
文件下载步骤:
1、设置 response 响应头
2、读取文件 — InputStream
3、写出文件 — OutputStream
4、执行操作
5、关闭流 (先开后关)
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request)throws Exception{
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "基础语法.jpg";
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
点击下载