MVC
?它是一种开发模式,它是模型视图控制器的简称。所有的web
应用都是基于MVC
开发的
M
: 模型层,它是模型视图控制器的简称。所有的web
应用都是基于MVC
开发
V
: 视图层,html、javascript、vue
等都是视图层,用来显示数据
C
: 控制器,它是用来接受客户端的请求,并返回响应到客户端的组件,Servlet
就是组件
MVC
的框架IoC
和AOP
maven
项目,选择模板webapp
创建项目 |
---|
添加java目录... ,webapp 目录配置 |
---|
pom.xml
,添加SpringMVC、Servlet
的依赖<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>springmvc-001artifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.23version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>springmvc-001finalName>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.xmlinclude>
<include>**/*.propertiesinclude>
includes>
resource>
resources>
build>
project>
springmvc.xml
配置文件,指定包扫描,添加视图解析器
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<context:component-scan base-package="com.example"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/admin/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
wen.xml
文件(版本过低),新建web.xml
web.xml |
---|
web.xml
文件中注册springmvc
框架(所有的web
请求都是基于servlet
的)
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
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>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.actionurl-pattern>
servlet-mapping>
web-app>
index.jsp
,并新建,发送请求给服务器
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
访问 main
webapp
目录下新建admin
目录(根据配置文件中的需要添加),在admin/admin.jsp
,删除index.jsp
,并新建
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Admin-Page
show admin.............................
Servlet
),它是一个普通的类package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MainController {
@RequestMapping("/main.action")
public String main() {
return "admin";
}
}
Tomcat
启动测试测试请求 |
---|
注意点
在这些步骤的前提下,如果访问出现404
,那么进行IDEA
缓存清除,重新构建,再次启动测试
项目目录结构
当前目录结构 |
---|
<%-- 单个提交数据 --%>
<form action="/user.do" method="post">
<input type="text" name="myname">
<input type="number" name="age">
<input type="submit" value="提交">
form>
@RequestMapping("/user.do")
public String user(String myname, int age) {
System.out.println(myname + " " + (age + 10));
return "admin";
}
// 实体类
package com.example.entity;
import lombok.Data;
@Data
public class User {
private String username;
private Integer age;
}
@RequestMapping("/pojo.do")
public String user(User user) {
System.out.println(user.getUsername() + " " + (user.getAge() + 10));
return "admin";
}
<%-- 2. 对象封装提交 --%>
占位符
@RequestMapping("/test/{username}/{age}.do")
public String TestDo(@PathVariable("username") String username, @PathVariable("age") int age) {
System.out.println(username + (age));
return "admin";
}
// 通过 @RequestParam 将 username 注给 uname
@RequestMapping("/nomapping.do")
public String NoMapping(
@RequestParam("username")
String uname,
@RequestParam("age")
int ahe
) {
System.out.println(uname + " " + (ahe));
return "admin";
}
web.xml
中配置过滤器,建议写在顶部<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
String
: 客户端资源的地址,自动拼接前缀和后缀,还可以屏蔽自动拼接字符串,可以指定返回的路径Object
: 返回json
格式的对象。自动将对象或集合转为json
,使用jackson
工具进行转换,必须要添加jackson
依赖。一般用于ajax
请求void
: 无返回值,一般用于ajax
请求ajax
请求ModelAndView
: 返回数据和视图对象,现在用的很少jackson
依赖<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.4.2version>
dependency>
webapp
目录下新建js
目录,添加axios
函数库<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>
index.jsp
页面上导入函数库<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
action
上添加注解@ResponseBody
,用来处理ajax
请求package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Controller
public class UserController {
@ResponseBody
@RequestMapping("/list.do")
public List<String> list() {
List<String> list = new ArrayList<>();
Collections.addAll(list, "aa", "bb", "cc", "dd");
return list;
}
}
springmvc.xml
文件中添加注解驱动
,用它来解析@RespinseBody
注解
<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="http://www.springframework.org/schema/beans"
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.example"/>
<mvc:annotation-driven/>
beans>
控制台输出 |
---|
要使用注解@DateTimeFormat
,此注解必须搭配springmvc.xml
中的
package com.example.controller;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class DateController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@RequestMapping("/mydate.do")
public String myDate(
@DateTimeFormat(pattern = "yyyy-MM-dd")
Date mydate) {
System.out.println(sdf.format(mydate));
return "admin";
}
}
package com.example.controller;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class DateController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 注册一个全局的日期处理注解
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
@RequestMapping("/mydate.do")
public String myDate(Date mydate) {
System.out.println(sdf.format(mydate));
return "admin";
}
}
如果一个类的成员属性是日期格式
,可以在类的成员 setXX
添加注解 @DateTimeFormat(pattern = "yyyy-MM-dd")
如果是json
类型,需要在类中
的成员变量getXXX
方法上添加注解@JsonFormat(pattern="yyyy-MM-dd")
此目录下的动态资源,不可以直接访问,只能通过请求转发的方式进行访问
修改springmvc.xml
配置
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
WEB-INF/main
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebInfController {
@RequestMapping("/showMain.do")
public String showMain() {
return "main";
}
}
针对请求和响应进行的额外处理。在请求和响应的过程中添加预处理,后处理和最终处理
拦截器的执行时机
preHandle
: 在请求被处理之前进行操作
postHandle
: 在请求被处理之后,但结果还没有渲染前进行操作,可以改变响应结果
afterCompletion
: 所有的请求响应结束后执行善后工作,清理对象,关闭资源
拦截器实现的两种方式
集成HandlerIntercepterAdpater
的父类
实现HandlerInterceptor
接口【推荐使用实现接口的方式】
登录拦截器实现的步骤
改造登录方法,在session
中存储用户信息,用于进行权限验证
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class WebInfController {
@RequestMapping("/showLogin")
public String showLogin() {
return "login";
}
@RequestMapping("/main.do")
public String showMain(String username, String password, HttpServletRequest request) {
if ("coder-itl".equalsIgnoreCase(username) && "coder-itl".equalsIgnoreCase(password)) {
request.getSession().setAttribute("username", username);
return "main";
} else {
request.setAttribute("msg", "用户名和密码错误");
return "login";
}
}
}
开发拦截器的功能,实现HandlerInterceptor
接口,重写preHandle
方法
package com.example.intercepter;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// TODO: 无法实现跳转
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession().getAttribute("username") == null) {
// 没有登陆
request.setAttribute("msg", "您还未登录,请先登录!");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
// 登录成功放行
return true;
}
}
在springmvc.xml
文件中注册拦截器
<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="http://www.springframework.org/schema/beans"
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.example"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:annotation-driven/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/showLogin"/>
<mvc:exclude-mapping path="/main.do"/>
<bean class="com.example.intercepter.LoginInterceptor"/>
mvc:interceptor>
mvc:interceptors>
beans>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>spring-ssmartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8maven.compiler.encoding>
<java.version>1.8java.version>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<junit.version>4.12junit.version>
<spring.version>5.1.2.RELEASEspring.version>
<mybatis.version>3.2.8mybatis.version>
<mybatis.spring.version>1.2.2mybatis.spring.version>
<mybatis.paginator.version>1.2.15mybatis.paginator.version>
<mysql.version>8.0.22mysql.version>
<slf4j.version>1.6.4slf4j.version>
<druid.version>1.0.9druid.version>
<pagehelper.version>5.1.2pagehelper.version>
<jstl.version>1.2jstl.version>
<servlet-api.version>3.0.1servlet-api.version>
<jsp-api.version>2.0jsp-api.version>
<jackson.version>2.9.6jackson.version>
<loback.version>1.2.11loback.version>
<lombok.version>1.18.24lombok.version>
properties>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.11version>
dependency>
<dependency>
<groupId>org.jsongroupId>
<artifactId>jsonartifactId>
<version>20140107version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency><project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>spring-ssmartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8maven.compiler.encoding>
<java.version>1.8java.version>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<junit.version>4.12junit.version>
<spring.version>5.1.2.RELEASEspring.version>
<mybatis.version>3.2.8mybatis.version>
<mybatis.spring.version>1.2.2mybatis.spring.version>
<mybatis.paginator.version>1.2.15mybatis.paginator.version>
<mysql.version>8.0.22mysql.version>
<slf4j.version>1.6.4slf4j.version>
<druid.version>1.0.9druid.version>
<pagehelper.version>5.1.2pagehelper.version>
<jstl.version>1.2jstl.version>
<servlet-api.version>3.0.1servlet-api.version>
<jsp-api.version>2.0jsp-api.version>
<jackson.version>2.9.6jackson.version>
<loback.version>1.2.11loback.version>
<lombok.version>1.18.24lombok.version>
properties>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.11version>
dependency>
<dependency>
<groupId>org.jsongroupId>
<artifactId>jsonartifactId>
<version>20140107version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jmsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis.spring.version}version>
dependency>
<dependency>
<groupId>com.github.miemiedevgroupId>
<artifactId>mybatis-paginatorartifactId>
<version>${mybatis.paginator.version}version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>${pagehelper.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>${jstl.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<scope>providedscope>
<version>${jsp-api.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.28version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.2.11version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.2.11version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.3.23version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
plugin>
plugins>
<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>
project>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jmsartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>${mybatis.spring.version}version>
dependency>
<dependency>
<groupId>com.github.miemiedevgroupId>
<artifactId>mybatis-paginatorartifactId>
<version>${mybatis.paginator.version}version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>${pagehelper.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>${jstl.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<scope>providedscope>
<version>${jsp-api.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.28version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>${loback.version}version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${lombok.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.3.23version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
plugin>
plugins>
<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>
project>
添加缺失目录java,resources
更换高版本的web.xml
在resources
目录下创建jsbc.properties
# 5.7
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmuser?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
# 8.0
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmuser?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true
jdbc.username=root
jdbc.password=root
mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J"/>
settings>
<typeAliases>
<package name="com.example.entity"/>
typeAliases>
<mappers>
<package name="com.example.mapper"/>
mappers>
configuration>
spring-service.xml
文件
<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">
beans>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
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/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.example"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<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.example.mapper"/>
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myDataSource"/>
bean>
<tx:advice id="myAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*select*" read-only="true"/>
<tx:method name="*find*" read-only="true"/>
<tx:method name="*get*" read-only="true"/>
<tx:method name="*search*" read-only="true"/>
<tx:method name="*insert*" propagation="REQUIRED"/>
<tx:method name="*save*" propagation="REQUIRED"/>
<tx:method name="*add*" propagation="REQUIRED"/>
<tx:method name="*delete*" propagation="REQUIRED"/>
<tx:method name="*remove*" propagation="REQUIRED"/>
<tx:method name="*clear*" propagation="REQUIRED"/>
<tx:method name="*update*" propagation="REQUIRED"/>
<tx:method name="*modify*" propagation="REQUIRED"/>
<tx:method name="*change*" propagation="REQUIRED"/>
<tx:method name="*set*" propagation="REQUIRED"/>
<tx:method name="*" propagation="SUPPORTS"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="myPointCut" expression="execution(* com.example.service.impl.*.*(..))"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="myPointCut"/>
aop:config>
beans>
spring-mvc.xml
<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="http://www.springframework.org/schema/beans"
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.xsd">
<context:component-scan base-package="com.example"/>
<mvc:annotation-driven/>
beans>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:spring-service.xmlparam-value>
context-param>
web-app>
package com.example.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class User implements Serializable {
private String userId;
private String cardType;
private String cardNo;
private String userName;
private String userSex;
private String userAge;
private String userRole;
}
service,impl
// service
package com.example.service;
import com.example.entity.User;
import java.util.List;
public interface UserService {
List<User> selectUserPage(String userName, String userSex, int startRow);
int createUser(User user);
int deleteUserById(String userId);
int getRowCount(String userName, String userSex);
}
// serviceImpl
package com.example.service.impl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectUserPage(String userName, String userSex, int startRow) {
return userMapper.selectUserPage(userName, userSex, startRow);
}
@Override
public int createUser(User user) {
return userMapper.createUser(user);
}
@Override
public int deleteUserById(String userId) {
return userMapper.deleteUserById(userId);
}
@Override
public int getRowCount(String userName, String userSex) {
return userMapper.getRowCount(userName, userSex);
}
}
mapper
映射文件
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="userMap" type="user">
<id property="userId" column="user_id"/>
<result property="cardType" column="card_type"/>
<result property="cardNo" column="card_no"/>
<result property="userName" column="user_name"/>
<result property="userSex" column="user_sex"/>
<result property="userAge" column="user_age"/>
<result property="userRole" column="user_role"/>
resultMap>
<sql id="allColumns">
user_id
,
card_type,
card_no,
user_name,
user_sex,
user_age,
user_role
sql>
<select id="selectUserPage" resultMap="userMap">
select
<include refid="allColumns"/>
from user
<where>
<if test="userName!=null and userName!=''">
and user_name like concat('%',#{userName},'%')
if>
<if test="userSex!=null and userSex!=''">
and user_sex=#{userSex}
if>
where>
limit #{startRow},5
select>
<insert id="createUser" parameterType="user">
insert into user
values (#{userId}, #{cardType}, #{cardNo}, #{userSex}, #{userAge}, #{userRole})
insert>
<delete id="deleteUserById" parameterType="string">
delete
from user
where userId = #{userId}
delete>
<select id="getRowCount" resultType="integer">
select count(*)
from user
<where>
<if test="userName!=null and userName!=''">
and user_name like concat('%',#{userName},'%')
if>
<if test="userSex!=null and userSex!=''">
and user_sex=#{userSex}
if>
where>
select>
mapper>
// spring-service.xml 是 spring 管理 service,dao 相关的对象
public class UserServiceTest {
@Test
public void selectUserPageTest() {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-service.xml");
UserService userService = ac.getBean("userService", UserService.class);
int rowCount = userService.getRowCount(null, "男");
System.out.println(rowCount);
}
}
测试整合是否有效 |
---|