1:SpringMVC框架的认识
1:SpringMVC是spring的一个模块框架,专门做web开发的 2:SpringMVC开发底层是servlet,作用是servlet的功能增强 3:SpringMVC也可以把对象放到容器中管理,@Controller对象
1.1:中央调度器(DispatcherServlet)
中央调度器DispatcherServlet是Servlet对象 作用: 1:负责接收用户请求 2:扫描Controller对象 3:把请求转发给Controller对象,然后Controller对象处理请求 4:把返回结果发送到结果页面
流程图: 用户请求(index.jsp)——中央调度器(DispatcherServlet)——Controller对象 中央调度器代码实现: 1:创建web项目 2:pom.xml加入依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.12</version>
</dependency>
3:配置web.xml(声明中央调度器对象)
<?xml version="1.0" encoding="UTF-8"?>
<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>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
4:在resources文件夹下创建springmvc配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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">
<context:component-scan base-package="com.javaWeb.controller"/>
</beans>
5:创建控制器类 配置tomcat: 配置index.jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p><a href="some.do">发起some.do请求</a></p>
</body>
</html>
创建控制器类(用来处理请求):
package com.javaWeb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.setViewName("/result.jsp");
return mv;
}
}
创建识图页面(结果页面):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>msg数据:${msg}</h3>
</body>
</html>
测试:
1.2:配置识图解析器
为了防止用户跳过index.jsp直接访问some.do请求的result.jsp需要将结果页面result.jsp切换文件夹 将结果页面result.jsp放入WEB-INF文件夹下,资源保护防止直接访问result.jsp 在springmvc的配置文件中声明视图解析器:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.javaWeb.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
修改控制器的处理结果页面:
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.setViewName("result");
return mv;
}
}
1.3:转发forward/重定向redirect
使用ModelAndView的转发forward和重定向redirect来跳转页面 作用: 当文件资源不在识图解析器配置的路径内,可以使用转发和重定向到达页面(必须写完整路径) 重定向redirect:无法访问WEB-INF下的资源 转发forward:可以访问WEB-INF的资源
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.setViewName("forward:/result.jsp");
return mv;
}
}
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.setViewName("redirect:/result.jsp");
return mv;
}
使用redirect的时候发送一条请求实际处理两条请求,所以是两个request所以结果页面接收参数需要使用EL表达式:${param.参数名} 来接收参数
2:SpringMVC注解式
2.1:@RequestMapping第二种用法
@RequestMapping不但可以放在方法上面,还可以放在类上面:
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.setViewName("result");
return mv;
}
}
发起请求的主页面(发送请求使用user/some.do):
<html>
<head>
<title>Title</title>
</head>
<body>
<p><a href="user/some.do">发起some.do请求</a></p>
</body>
</html>
2.2:请求方式Method属性
@RequestMapping还有Method属性,是用来指定使用get请求处理还是post处理
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public ModelAndView doSome(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.setViewName("result");
return mv;
}
}
2.2.1:Request接收参数
Controller控制器接收参数的方式: HttpServletRequest HttpServletResponse HttpSession
需要在处理请求的方法参数上加上这三个参数:
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public ModelAndView doSome(HttpServletRequest request, HttpServletResponse response, HttpSession session){
String name = request.getParameter("name");
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.addObject("name",name);
mv.setViewName("result");
return mv;
}
}
2.2.2:接收用户提交的参数
逐个接收:
请求页面(传入的参数名name):
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="user/some.do">
姓名<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
处理页面:
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public ModelAndView doSome(String name){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.addObject("name",name);
mv.setViewName("result");
return mv;
}
}
显示结果: 对象接收:
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public ModelAndView doSome(Student student){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.addObject("name",student.getName());
mv.setViewName("result");
return mv;
}
}
2.2.3:配置过滤器设置页面编码
在web.xml文件中声明过滤器
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.2.4:@RequestParam注解
请求中的参数名和处理方法的参数名不一样时,需要使用@RequestParam注解 假如请求页面的参数是Rname:
姓名<input type="text" name="Rname">
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public ModelAndView doSome(@RequestParam(value = "Rname",required = false) String name){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","执行doSome方法");
mv.addObject("name",name);
mv.setViewName("result");
return mv;
}
}
2.3:处理请求方法的返回值
返回值ModelAndView 返回值是ModelAndView是同时处理数据(接收参数)和视图(页面跳转)的
返回值String 如果返回值只是一个跳转页面操作只需要用字符串就可以
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public String doSome(){
return "result";
}
}
返回值void 返回值void表示不做数据处理也不做视图页面跳转 主要作用是在ajax从控制器打印数据时,接收print而已
@Controller
@RequestMapping(value = "/user")
public class MyController {
@RequestMapping(value = "/some.do",method = RequestMethod.GET)
public void doSome(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
PrintWriter pw = response.getWriter();
pw.println("ajax的json数据格式");
pw.flush();
pw.close();
}
}
返回值Object 返回值Object表示返回只是数据,和视图无关 数据可以是Integer,String等基础数据类型还有合法类型等
2.3.1:用处理器的返回值实现ajax的数据接收
步骤: 1:加入依赖:加入处理json工具库的依赖,springmvc默认使用的是jackson杰克逊工具
2:在springmvc的配置文件加入<mvc:annotation-driven>注解驱动 底层原理: 注解驱动的作用是完成java对象转换成jason,xml,text,二进制等数据格式的转换 它有一个HttpMessageConverter接口,这个接口的实现类就是用来做数据格式转换的
3:在处理器方法上加入@ResponseBody注解
实现过程: 1:加入依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2:创建ajax页面(index.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="res/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function (){
$("#btn").on("click",function (){
var StuName = $("#StudentName").val();
$.ajax({
data:{
name:StuName
},
dataType:"json",
success:function (resp){
window.alert(resp.name);
},
url:"some.do"
})
})
})
</script>
</head>
<body>
<div>
姓名<input type="text" id="StudentName">
<input type="button" id="btn" value="提交">
</div>
</body>
</html>
5:在springmvc配置页面注册驱动:
<mvc:annotation-driven></mvc:annotation-driven>
4:配置处理器页面:
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
@ResponseBody
public Student doSome(String name) throws IOException {
Student student = new Student(name);
return student;
}
}
结果:
2.4:url-pattern(静态资源问题)
项目中的index.jsp(默认主页面)还有静态资源:jpg或html等都归tomcat处理(跟框架无关) 项目中的控制器处理的请求,比如*.do,*.xml,*.action等都是归springmvc框架处理的
在tomcat服务器中的web.xml配置文件中有一项配置:
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
名为default的servlet 它是处理静态资源的配置,还可以处理未映射的请求(没有在web.xml映射Mapping的servlet是未映射)
如果想用springmvc处理静态资源的话需要将tomcat的default覆盖: 在自己项目的web.xml中修改springmvc的Mapping:
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
第一种方式处理静态资源:然后在springmvc的配置文件加入标签:default-servlet-handle
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
第二种方式处理静态资源:在springmvc的配置文件加入标签resources:
<mvc:resources mapping="**" location="/res"/>
2.5:动态获取项目地址
只针对一个页面文件有效<base>标签:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>"/>
</head>
<body>
<a href="some.do"></a>
</body>
</html>
标签作用:让页面的所有href可以省去地址路径,只需要写资源名或请求就可以
3:SSM三大框架整合开发(Spring SpringMVC Mybatis)
SSM三大框架整合:spring集成Mybatis再配置springmvc 步骤:
3.1:创建项目结构
3.2:加入spring,mybatis,springmvc依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.12</version>
</dependency>
加入读取配置文件的插件:
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
3.3:创建主配置文件applicationContext,spring,springmvc,mybatis,jdbc,web.xml等配置文件
mybatis配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<package name="com.javaWeb.dao"/>
</mappers>
</configuration>
jdbc配置文件:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ccxg
name=root
password=123456
spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:conf/jdbc.properties"></context:property-placeholder>
<bean id="DataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="DataSource"></property>
<property name="configLocation" value="classpath:conf/mybatis.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.javaWeb.dao"></property>
</bean>
<context:component-scan base-package="com.javaWeb.service"></context:component-scan>
</beans>
springmvc配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context 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.javaWeb.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
主配置文件applicationContext:
<?xml version="1.0" encoding="UTF-8"?>
<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="classpath:conf/spring-web.xml"/>
<import resource="classpath:conf/spring-mvc.xml"/>
</beans>
web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<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>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
配置tomcat:
3.4:创建dao,entity,controller,service层的对象
entity:
package com.javaWeb.entity;
public class User {
private Integer id;
private String username;
private String password;
private String sex;
private String email;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
public User() {
}
public User(Integer id, String username, String password, String sex, String email) {
this.id = id;
this.username = username;
this.password = password;
this.sex = sex;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
dao:
package com.javaWeb.dao;
import com.javaWeb.entity.User;
import java.util.List;
public interface UserDao {
List<User> SelectUsers();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.javaWeb.dao.UserDao">
<select id="SelectUsers" resultType="com.javaWeb.entity.User">
select id,username,password,sex,email from usertable
</select>
</mapper>
service:
package com.javaWeb.service;
import com.javaWeb.entity.User;
import java.util.List;
public interface UserService {
List<User> SelectUsers();
}
package com.javaWeb.service.impl;
import com.javaWeb.dao.UserDao;
import com.javaWeb.entity.User;
import com.javaWeb.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao dao;
@Override
public List<User> SelectUsers() {
return dao.SelectUsers();
}
}
controller:
package com.javaWeb.controller;
import com.javaWeb.entity.User;
import com.javaWeb.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Resource
private UserService service;
@RequestMapping(value = "/selectUsers.do")
@ResponseBody
public List<User> SelectUsers(User user){
return service.SelectUsers();
}
}
3.5:创建页面并测试
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function (){
$("#btn").on("click",function (){
$.ajax({
url:"user/selectUser.do",
data:{},
dataType:"json",
success:function (resp){
$("#data").empty();
$.each(resp,function (i,e){
$("#data").append("<tr>")
.append("<td>"+e.id+"</td>")
.append("<td>"+e.username+"</td>")
.append("<td>"+e.password+"</td>")
.append("<td>"+e.sex+"</td>")
.append("<td>"+e.email+"</td>")
.append("</tr>")
})
}
})
})
})
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>编号</td>
<td>姓名</td>
<td>密码</td>
<td>性别</td>
<td>邮箱</td>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
<input type="button" id="btn" value="查询">
</div>
</body>
</html>
结果:
4:集中统一处理异常
springmvc框架采用全局统一的异常处理 把controller的所有异常都集中到一个地方处理,底层采用aop技术 需要使用的注解: @ExceptionHandler @ControllerAdvice 步骤:
4.1:创建自定义的异常类
package com.javaWeb.exception;
public class UserException extends Exception{
public UserException() {
super();
}
public UserException(String message) {
super(message);
}
}
package com.javaWeb.exception;
public class UserMessageException extends UserException{
public UserMessageException() {
super();
}
public UserMessageException(String message) {
super(message);
}
}
在controller层抛出异常:
@RequestMapping(value = "/some.do")
public ModelAndView doSome() throws UserException {
ModelAndView mv = new ModelAndView();
throw new UserMessageException("信息异常已抛出");
}
4.2:创建普通类作为全局异常处理类
package com.javaWeb.handler;
import com.javaWeb.exception.UserMessageException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class UserExceptionHandler {
@ExceptionHandler(value = UserMessageException.class)
public ModelAndView UserMessageException(Exception ex){
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
return mv;
}
@ExceptionHandler
public ModelAndView OtherException(Exception ex){
ModelAndView mv = new ModelAndView();
mv.setViewName("result");
return mv;
}
}
4.3:组件扫描器,注解驱动
<context:component-scan base-package="com.javaWeb.handler"/>
<mvc:annotation-driven/>
5:拦截器
拦截器作用是判断用户请求的权限,合法性等
5.1:创建拦截器类
package com.javaWeb.handler;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Interceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
modelAndView.setViewName("result");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
5.2:声明拦截器
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/**/"/>
<bean class="com.javaWeb.handler.Interceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/user/**/"/>
<bean class="com.javaWeb.handler.Interceptor"/>
</mvc:interceptor>
</mvc:interceptors>
拦截器的声明底层是用AarrayList集合存储的
5.3拦截器和过滤器的区别
1:过滤器是servlet中的对象,拦截器是框架中的对象 2:过滤器实现Filter接口的对象,拦截器是HandlerInterceptor 3:过滤器是用来设置request,response的参数属性的,侧重数据过滤 拦截器用来验证请求合法性,能截断请求 4:过滤器是在拦截器之前执行的 5:过滤器是tomcat服务器创建的对象,拦截器是springmvc容器中的对象 6:过滤器是一个执行时间点,拦截器是三个执行时间点 7:过滤器可以处理jsp,js,html等,拦截器是对Controller对象进行拦截,如果请求不会被中央调度器接收,那么拦截器也收不到 8:拦截器拦截普通类方法执行(Controller控制器的方法),过滤器过滤servlet请求响应
6:springmvc的执行流程(映射器的介绍)
springmvc处理流程:
1:用户发起请求:some.do
2:DispatcherServlet中央调度器接收请求some.do,把请求转交给处理器映射器 处理器映射器作用:springmvc框架中的一个对象,框架把实现了HandlerMapping接口的类叫做映射器(有很多个),框架把处理器对象放到一个叫做处理器执行链(HandlerExecutionChain)的类里保存 HandlerExecutionChain的类里保存着:处理器对象(Controller对象),拦截器(List<HandlerInterceptor>)
3:中央调度器(DispatcherServlet)把处理器映射器的HandlerExecutionChain中的处理器对象交给了处理器适配器对象(有很多个) 处理器适配器:springmvc框架的对象,实现了HandlerAdapter接口的对象 适配器作用:执行处理器方法(执行Controller对象的方法得到返回值ModelAndView)
4:中央调度器(DispatcherServlet)把处理器适配器中获取的返回值ModelAndView交给视图解析器对象 视图解析器:实现了ViewResoler接口的对象(有多个) 视图解析器作用:使用前缀后缀组成视图完整路径,然后创建view对象 View是一个接口表示视图的,在框架中的jsp,html不是String表示,而是使用View和他的实现类表示视图 比如:mv.setViewName(“result”);执行完后这个result会变成路径:/WEB-INF/jsp/result.jsp 会被转成View对象:相当于mc.setView(new ForwardView("/WEB-INF/jsp/result.jsp"));转发 InternalResourceView:视图类,表示jsp文件,视图解析器会创建InternalResourceView对象 这对象里有个属性叫url=/WEB-INF/jsp/result.jsp
5:中央调度器(DispatcherServlet)把视图解析器中创建的View对象获取到,调用View类的方法 把返回值Model数据放入request作用域中,执行对象视图的forward,请求结束。
|