建立maven+springMVC项目
project name和artifactId一致
添加一个键值对
archetypeCatalog
internal
出现build success maven创建完成
pom.xml导入springMVC依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
建立springmvc.xml文件在resources里(日期转换器是后期用到时候配的)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
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">
<!-- 开启注解扫描-->
<context:component-scan base-package="cn.hxy"></context:component-scan>
<!-- 视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置日期转化器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.hxy.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!-- 开启springMVC框架支持的注解,可以使处理器,映射器等生效-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
</beans>
配置DispatcherServlet在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>
<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:springmvc.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>
</web-app>
在main路径下建立Java和resources
日期转换器(输入2020-01-01格式不报错)
建立一个工具类
package cn.hxy.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
if(source==null){
throw new RuntimeException("请传入数据");
}
DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
try {
//把字符串转化成日期
return df.parse(source);
}catch (Exception e){
throw new RuntimeException("数据类型转出出现错误");
}
}
}
springmvc.xml里面配置
<!-- 配置日期转化器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="cn.hxy.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!-- 开启springMVC框架支持的注解,可以使处理器,映射器等生效-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
<%--
Created by IntelliJ IDEA.
User: Hxy
Date: 2020/4/18
Time: 12:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--自定义类型转换器--%>
<form action="param/saveUser" method="post">
用户的姓名:<input type="text" name="uname"><br>
用户的年龄:<input type="text" name="age"><br>
用户的生日:<input type="text" name="date"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
package cn.hxy.control;
import cn.hxy.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/param")
public class Control {
/**
* 自定义类型转换器
* @param user
* @return
*/
@RequestMapping("/saveUser")
public String saveUser(User user){
System.out.println("saveUser 执行了。。。");
System.out.println(user);
return "success";
}
}
package cn.hxy.domain;
import java.util.Date;
public class User {
private String uname;
private Integer age;
private Date date;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "User{" +
"uname='" + uname + '\'' +
", age=" + age +
", date=" + date +
'}';
}
}
常用注解和属性
主要代码
<%--
Created by IntelliJ IDEA.
User: Hxy
Date: 2020/4/18
Time: 12:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--自定义类型转换器--%>
<form action="param/saveUser" method="post">
用户的姓名:<input type="text" name="uname"><br>
用户的年龄:<input type="text" name="age"><br>
用户的生日:<input type="text" name="date"><br>
<input type="submit" value="提交">
</form>
<a href="param/testPathVariable/20">testPathVariable</a><br>
<a href="param/testCookieValue">testCookieValue</a><br>
<form action="param/testModelAttribute1" method="post">
用户的姓名:<input type="text" name="uname"><br>
用户的年龄:<input type="text" name="age"><br>
<input type="submit" value="提交">
</form>
<br>
<a href="param/testSessionAttributes">setSessionAttributes</a><br>
<a href="param/getSessionAttributes">getSessionAttributes</a><br>
<a href="param/delSessionAttributes">delSessionAttributes</a><br>
</body>
</html>
package cn.hxy.control;
import cn.hxy.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import java.util.Date;
import java.util.Map;
@Controller
@RequestMapping("/param")
@SessionAttributes("msg") //把msg=美美存到session域中
public class Control {
/**
* 自定义类型转换器
* @param user
* @return
*/
@RequestMapping("/saveUser")
public String saveUser(User user){
System.out.println("saveUser 执行了。。。");
System.out.println(user);
return "success";
}
/**
* 注解PathVariable
* @param id
* @return
*/
@RequestMapping("/testPathVariable/{sid}")
public String testPathVariable(@PathVariable("sid") String id){
System.out.println("saveUser 执行了。。。");
System.out.println(id);
return "success";
}
/**
* 注解CookieValue
* @param cookieValue
* @return
*/
@RequestMapping("/testCookieValue")
public String testCookValue(@CookieValue(value = "JSESSIONID") String cookieValue){
System.out.println("testCookValue 执行了。。。");
System.out.println(cookieValue);
return "success";
}
/**
* 注解testModelAttribute,对应有返回值的情况
* @param
* @return
*/
@RequestMapping("/testModelAttribute")
public String testModelAttribute(User user){
System.out.println("testModelAttribute 执行了。。。");
System.out.println("testModelAttribute"+user);
return "success";
}
/**
* 改方法会在触发方法之前先执行
* 这个方法中的数据会覆盖原来数据
*
* 有返回值的情况
* @param uname
* @return
*/
@ModelAttribute
public User showUser(String uname){
User user = new User();
user.setUname(uname);
user.setAge(12);
user.setDate(new Date());
System.out.println("showUser:"+user);
System.out.println("showUser执行了。。");
return user;
}
/**
* 注解ModelAttribute,对应没有返回值的情况
* @param user
* @return
*/
@RequestMapping("/testModelAttribute1")
public String testModelAttribute1(@ModelAttribute("abc") User user){
System.out.println("testModelAttribute 执行了。。。");
System.out.println("testModelAttribute"+user);
return "success";
}
/**
* 注解ModelAttribute,对应没有返回值的情况
* @param uname
* @param map
* @return
*/
@ModelAttribute
public User showUser1(String uname, Map<String,User> map){
User user = new User();
user.setUname(uname);
user.setAge(15);
user.setDate(new Date());
map.put("abc",user);
System.out.println("showUser 1 :"+user);
System.out.println("showUser 1 执行了。。");
return user;
}
/**
* 注解SessionAttributes必须写在类上,
* 此方法设置值
* @param model
* @return
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Model model){
System.out.println("testSessionAttributes 执行了。。。");
//底层会存储到request域对象中
model.addAttribute("msg","guy");
return "success";
}
/**
*此方法获取注解SessionAttributes的值
* @param modelMap
* @return
*/
@RequestMapping("/getSessionAttributes")
public String getSessionAttributes(ModelMap modelMap){
System.out.println("getSessionAttributes 执行了。。。");
//底层会存储到request域对象中
String msg = (String)modelMap.get("msg");
System.out.println("getSessionAttributes域中获取msg值:"+msg);
return "success";
}
/**
* 清除SessionAttributes
* @param status
* @return
*/
@RequestMapping("/delSessionAttributes")
public String delSessionAttributes(SessionStatus status){
System.out.println("delSessionAttributes 执行了。。。");
status.setComplete();
return "success";
}
}
<%--
Created by IntelliJ IDEA.
User: Hxy
Date: 2020/4/18
Time: 12:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>成功</title>
</head>
<body>
<h2>Hello World!</h2>
入门成功
<%-- request域--%>
${requestScope.msg}
<%-- session域--%>
${sessionScope}
</body>
</html>
Model
response.jsp页面
<a href="user/testString">testString</a><br>
<a href="user/testVoid">testVoid</a><br>
Controller类
package cn.hxy.controller;
import cn.hxy.domain.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 javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 返回值类型是字符串
* @param model
* @return
*/
@RequestMapping("/testString")
public String testString(Model model){
//模拟从数据库里面查数据
System.out.println("testString....");
User user = new User();
user.setUsername("hxy");
user.setAge(18);
user.setPassword("123");
model.addAttribute("user",user);
return "success";
}
/**
* 返回值类型是void
*/
@RequestMapping("testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid..");
//请求转发
// request.getRequestDispatcher("/pages/success.jsp").forward(request,response);
//重定向
// response.sendRedirect("/pages/success.jsp");
//设置中文乱码
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("你好");
}
}
ModelAndView
response.jsp
<body>
<a href="user/testModelAndView">testModelAndView</a> //本次测试这个
</body>
UserController.java
/**
* 返回ModelAndView
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView modelAndView = new ModelAndView();
//模拟从数据库里面查数据
System.out.println("testModelAndView....");
User user = new User();
user.setUsername("hxy");
user.setAge(18);
user.setPassword("123");
modelAndView.addObject("user",user);
modelAndView.setViewName("success");
return modelAndView;
}
success.jsp是一个纯显示页面,ModelAndView和Model会用到视图解析器,关键字forward和redirect不会用到视图解析器
关键字forward和redirect
response.jsp页面
<a href="user/testForwardOrRedirect">testForwardOrRedirect</a> <br> 本次测试这个
UserController.java类
/**
* 用关键字的方式进行转发
* forward或者redirect
* @param
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
//模拟从数据库里面查数据
System.out.println("testForwardOrRedirect....");
//请求转发
// return "forward:/pages/success.jsp";
//重定向
return "redirect:/pages/success.jsp";
}
配置静态资源路径以及响应json数据发送ajax请求
需要在springmvc.xml文件配置静态资源的路径,为了的是告诉前端控制器DispatcherServlet不要拦截静态资源
首先:在webapp下面建立文件夹js
其次在springmvc.xml添加代码,这里css.images配置是为了以后用的
<!-- 前端控制器,哪些静态资源不拦截-->
<mvc:resources mapping="/js/**" location="/js/**"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/**"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/**"></mvc:resources>
再再次,在pom上面添加依赖
<!-- json用到的依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
response.jsp页面内容
<%--
Created by IntelliJ IDEA.
User: Hxy
Date: 2020/4/19
Time: 19:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>response</title>
<script src="js/jquery.min.js"></script>
<script>
//页面加载,绑定单击事件
$(function(){
$("#btn").click(function () {
//返送ajax请求
$.ajax({
//编写json格式,设置属性和值
url:"user/testAjax",
contentType:"application/json;charset=utf-8",
data:'{"username":"hxy","password":"123","age":30}',
dataType:"json",
type:"post",
success:function (data) {
//data:服务器响应的json数据,进行解析
alert(data);
alert(data.username);
alert(data.password);
alert(data.age);
}
});
});
});
</script>
</head>
<body>
<%--异步请求--%>
<button id="btn">发送ajax的请求</button><br> 本次测试这个
</body>
</html>
UserController.java类中方法代码
/**
* 模拟异步请求响应
* @RequestBody是获得请求体,这里的请求体是传过来Jason字符串:
* data:'{"username":"hxy","password":"123","age":30}'
* @ResponseBody是讲User封装成json对象,返回给页面
* @param user
*/
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
//客户端发送ajax,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
//做响应模拟查询数据库
user.setUsername("hhh");
user.setAge(40);
user.setPassword("123");
System.out.println("testAjax.........");
return user;
}
ps:如果最开始没有配置静态路径在springmvc.xml,后面配置完了也不好使,那就在本地找到这个项目,删除target文件夹,从新restart服务器就能解决
springMVC处理异常请求
一般情况如果dao层有异常,会往service层抛,service有异常会往Controller控制器抛,Controller类有异常会往DispatcherServlet控制器里面抛,如果控制器不做处理就会忘用户界面抛,如下图
首先自定义异常类
package cn.hxy.exception;
/**
* 自定义异常类
*/
public class SysException extends Exception {
private String message;
public SysException(String message) {
this.message = message;
}
public SysException() {
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
其次编写异常处理器
package cn.hxy.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
*处理异常业务逻辑
* @param httpServletRequest
* @param httpServletResponse
* @param o 当前处理器的对象
* @param e Controller抛出来的异常对象
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) {
System.out.print("1231323");
// 获取异常对象
SysException exception = null;
// 如果e是SysException类型就强转,不是的话就new一个
if (e instanceof SysException){
exception = (SysException) e;
}else{
exception = new SysException();
exception.setMessage("系统正在维护");
}
//创建ModelAndView设置值并且跳转error页面
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("errorMsg",e.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
再次配置异常处理器,在springMVC中
<!-- 配置异常处理器-->
<bean id="sysExceptionResolver" class="cn.hxy.exception.SysExceptionResolver" />
response.jsp页面
<body>
<a href="user/testException">testException</a><br>
</body>
UserController.java类
package cn.hxy.controller;
import cn.hxy.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws Exception {
System.out.println("testException...");
try {
// 模拟异常
int i=1/0;
}catch (Exception e){
e.printStackTrace();
//抛出自己定义异常
throw new SysException();
}
return "success";
}
}
显示结果
拦截器
拦截器:在controller执行之前拦截,在controller类返回之后也拦截
拦截链:有多个拦截器,如下图
拦截器和过滤器的功能比较类似,有区别
- 过滤器是Servlet规范的一部分,任何框架都可以使用过滤器技术。
- 拦截器是SpringMVC框架独有的。
- 过滤器配置了/*,可以拦截任何资源。
- 拦截器只会对控制器中的方法进行拦截。
代码环节:
首先编写拦截器1号
package cn.hxy.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
/**
* 预处理,在controller之前执行
* return true:放行,执行下一个拦截器,如果没有拦截器,执行Controller
* return false:不放行
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("preHandle...");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterHandle...");
}
}
拦截器2号
package cn.hxy.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor1 implements HandlerInterceptor {
/**
* 预处理,在controller之前执行
* return true:放行,执行下一个拦截器,如果没有拦截器,执行Controller
* return false:不放行
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("preHandle...2222");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...2222");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterHandle...2222");
}
}
springmvc配置拦截器
<!-- 配置拦截器-->
<mvc:interceptors>
<!-- 配置一个拦截器-->
<mvc:interceptor>
<!-- 要拦截的方法-->
<mvc:mapping path="/user/**"/>
<!-- 不要拦截的方法,和mvc:mapping算上,这俩配置一个就可
<mvc:exclude-mapping path=""/>-->
<!-- 配置拦截器对象-->
<bean id="myInterceptor" class="cn.hxy.interceptor.MyInterceptor"></bean>
</mvc:interceptor>
<!-- 配置第2个拦截器-->
<mvc:interceptor>
<!-- 要拦截的方法-->
<mvc:mapping path="/**"/>
<!-- 不要拦截的方法,和mvc:mapping算上,这俩配置一个就可
<mvc:exclude-mapping path=""/>-->
<!-- 配置拦截器对象-->
<bean id="myInterceptor1" class="cn.hxy.interceptor.MyInterceptor1"></bean>
</mvc:interceptor>
</mvc:interceptors>
response.jsp页面
<body>
<a href="user/testInterceptor">testInterceptor</a><br>
</body
UserController .java类
package cn.hxy.controller;
import cn.hxy.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testInterceptor")
public String testInterceptor() {
System.out.println("testInterceptor...");
return "success";
}
}
浏览器执行界面
控制台执行界面:
preHandle…
preHandle…2222
testInterceptor…
postHandle…2222
postHandle…
success执行了…
afterHandle…2222
afterHandle…
整合SSM
以spring框架为主要,去整合springmvc和mybatis
先配置spring框架,配置pom.xml引入jar包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<!-- aop begin-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- aop end-->
<!-- springMvc begin-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<!-- springMvc end-->
<!-- 单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- 单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- servlet/jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- el表达式-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency><dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
<!-- 连接池-->
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
新建applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 开启扫描,希望处理service和dao,controller不需要spring框架去处理-->
<context:component-scan base-package="cn.hxy">
<!-- 配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
编写代码,测试spring的配置情况
package cn.hxy.dao;
import cn.hxy.domain.Account;
import java.util.List;
/**
* 账户dao接口
* 只要写接口就行,mybatis可以生成一个代理对象执行,不用写实现类
*/
public interface IAccountDao {
//查询所有账户
public List<Account> findAll();
//保存账户信息
public void saveAccount(Account account);
}
package cn.hxy.domain;
import java.io.Serializable;
/**
* 账户
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
package cn.hxy.service;
import cn.hxy.domain.Account;
import java.util.List;
/**
* 业务层接口
*/
public interface IAccountService {
//查询所有账户
public List<Account> findAll();
//保存账户信息
public void saveAccount(Account account);
}
package cn.hxy.service.impl;
import cn.hxy.domain.Account;
import cn.hxy.service.IAccountService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 业务实现层
*/
@Service("accountService")
public class AccountService implements IAccountService {
public List<Account> findAll() {
System.out.println("业务层:查询所有接口");
return null;
}
public void saveAccount(Account account) {
System.out.println("业务层:保存账户接口");
}
}
package cn.hxy;
import cn.hxy.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
// 加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象
IAccountService as = (IAccountService) ac.getBean("accountService");
// 调用方法
as.findAll();
}
}
打印结果:
业务层:查询所有接口
表示spring配置完成,开始配置springmvc框架:
和springmvc有关的结构图:
新建springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
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">
<!-- 开启注解扫描,只扫描controller注解-->
<context:component-scan base-package="cn.hxy.controller">
<!-- 另一种写法-->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
</context:component-scan>
<!-- 配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 过滤静态资源-->
<mvc:resources mapping="/js/**" location="/js/**"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/**"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/**"></mvc:resources>
<!-- 开启springmvc注解的支持-->
<mvc:annotation-driven/>
</beans>
web.xml配置,过滤器要放在前端控制器前面配置,要不容易报错
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 解决中文乱码的过滤器-->
<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>
<servlet>
<!-- 配置前端控制器-->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载springmvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器,创建该servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<body>
<a href="account/findAll">testFindAll</a>
</body>
AccountController .java
package cn.hxy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* web层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有账户");
return "list";
}
}
list.jsp
<body>
<h1>查询了所有的项目</h1>
</body>
配置Tomcat服务器,springmvc配置成功界面:
spring整合springmvc:
这里的监听器spring已经提供好了,在web.xml里面配置添加监听器的配置
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
业务层添加注解:
/**
* 业务实现层
*/
@Service("accountService")
public class AccountService implements IAccountService {
Controller层修改代码,创建业务层对象,调用业务层方法
package cn.hxy.controller;
import cn.hxy.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* web层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层,查询所有账户");
// 调用service方法
accountService.findAll();;
return "list";
}
}
点击index.jsp页面链接测试spring整合springmvc结果
控制台打印结果:
表现层,查询所有账户
业务层:查询所有接口