Spring MVC开发环境的搭建和实例

时间:2021-04-12 13:00:37

一、安装jdk

二、安装tomcat

三、安装maven
  新增环境变量MAVEN-HOME,并在path变量中添加bin路径

四、安装IntelliJ IDEA

五、创建maven web项目
选择jdk,勾选create from archetype,选择org.apache.maven.archetypes:maven-archetype-webapp
maven会在后台生成web项目,需要等待,如果卡住,可参考
文章1: http://www.cnblogs.com/beiyeren/p/4566485.html
文章2:http://blog.csdn.net/cleverlzc/article/details/50864582

六、maven自动导入jar包
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zyz</groupId>
<artifactId>test1</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>test1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.spring>4.3.0.RELEASE</version.spring>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${version.spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${version.spring}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency> </dependencies>
<build>
<finalName>test1</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

七、配置 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_3_1.xsd"
version="3.1"> <!--当前的项目名-->
<display-name>mvc-test</display-name> <!--监听applicationContext-jdbc.xml文件加载-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--指定spring配置的xml文件的位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext*.xml</param-value>
</context-param> <servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!--处理中文post请求,防止出现乱码-->
<filter>
<filter-name>encodingFilter</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

八、xxx-servlet.xml(mvc-dispatcher-servlet.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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--指定注解扫描的包-->
<context:component-scan base-package="com.zyz" />
<!--处理image,js等静态资源-->
<mvc:default-servlet-handler/>
<!--开启注解-->
<mvc:annotation-driven />
<!--jsp视图解析-->
<!--<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<property name="prefix" value="/WEB-INF/jsp/"></property>-->
<!--<property name="suffix" value=".jsp"></property>-->
<!--</bean>--> <!--freemarker配置-->
<bean id="freeMarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="WEB-INF/ftl/"></property>
<property name="defaultEncoding" value="UTF-8"></property><!--支持中文必要条件1-->
</bean>
<!--freemarker视图解析-->
<bean id="ftlViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="suffix" value=".ftl"></property>
<property name="contentType" value="text/html;charset=UTF-8"></property><!--支持中文必要条件2-->
</bean>
</beans>

九、配置mysql数据库

<?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:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
"> <!--配置mysql数据库-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean> <!--jdbcTemplate和数据库关联-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref="dataSource"/>
</bean>
</beans>

十、主要代码

dao

package com.zyz.dao;

import com.zyz.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Repository; import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* Created by zyz on 2016-8-3.
*/
@Repository
public class TeacherDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Teacher> getTeachers(){
List<Teacher> teachers=new ArrayList<Teacher>();
String sql="select tno,tname,dno from teacher";
teachers=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Teacher>(Teacher.class));
return teachers;
}
public void addTeacher(Teacher teacher){
String sql="insert into teacher(tno,tname,dno) values(?,?,?)";
jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1,teacher.getTno());
ps.setString(2,teacher.getTname());
ps.setString(3,teacher.getDno());
}
});
}
}

service

package com.zyz.service;

import com.zyz.dao.TeacherDao;
import com.zyz.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; /**
* Created by zyz on 2016-8-3.
*/
@Service
public class TeacherService {
@Autowired
private TeacherDao teacherDao;
public List<Teacher> getTeachers(){
return teacherDao.getTeachers();
}
public void addTeacher(Teacher teacher){
teacherDao.addTeacher(teacher);
}
}

action

package com.zyz.action;

import com.zyz.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
* Created by zyz on 2016-8-3.
*/
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService; @RequestMapping(value = "/list",method = RequestMethod.GET)
public String listTeacher(Model model){
model.addAttribute("teachers",teacherService.getTeachers());
return "listTeacher";
} @RequestMapping(value = "/add",method = RequestMethod.GET)
public String addTeacher(){
return "addTeacher";
}
}

api

package com.zyz.api;

import com.zyz.model.Teacher;
import com.zyz.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList;
import java.util.List; /**
* Created by zyz on 2016-8-4.
*/
@RestController
@RequestMapping("/teacher")
public class TeacherApi {
@Autowired
private TeacherService teacherService;
@RequestMapping(value = "/add",method = RequestMethod.POST)
public ResponseData add(@RequestBody Teacher teacher){
List<Msg> msgs=new ArrayList<Msg>();
if(teacher.getTno()==null || teacher.getTno().equals("")){
msgs.add(new Msg("tnoMsg","工号不能为空."));
}
if(teacher.getTname()==null || teacher.getTname().equals("")){
msgs.add(new Msg("tnameMsg","姓名不能为空."));
}
if(teacher.getDno()==null || teacher.getDno().equals("")){
msgs.add(new Msg("dnoMsg","部门号不能为空."));
}
if(msgs.size()==0){
teacherService.addTeacher(teacher);
return new ResponseData(true,"添加成功.");
}else {
return new ResponseData(false,"添加失败.",msgs);
}
}
}

ajax

/**
* Created by zyz on 2016-8-2.
*/
$(function () {
// 将所有class为msg的元素内容清空,这些元素通常提示错误信息的,每次提交前都要清除,以显示本次的信息
function clearMsg() {
$(".msg").html('');
}
//获取表单数据,返回一个json对象,准备提交给服务器,注意此处json对象的属性必须和对应model对象Person的属性名保持一致
function formData() {
return {
tno:$("#tno").val(),
tname:$("#tname").val(),
dno:$("#dno").val()
};
}
function add() {
var url="/teacher/add";//通过该url找到对应api类的某个方法来接收ajax请求并作出响应(返回一个json对象)
var data=formData();//此处的data是一个json对象
clearMsg();
$.ajax({
type:'POST',//处理异步请求数据的api类@RequestMapping(value="/add",method=RequestMethod.POST)
url: url,
dataType:'json',
contentType: 'application/json',
data:JSON.stringify(data),
//将一个json对象转换成json对象字符串,因为在api中参数@RequestBody接受的是一个json对象字符串,而不是一个json对象
success:function (responseData) {//此处success是表示响应成功,即状态码为200,responseData参数表示返回的数据
if(responseData.success==true){
//ResponseData是一个json对象,是由后台类(ResponseData(success,desc,msgs)类)的对象返回到前台形成的一个json对象,
// 此处的success仅表示该json对象的一个属性,
alert(responseData.desc);
window.location.href="/teacher/list";
}else {//如果验证失败,则 显示错误信息
var msgs=responseData.msgs;
for(var i=0;i<msgs.length;i++){
$('#'+msgs[i].id).html(msgs[i].msg);
}
}
}
});
}
// 定义一个初始化的方法
function init() {
$("#add").on("click",function () {//给添加按纽绑定事件
add();
});
}
init();//调用初始化事件
})

ftl

listTeacher.ftl

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>教师列表</title>
</head>
<body>
<a href="/teacher/add">添加教师</a>
<table border="1">
<tr>
<th>工号</th>
<th>姓名</th>
<th>部门号</th>
</tr>
<#list teachers as teacher>
<tr>
<td>${teacher.tno}</td>
<td>${teacher.tname}</td>
<td>${teacher.dno}</td>
</tr>
</#list>
</table>
</body>
</html>

addTeacher.ftl

<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>添加教师</title>
<style>
.msg{
color:red;
}
</style>
</head>
<body>
工号:<input type="text" id="tno"><span id="tnoMsg" class="msg"></span><br>
姓名:<input type="text" id="tname"><span id="tnameMsg" class="msg"></span><br>
部门号:<input type="text" id="dno"><span id="dnoMsg" class="msg"></span><br>
<input type="button" id="add" value="添加">
<script src="/js/common/jquery.min.js"></script>
<script src="/js/teacher/add.js"></script>
</body>
</html>