环境:
框架:Spring + SpringMVC + MyBatis + velocity + JQuery + Bootstrap
工具:idea、tomcat、mysql
环境:jdk1.8
一、新建工程
1. Idea新建maven-archetype-webapp工程
2. 配置maven settings.xml文件、仓库等信息
二、Spring、SpringMVC添加与配置
1. 在pom.xml文件中添加依赖
<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
这里依赖的version统一配置,在pom.xml文件中新增配置节如下:
<properties>
<spring.framework.version>4.1.2.RELEASE</spring.framework.version>
</properties>
2. webapp/WEB-INF下web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3. 工程resources目录下新建spring-config.xml、springmvc-config.xml
4. 配置spring-config.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.xxx.xxx.service,com.xxx.xxx.dao"/>
</beans>
5. 配置springmvc-config.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">
<mvc:annotation-driven/>
<context:component-scan base-package="com.xxx.xxx.controller"/>
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--<property name="prefix" value="/WEB-INF/views/" />-->
<!--<property name="suffix" value=".jsp" />-->
<!--</bean>-->
</beans>
6. 在工程中创建com.xxx.xxx.controllor、com.xxx.xxx.service包,包下分别创建XxxController.java、XxxService.java文件。
XxxControllor.java文件如下:
package com.xx.xxx.controller;
import com.xxx.xxx.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by smilefish on 2017/12/28.
*/
@Controller
public class MainController {
@Autowired
private HelloService helloService;
@RequestMapping("/index")
// @ResponseBody
public ModelAndView index() {
// return helloService.sayHello();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
modelAndView.addObject("name", "smilefish");
return modelAndView;
}
}
XxxService.java文件如下:
package com.xxx.xxx.service;
import org.springframework.stereotype.Service;
/**
* Created by smilefish on 2017/12/28.
*/
@Service
public class HelloService {
public String sayHello() {
return "Hello World! Ocean~";
}
}
三、velocity配置
1. 添加velocity依赖
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.framework.version}</version>
</dependency>
2. 配置springmvc-config.xml文件,添加以下配置节
<!-- 配置velocity引擎,通过加载配置文件的方式进行 -->
<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/templates/" /><!-- 模板存放的路径 -->
<property name="configLocation" value="/WEB-INF/velocity.properties"/>
</bean>
<!-- Velocity 视图解析器配置-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="prefix" value=""></property>
<property name="suffix" value=".vm"></property>
<property name="toolboxConfigLocation" value="/WEB-INF/toolbox.xml"></property>
<property name="dateToolAttribute" value="date"></property><!--日期函数名称-->
<property name="numberToolAttribute" value="number"></property><!--数字函数名称-->
<property name="contentType" value="text/html;charset=UTF-8"></property>
<property name="exposeSpringMacroHelpers" value="true" /><!--是否使用spring对宏定义的支持-->
<property name="exposeSessionAttributes" value="true"></property>
<property name="exposeRequestAttributes" value="true"></property>
<property name="layoutUrl" value="/layout/empty.vm"></property>
<property name="layoutKey" value="layoutPath"></property>
<property name="allowRequestOverride" value="true" />
</bean>
3. 在WEB-INF目录下添加toolbox.xml、velocity.properties文件
toolbox.xml文件如下
<?xml version="1.0" encoding="UTF-8" ?>
<toolbox>
</toolbox>
velocity.properties文件如下
velocimacro.permissions.allow.inline=true
velocimacro.permissions.allow.inline.to.replace.global=true
velocimacro.permissions.allow.inline.local.scope=true
input.encoding=UTF-8
output.encoding=UTF-8
resource.loader=webapp, class
class.resource.loader.description=Velocity Classpath Resource Loader
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path=/WEB-INF/vm/
webapp.resource.loader.cache=false
4. WEB-INF下新建vm目录,vm目录下新建index.vm文件,内容如下
<html>
<body>
<h2>Hello World! $!name</h2>
</body>
</html>
四、 tomcat配置
- DebugConfigurations配置Server路径、默认页面、启动端口、执行的war文件
- 这里运行就能访问index.vm文件并且页面显示Hello World! smilefish
五、MyBatis配置
1. 添加依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
2. spring-config.xml文件中实例化PropertyPlaceholderConfigurer,且引入dao.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.xxx.xxx.service,com.xxx.xxx.dao"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:properties/*.properties</value>
</list>
</property>
</bean>
<import resource="dao.xml" />
</beans>
3. resources目录下新建dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:mappers/*.xml" />
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sessionFactory" />
</bean>
</beans>
4. resources目录下新建mybatis-config.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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.xxx.xxx.domain.User" alias="User"/>
</typeAliases>
</configuration>
5. resources目录下添加properties目录,properties目录下新建db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xx.xx.xx.xx:3306/XXX
jdbc.username=root
jdbc.password=password
6. resources目录下添加mappers目录,mappers目录下新建User.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTO Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="User">
<resultMap id="userMap" type="User">
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
</resultMap>
<select id="selectOne" resultMap="userMap" parameterType="java.lang.String">
select id,username,password
FROM `user`
where username=#{username}
</select>
</mapper>
7. 数据库新建user表,包含列id、用户名、密码
8. 添加包com.xxx.xxx.dao,目录下新建文件UserDao.java及UserDaoUmpl.java
package com.xxx.xxx.dao;
import com.xxx.xxx.domain.User;
/**
* Created by smilefish on 2018/1/1.
*/
public interface UserDao {
/**
* 根据username查找user
* @param username
* @return
*/
User select(String username);
}
package com.xxx.xxx.dao.impl;
import com.xxx.xxx.dao.UserDao;
import com.xxx.xxx.domain.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Created by smilefish on 2018/1/1.
*/
@Component
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
public User select(String username) {
return sqlSessionTemplate.selectOne("User.selectOne", username);
}
}
9. 添加包com.xxx.xxx.domain,目录下新建文件User.java
package com.xxx.xxx.domain;
/**
* Created by smilefish on 2018/1/1.
*/
public class User {
private String username;
private String password;
private int id;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
10. 添加包com.xxx.xxx.service,目录下新建文件UserService.java
package com.xxx.xxx.service;
import com.xxx.xxx.dao.UserDao;
import com.xxx.xxx.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by smilefish on 2018/1/1.
*/
@Service
public class UserService {
@Autowired
private UserDao userDao;
public boolean match(String username, String password) {
User user = userDao.select(username);
// if (user != null)
// System.out.println(user.getUsername() + user.getPassword() + "!!!!");
return user != null && user.getPassword() != null && user.getPassword().equals(password);
}
}
六、添加JQuery、Bootstrap
1. 在webapp下新增statics目录
这里一定要放在webapp目录下与WEB-INF同级。不可放在WEB-INF目录下,否则服务启动后访问页面时,加载不到静态资源(css、js、image等)。因为WEB-INF目录下的资源只允许内部访问,外部是访问不到的。
2. 在statics目录下新增css、js、image目录
3. 在JQuery官网下载JQuery文件放到js目录下
4. 在Bootstrap官网下载Bootstrap文件放到css目录下
5. 在vm模板文件中引入JQuery
页面元素尾部且body标签中添加
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="../../../statics/js/bootstrap/bootstrap.min.js"></script>
6. 在vm模板文件中引入Bootstrap
head标签中添加
<link href="../../statics/css/bootstrap/bootstrap.min.css" rel="stylesheet">
7. 设置静态资源可被外部访问
在springmvc-config.xml文件中添加配置节
<mvc:resources mapping="/statics/**" location="/statics/" />
七、添加拦截器,结合session实现请求时登录状态校验
1. 在pom.xml中添加interceptor依赖
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
2. 在springmvc-config.xml文件中添加配置节
<!--<mvc:default-servlet-handler />-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean id="loginInterceptor" class="com.xxx.xxx.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3. 新建com.xxx.xxx.interceptor包,包下新建LoginInterceptor.java文件
package com.xxx.xxx.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by smilefish on 2018/1/3.
*/
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String url = httpServletRequest.getRequestURI().toString();
String[] allowUrls = new String[]{"/login", "/checkLogin"};
for (String strUrl : allowUrls) {
if (url.contains(strUrl)) {
return true;
}
}
HttpSession session = httpServletRequest.getSession();
String username = (String) session.getAttribute("username");
if (null != username) {
return true;
} else {
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
}
return false;
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
}
4. 在controller文件中判断登录成功时添加session存储
@RequestMapping(value = "checkLogin", method = {RequestMethod.POST})
public ModelAndView checkLogin(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
if (userService.match(username, password)) {
modelAndView.setViewName("index");
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setMaxInactiveInterval(1800);
} else {
modelAndView.setViewName("pages/login");
}
return modelAndView;
}