三层架构
从代码结构的功能上分为三层
- Dao层(data access object) 数据访问层
- Servcie 层(或者成为business) 业务层 整合dao层
- Controller 控制层 控制页面显示和跳转的
三层之间的调用关系:service调用dao层,controller层调用service层
Mvc
从代码的运行角度上栏分为mvc三层结构
- M model 数据模型层
- V view 视图层 数据显示层
- C controller 控制层
Model层相当于三层架构中的dao+service层 View 相当于jsp或者html 用于显示数据的 Controller 控制层,控制页面的跳转,可以发送和接收view的数据,相当于servlet
Springmvc
执行流程
1. Springmvc使用过程
Idea创建web项目
web.xml版本太低,至少要用web3.0以上
<?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">
</web-app >
修改项目结构,新建java和resources文件夹
运行web项目
Jsp(java server page) java的服务器页面 ,和html区别在于可以在jsp书写java代码,在运行的时候,服务器tomcat会把jsp编译成.class文件,里面的标签,css和js书写方式一模一样
可以自己创建一个jsp或者html文件,直接在浏览器中输入页面 名称访问新的页面
Springmvc入门案例
1. 导入springwebmvc的依赖
<dependencies>
<!--spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
</dependencies>
2. 配置springmvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描controller-->
<context:component-scan base-package="com.ujiuye.controller"/>
<!--配置视图解析器 ,会在controller中方法的返回值上加上前后缀-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/> <!--前缀-->
<property name="suffix" value=".jsp"/> <!--后缀-->
</bean>
</beans>
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>mvc</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>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4. 随便webapp下面创建一个jsp文件
5. 书写HelloController
@Controller
public class HelloController {
@RequestMapping("/h1")
public String hello(){
return "ok";
}
}
浏览器直接访问http://localhost:8080/day07/h1
2. 相关配置
1. 静态资源不拦截
在springmvc.xml中配置 mvc:default-servlet-handler/
2. 数据传递到前台jsp
1.导入jstl的依赖
<!-- jstl jsp标签库包 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2. 在springmvc.xml加入mvc的注解驱动
3. 创建UserBean
public class UserBean {
private int uid;
private String uname;
private String address;
//alt+insert 生成get/set/构造
public UserBean() {
}
public UserBean(int uid, String uname, String address) {
this.uid = uid;
this.uname = uname;
this.address = address;
}
}
4. HelloController
@RequestMapping("/h2")
public String h2(Model model){
UserBean u=new UserBean(1,"张三","西安");
model.addAttribute("user",u);
return "okk";
}
@RequestMapping("/h3")
public String h3(Map map){
UserBean u1=new UserBean(1,"张三","西安");
UserBean u2=new UserBean(2,"李四","宝鸡");
UserBean u3=new UserBean(3,"王五","北京");
List<UserBean> list=new ArrayList<>();
list.add(u1);
list.add(u2);
list.add(u3);
map.put("datas",list);
return "list";
}
5. 创建okk.jsp list.jsp
okk.jsp
<body>
id:${user.uid}
用户名:${user.uname}
地址:${user.address}
</body>
list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1" width="300">
<tr>
<th>编号</th>
<th>姓名</th>
<th>地址</th>
</tr>
<c:forEach items="${datas}" var="u">
<tr>
<td>${u.uid}</td>
<td>${u.uname}</td>
<td>${u.address}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
访问:
http://localhost:8080/day07/h2
http://localhost:8080/day07/h3
执行过程:
先经过controller的方法,在方法中存入了数据,再根据方法的返回值,跳转到指定jsp页面,在jsp页面中获取controller传过来的数据,所有我们在访问的时候,一定是访问controller的方法
3. Ajax做法
1. pom 导入fastjson支持
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
2. JsonController
@RestController //相当于在当前类所有的方法上面全部加上 @ResponseBody
//RestController 跳转+编码+ //相当于在当前类所有的方法上面全部加上 @ResponseBody
//Controller 跳转页面
@RequestMapping("/json/")
public class JsonController {
@RequestMapping("/h1")
// @ResponseBody //将返回值转成json格式的字符串
public UserBean c1(){
UserBean u=new UserBean(1,"张三","西安");
return u;
}
@RequestMapping("/h3")
public List<UserBean> h3(){
UserBean u1=new UserBean(1,"张三","西安");
UserBean u2=new UserBean(2,"李四","宝鸡");
UserBean u3=new UserBean(3,"王五","北京");
List<UserBean> list=new ArrayList<>();
list.add(u1);
list.add(u2);
list.add(u3);
return list;
}
}
3. Json.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax请求</title>
<script src="js/jquery.min.js"></script>
<script>
//等待网页加载完成之后执行
$(function () {
//第一种写法
/* $.ajax({
url:"json/h1", //请求路径
dataType:"json", //后台返回的数据格式,默认就是json
success:function (data) {
console.log(data)
var str="id="+data.uid+"姓名:"+data.uname+"地址:"+data.address;
$("#content").html(str);
}
});*/
//ajax的简写方法 解析对象
$.get("json/h1",function (data) {
console.log(data)
var str="id="+data.uid+"姓名:"+data.uname+"地址:"+data.address;
$("#content").html(str);
});
//解析集合
$.get("json/h3",function (data) {
console.log(data);
var str="";
/* for(var i=0;i<data.length;i++){
var user=data[i];
str+="<tr><td>"+user.uid+"</td><td>"+user.uname+"</td><td>"+user.address+"</td></tr>"
}*/
$(data).each(function (i,user) {
str+="<tr><td>"+user.uid+"</td><td>"+user.uname+"</td><td>"+user.address+"</td></tr>"
})
$("#head").after(str);
})
})
</script>
</head>
<body>
<div id="content">
</div>
<table border="1" width="300">
<tr id="head">
<th>编号</th>
<th>姓名</th>
<th>地址</th>
</tr>
</table>
</body>
</html>
直接访问json.jsp 文件
http://localhost:8080/day07/json.jsp
执行过程,直接访问页面jsp或者html,在页面中使用ajax请求controller中数据,拿到json数据直接自己解析
4. 后台接收前端传递过来参数
Get请求:直接在浏览器的地址栏中发送数据,以?参数=值&参数2=值2
Post提交,以请求体的方式提交的,在地址栏中表面上看不到
Post提交是没有数据量限制的,但是get请求一般限制大小是4K,所以提交文件的时候必须是post提交,但是get提交速度快
1. 如果碰到后台接受乱码,在web.xml中配置编码过滤器
<!--编码过滤器-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2. 创建ParamController
@Controller
@RequestMapping("/form/")
public class ParamController {
/**
* @param username 变量名一定和前端传过来拿的参数名保持一致
* @param password 变量名一定和前端传过来拿的参数名保持一致
* @return
*/
@RequestMapping("p1")
public String p1(String username,String password){
System.out.println("name=="+username+"psw=="+password);
return "ok";
}
}
3. 创建一个表单 regist.html
<form action="form/p1" method="post">
<div>
用户名:<input name="username">
</div>
<div>
密码:<input name="password">
</div>
<div>
<input type="submit" value="注册">
</div>
</form>
错误类型: 4:前端错误 404:路径错误 400:前后端参数类型不匹配 5:服务器内部错误,java方法错误 接收参数设置默认值 @RequestMapping(“p1”) public String p1(String username, @RequestParam(defaultValue = “123”) String password, @RequestParam(defaultValue = “100”) Integer id){ System.out.println(“name==”+username+”psw==”+password +”id=”+id); return “ok”; } http://localhost:8080/day07/form/p1?username=张三 对象接收参数 @RequestMapping(“p2”) public String p2(UserBean u){ System.out.println(u); return “ok”; } 访问: http://localhost:8080/day07/form/p2?uid=200&uname=admin&address=西安 前台传过来的参数名和对象中属性名保持一致
3. SSM整合
1. Pom
<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>
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring 整合Jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring面向切面编程 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl jsp标签库包 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<!--MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- MyBatis整合Spring的适配包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--引入pageHelper分页插件 PageInfo -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--MySQL-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 阿里巴巴 数据源 druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!--读取excel文件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
2. PersonBean
public class PersonBean {
private Integer pid;
private String pname;
//alt+insert 生成get/set
}
3. personDao
public interface PersonDao {
int add(PersonBean p);
int del(Integer id);
int update(PersonBean p);
List<PersonBean> findAll();
}
4. PersonService
@Service
public class PersonService {
@Autowired
private PersonDao dao;
public boolean add(PersonBean p){
return dao.add(p)>0?true:false;
}
public boolean del(Integer id){
return dao.del(id)>0?true:false;
}
public boolean update(PersonBean p){
return dao.update(p)>0?true:false;
}
public List<PersonBean> findAll(){
return dao.findAll();
}
}
5. PersonController
@RestController
@RequestMapping("/person/")
public class PersonController {
@Autowired
private PersonService service;
@RequestMapping("add")
public boolean addPerson(PersonBean p){
return service.add(p);
}
@RequestMapping("del")
public boolean delPerson(Integer pid){
return service.del(pid);
}
@RequestMapping("update")
public boolean updatePerson(PersonBean p){
return service.update(p);
}
@RequestMapping("showAll")
public List<PersonBean> showAllPerson(){
return service.findAll();
}
}
6 mybatis_conf.xml
<?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>
</configuration>
7. PersonMapper.xml
<?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.ujiuye.dao.PersonDao">
<insert id="add" parameterType="com.ujiuye.bean.PersonBean">
insert person(pname)values(#{pname})
</insert>
<delete id="del">
delete from person where pid=#{0}
</delete>
<update id="update" parameterType="com.ujiuye.bean.PersonBean">
update person set pname=#{pname} where pid=#{pid}
</update>
<select id="findAll" resultType="com.ujiuye.bean.PersonBean">
select * from person
</select>
</mapper>
8. db.properties
url=jdbc:mysql://localhost:3306/tt?characterEncoding=utf-8
driver=com.mysql.jdbc.Driver
user=root
password=123456
9. spring_core.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.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.ujiuye.service"/>
<!--读取properties配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--配置数据源-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="ds">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds"/>
<property name="configLocation" value="classpath:mybatis/mybatis_conf.xml"/>
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!--扫描dao层包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ujiuye.dao"/>
</bean>
</beans>
10. 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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring_core.xml</param-value>
</context-param>
<!--监听器,监听到服务器一旦启动,自动读取context-param的参数-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--中央控制器-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--编码过滤器-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
11. 测试:
添加:
http://localhost:8080/day07/person/add?pname=admin
删除
http://localhost:8080/day07/person/del?pid=14
修改:
http://localhost:8080/day07/person/update?pid=15&pname=王五
查询