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:
*注: 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
...
...
...
...
在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
}
5. 配置 SpringMVC 和 Data source
1) 修改 src/main/webapp/WEB-INF/web.xml
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
...
...
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
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">
6. 用 HibernateDao 连接数据库
1) 修改 src/main/resources/springmvc-beans.xml
...
...
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
return this.getSessionFactory().openSession().createSQLQuery("SELECT * FROM user").addEntity(User.class).list();
}
}
7. 用 JdbcDao 连接数据库
1) 修改 src/main/resources/springmvc-beans.xml
...
...
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
List
new RowMapper
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
...
...
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"%>
Demo
通过 (Jdbc Dao) 创建用户数据表
通过 (Hibernate Dao) 注册用户
|
3) 添加 src/main/webapp/WEB-INF/jsp/success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
Success Page
Message: ${message}
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
...
...
2) 添加 src/main/webapp/static/test.html
Static HTML Page - Test
访问 http://localhost:9090/static/test.html
3) JS/CSS/Images 和 html类似
略