1、新建一个maven项目,选择maven-archetpe-webapp模板。
2、配置项目名称和本地保存路径
3、配置Maven
等待项目初始化完成,大概是这个样子的
4、在src/main文件夹下面新建java文件夹和resources文件夹。
5、pom.xml文件引入依赖
spring基础包
<!--spring相关--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.18.RELEASE</version> </dependency>
持久层mybatis和mysql
<!--mybatis--> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency>
数据库事务管理
<!--数据库事务管理--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.18.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.18.RELEASE</version> </dependency>
spring和mybatis整合
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency>
jsp页面
<!--jsp--> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
数据库连接池
<dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency>
json解析
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
6、在resources目录下新建spring文件夹,并新建spring-mvc.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!--使用注解驱动--> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--重定向时,是否加上上下文路径--> <property name="redirectContextRelative" value="true"/> <!--配置解析前后缀--> <property name="prefix" value="/WEB-INF/View/"/> <property name="suffix" value=".jsp"/> </bean> <!--扫描所有handler(控制器)--> <context:component-scan base-package="com.demo.controller"/> </beans>
7、在resources目录下,新建jdbc.properties文件
#mysql驱动 driver=com.mysql.cj.jdbc.Driver #News为我本地的数据库名 url=jdbc:mysql://localhost:3306/News?useUnicode=true&serverTimezone=GMT%2B8&useSSL=false #数据库登录用户名 username=root #下面输入自己数据库的密码 password=123456 #定义初始连接数 initialSize=1 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
8、在resources目录下新建mapper文件夹,用来保存mapper.xml映射文件,并在该文件夹下面的spring文件夹中新建spring和mybatis的整合配置文件:spring-mybatis.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.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!--自动扫描--> <context:component-scan base-package="com.demo"/> <!--引入properties文件--> <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"></property> </bean> <!--配置数据源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <!--数据库连接池--> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!--配置sqlsession工厂--> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--配置DAO所在spring会自动查找下面的类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.demo.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
9、在web.xml配置前端控制器
字符集监听器:org.springframework.web.filter.CharacterEncodingFilter
主要用来限制整个工程的字符集的。
前端控制器:org.springframework.web.servlet.DispatcherServlet
是spring用来接收用户请求的同时分配用户请求给控制器(controller)来控制请求处理
<!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 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" version="3.0" metadata-complete="true"> <display-name>Archetype Created Web Application</display-name> <!--请求和应答字符编码过滤器--> <filter> <filter-name>encoding-filter</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>encoding-filter</filter-name> <!--<url-pattern>/*</url-pattern>--> <servlet-name>springDispatcherServlet</servlet-name> </filter-mapping> <!--启动spring容器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mybatis.xml</param-value> </context-param> <!-- 用前端控制器初始化springmvc容器 --> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
10、准备数据库news表
CREATE TABLE `news` ( `id` int NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `info` longtext, `date` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
11、接下来编辑业务代码部分
准备实体News
package com.demo.pojo; import java.util.Date; public class News { private Integer id; private String name; private String info; private Date date; public News() { } public News(Integer id, String name, String info, Date date) { this.id = id; this.name = name; this.info = info; this.date = date; } 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 String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public String toString() { return "News{" + "id=" + id + ", name='" + name + '\'' + ", info='" + info + '\'' + ", date=" + date + '}'; } }
控制器NewsController
package com.demo.controller; import com.demo.pojo.News; import com.demo.service.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/news") public class NewsController { @Autowired private NewsService newsService; @GetMapping("/getNews") public ModelAndView getNews(){ List<News> newsList = newsService.getNewsList(); newsList.forEach(item -> { System.out.println(item); }); ModelAndView modelAndView = new ModelAndView("newlist"); modelAndView.addObject("newsList", newsList); return modelAndView; } }
业务层接口NewsService
package com.demo.service; import com.demo.pojo.News; import java.util.List; public interface NewsService { List<News> getNewsList(); }
业务层实现NewsServiceImpl
package com.demo.service.impl; import com.demo.dao.NewsDao; import com.demo.pojo.News; import com.demo.service.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class NewsServiceImpl implements NewsService { @Autowired private NewsDao newsDao; @Override public List<News> getNewsList() { return newsDao.getNewsList(); } }
持久层NewsDao
package com.demo.dao; import com.demo.pojo.News; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface NewsDao { List<News> getNewsList(); }
Mapper映射文件NewsMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.demo.dao.NewsDao"> <select id="getNewsList" resultType="com.demo.pojo.News"> select `id`, `name`, `info`, `date` from `news`; </select> </mapper>
在WEB-INF下面新建View文件夹,里面新建newlist.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title>新闻列表</title> </head> <body> <div> <table border="1" cellspacing="0" cellpadding="0"> <tr> <th>编号</th> <th>标题</th> <th>内容</th> <th>日期</th> </tr> <c:forEach items="${requestScope.newsList }" var="item"> <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.info}</td> <td>${item.date}</td> </tr> </c:forEach> </table> </div> </body> </html>
12、配置tomcat
把war包添加进来
13、启动测试