Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,在使用Spring进行WEB开发时,也可以集成其他MVC开发框架,如 Struts等。
OS:macOS High Sierra (Version: 10.13.6)
Java, Maven,IDEA,MariaDB等安装配置过程,见 IDEA创建Maven Quickstart项目
1. 在 IDEA上创建 Maven Webapp 项目
New Project -> Project Type: Maven -> Project SDK: 1.8 -> select maven-archtype-webapp: Next
Name: MavenWebappSpringmvc
GroupId: com.example
ArtifactId: MavenWebappSpringmvc
-> Finish
生成的项目目录结构,参考IDEA创建Maven Webapp项目
2. 使用 tomcat7-maven-plugin, 将 tomcat 内嵌运行
1) 修改 pom.xml:
<project ... >
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>9090</port>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
*注: path 项目访问路径, 本例:localhost:9090, 如果配置的aa,则访问路径为localhost:9090/aa;uriEncoding 非必选项。
2) 运行
Run -> Edit configurations -> Click "+" -> Select "Maven"
Command line: clean tomcat7:run
Name: MavenWebappSpringmvc [clean,tomcat7:run]
Before Launch:
Click "+", select "Launch Web Browser"
Browser: default
Url: http://localhost:9090
-> OK
Run -> Run "MavenWebappSpringmvc [clean,tomcat7:run]"
* tomcat7 除了支持 run, 还可以支持如下 Goal:
help, deploy, deploy-only, redeploy, redeploy-only, undeploy,
exec-war, exec-war-only, run-war, run-war-only,
standalone-war, standalone-war-only, shutdown
3) 打包 War
Run -> Edit configurations -> Click "+" -> Select "Maven"
Command line: clean tomcat7:run-war
Name: MavenWebappSpringmvc [clean,tomcat7:run-war]
Before Launch:
Click "+", select "Launch Web Browser"
Browser: default
Url: http://localhost:9090
-> OK
Run -> Run "MavenWebappSpringmvc [clean,tomcat7:run-war]"
可见到 target/MavenWebappSpringmvc.war
3. 导入 Servlet, spring-*, MySQL/MariaDB, hibernate 依赖包
访问 http://www.mvnrepository.com/,查询 Servlet, spring-*, MariaDB, hibernate 等
修改 pom.xml
<project ... >
...
<dependencies>
...
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.9.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
...
</dependencies>
...
</project>
在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project
* Springmvc的核心是一个DispatcherServlet,向上溯源,DispatcherServlet 继承自HttpServlet,也就是说 DispatcherServlet 是一个 servelt。
* 这个实例 spring-web 和 springwebmvc 是必须导入,其它 spring 包,根据需要导入。
4. 数据库和实体
1) 数据库 (MySQL/MariaDB)
Database Name: testdb (创建一个新的空数据库,或使用已经存在的)
User: root
Password: 123456
Table:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`createtime` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2) 实体
添加 src/main/java/com/example/entity/User.java,路径中的目录如果不存在,就新建该目录,下同。
package com.example.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
private int id;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@Column(name = "age")
private int age;
@Column(name = "createtime")
private Date createtime;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
String strCreateTime = "";
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (createtime != null)
strCreateTime = f.format(createtime);
return "id: " + id + ", name: " + name + ", age: " + age + ", createtime: " + strCreateTime;
}
}
3) DAO
添加 src/main/java/com/example/dao/UserDao.java
package com.example.dao;
import java.util.List;
import com.example.entity.User;
public interface UserDao {
/**
* Init user table
*/
void createUserTable();
/**
* Add user
*/
void addUser(User user);
/**
* Query user
*/
List<User> listUser();
}
5. 配置 SpringMVC 和 Data source
1) 修改 src/main/webapp/WEB-INF/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>
...
<!-- Spring mvc 适配器 -->
<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-beans.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>
...
</web-app>
2) 添加 src/main/resources/config.properties
# MariaDB的配置信息
db_driverClassName=org.mariadb.jdbc.Driver
db_url=jdbc:mysql://localhost/testdb
db_username=root
db_password=123456
3) 添加 src/main/resources/springmvc-beans.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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
default-init-method="init"
default-destroy-method="destroy">
<!-- 自动扫描的包名 -->
<context:component-scan base-package="com.example"/>
<!-- 基于注解的配置 -->
<!-- <context:annotation-config/> -->
<mvc:annotation-driven />
<!-- Data source -->
<context:property-placeholder location="classpath:config.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db_driverClassName}" />
<property name="url" value="${db_url}" />
<property name="username" value="${db_username}" />
<property name="password" value="${db_password}" />
</bean>
</beans>
6. 用 HibernateDao 连接数据库
1) 修改 src/main/resources/springmvc-beans.xml
<beans ...>
...
<!-- Hibernate Dao Support -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" destroy-method="destroy">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedPackages" value="orm"/>
<property name="annotatedClasses">
<list>
<value>com.example.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="userHibernateDao" class="com.example.dao.UserHibernateDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
...
</beans>
2) 添加 src/main/java/com/example/dao/UserHibernateDaoImpl.java
package com.example.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import com.example.entity.User;
public class UserHibernateDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public void createUserTable() {
String strSql = "CREATE TABLE `user` (\r\n"
+ " `id` int(11) NOT NULL AUTO_INCREMENT,\r\n"
+ " `name` varchar(50) NOT NULL,\r\n"
+ " `password` varchar(255) NOT NULL,\r\n"
+ " `age` int(11) DEFAULT NULL,\r\n"
+ " `createtime` timestamp NULL DEFAULT NULL,\r\n"
+ " PRIMARY KEY (`id`)\r\n"
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
this.getSessionFactory().openSession().createSQLQuery(strSql);
}
/**
* Add user
*/
@Override
public void addUser(User user) {
Session session = this.getSessionFactory().openSession();
Transaction beginTransaction = session.beginTransaction();
session.persist(user);
//session.save(user);
beginTransaction.commit();
}
/**
* List all users
*/
@Override
public List<User> listUser() {
return this.getSessionFactory().openSession().createSQLQuery("SELECT * FROM user").addEntity(User.class).list();
}
}
7. 用 JdbcDao 连接数据库
1) 修改 src/main/resources/springmvc-beans.xml
<beans ...>
...
<!-- Jdbc Dao Support -->
<bean id="userJdbcDao" class="com.example.dao.UserJdbcDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
...
</beans>
2) 添加 src/main/java/com/example/dao/UserJdbcDaoImpl.java
package com.example.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Date;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.example.entity.User;
public class UserJdbcDaoImpl extends JdbcDaoSupport implements UserDao {
@Override
public void createUserTable() {
this.getJdbcTemplate().execute("CREATE TABLE `user` (\r\n"
+ " `id` int(11) NOT NULL AUTO_INCREMENT,\r\n"
+ " `name` varchar(50) NOT NULL,\r\n"
+ " `password` varchar(255) NOT NULL,\r\n"
+ " `age` int(11) DEFAULT NULL,\r\n"
+ " `createtime` timestamp NULL DEFAULT NULL,\r\n"
+ " PRIMARY KEY (`id`)\r\n"
+ ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
}
@Override
public void addUser(User user){
this.getJdbcTemplate().update("INSERT INTO user (name, password, age, createtime) VALUES (?,?,?,?)",
user.getName(),
user.getPassword(),
user.getAge(),
new Date());
}
@Override
public List<User> listUser() {
List<User> users = this.getJdbcTemplate().query("SELECT * FROM user",
new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
user.setCreatetime(rs.getDate("createtime"));
return user;
}
});
return users;
}
}
8. 数据库操作
1)配置 View 解析器
修改 src/main/resources/springmvc-beans.xml
<beans ...>
...
<!-- MVC viewResolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
...
</beans>
2) 添加 src/main/webapp/WEB-INF/jsp/demo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<h2>Demo</h2>
<hr/>
<p>通过 (Jdbc Dao) 创建用户数据表</p>
<form:form method="POST" action="/user/create/table">
<input type="submit" value="Create User Table"/>
</table>
</form:form>
<p> </p>
<hr/>
<p>通过 (Hibernate Dao) 注册用户</p>
<form:form method="POST" action="/user/register">
<table>
<tr>
<td><form:label path="name">Name:</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
3) 添加 src/main/webapp/WEB-INF/jsp/success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success Page</title>
</head>
<body>
<h3>Success Page</h3>
<p> </p>
<p>Message: ${message} </p>
<p> </p>
<p><a href="/user/demo">Back</a></p>
</body>
</html>
4) 添加 src/main/java/com/example/controller/UserController.java
package com.example.controller;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
import com.example.entity.User;
import com.example.dao.UserDao;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource(name="userHibernateDao")
private UserDao userHibernateDao;
@Resource(name="userJdbcDao")
private UserDao userJdbcDao;
@RequestMapping(value = "/demo", method = RequestMethod.GET)
public ModelAndView getRegister() {
return new ModelAndView("demo", "command", new User());
}
@RequestMapping(value = "/create/table", method = RequestMethod.POST)
public String createTable(ModelMap model) {
//
this.userJdbcDao.createUserTable();
model.addAttribute("message", "通过 (Jdbc Dao) 创建用户数据表完成");
return "success";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String postRegister(User user, ModelMap model) {
//
user.setCreatetime(new Date());
this.userHibernateDao.addUser(user);
model.addAttribute("message", "通过 (Hibernate Dao) 注册用户完成");
return "success";
}
}
访问 http://localhost:9090/user/demo/
*本实例数据库操作,没有做异常处理,请自行判断代码错误和操作错误
9. 支持静态资源访问 (html/js/css/images)
1) 修改 src/main/resources/springmvc-beans.xml
<beans ...>
...
<!-- 静态资源, 如 html,css,js,images -->
<mvc:resources location="/static/" mapping="/static/**" />
<mvc:default-servlet-handler />
...
</beans>
2) 添加 src/main/webapp/static/test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Static HTML</title>
</head>
<body>
<h3>Static HTML Page - Test</h3>
<p> </p>
</body>
</html>
访问 http://localhost:9090/static/test.html
3) JS/CSS/Images 和 html类似
略