1.springmvc篇
1>创建一个webapp项目(记得打勾Create from archetype)
点击下一步,填写信息,一直到finished。
项目初始状态如上图所示(名字随意,只是展示)
2>设置pom.xml(下载所有jar包)
<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.springmvc</groupId>
<artifactId>com.springmvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>com.springmvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--MongoDB驱动包-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.1.0</version>
</dependency>
<!--MongoDB核心包-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mysql driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!--mybatis spring整合-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- JDBC连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- DruidDataSource,本工程的dataSource配置使用的Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSON处理依赖包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<build>
<finalName>com.springmvc</finalName>
<plugins>
<!--mybatis 逆向工程插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3> 配置项
项目结构图
3.1> dispatcher-servlet
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 添加注解驱动 -->
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
<mvc:annotation-driven />
<!-- 默认扫描的包路径 -->
<!-- 启动包扫描功能,以便注册带有@Controller、@service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="com"/>
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/> <!-- 表示拦截所有的url包括子url路径 -->
<bean class="com.controller.interceptor.CommonInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<mvc:default-servlet-handler/>
</beans>
3.2> web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>mannix</display-name>
<!--springmvc配置-->
<servlet>
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml-->
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 设置dispatchservlet的匹配模式,通过把dispatchservlet映射到/,默认servlet会处理所有的请求,包括静态资源 -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--<!– 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 –>-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Spring配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<!--<listener>-->
<!--<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>-->
<!--</listener>-->
<!--<filter-mapping>-->
<!--<filter-name>CorsFilter</filter-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</filter-mapping>-->
<!-- 字符集过滤器 -->
<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>
3.3> applicationContext.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:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
">
<!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongodb.properties" />
<!--1.开启注解-->
<context:annotation-config/>
<!--2.配置包扫描 -->
<context:component-scan base-package="com">
<!--过滤掉控制层的注解 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--3.服务器连接信息-->
<mongo:mongo-client host="${mongo.host}" port="${mongo.port}"></mongo:mongo-client>
<!--4.创建mongoTemplate模板-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"/>
<!-- 设置使用的数据库名-->
<constructor-arg name="databaseName" value="${mongo.dbname}"/>
</bean>
</beans>
3.4> log4j.properties
#配置根Logger 后面是若干个Appender
log4j.rootLogger=DEBUG,A1,R
#log4j.rootLogger=INFO,A1,R
# ConsoleAppender 输出
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n
# File 输出 一天一个文件,输出路径可以定制,一般在根路径下
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=log.txt
log4j.appender.R.MaxFileSize=500KB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n
3.5> mongodb.properties
#mongoDB\u8FDE\u63A5\u914D\u7F6E
mongo.dbname=test
mongo.host=127.0.0.1
mongo.port=27017
#mongo.username=root
#mongo.password=root
#\u4E00\u4E2A\u7EBF\u7A0B\u53D8\u4E3A\u53EF\u7528\u7684\u6700\u5927\u963B\u585E\u6570
mongo.connectionsPerHost=8
#\u7EBF\u7A0B\u961F\u5217\u6570,\u5B83\u4EE5\u4E0A\u9762connectionsPerHost\u503C\u76F8\u4E58\u7684\u7ED3\u679C\u5C31\u662F\u7EBF\u7A0B\u961F\u5217\u6700\u5927\u503C
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
mongo.connectTimeout=1500
#\u6700\u5927\u7B49\u5F85\u65F6\u95F4
mongo.maxWaitTime=1500
#\u81EA\u52A8\u91CD\u8FDE
mongo.autoConnectRetry=true
#scoket\u4FDD\u6301\u6D3B\u52A8
mongo.socketKeepAlive= true
#scoket\u8D85\u65F6\u65F6\u95F4
mongo.socketTimeout=1500
#\u8BFB\u5199\u5206\u79BB
mongo.slaveOk=true
4.user实体类
package com.pojo;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "user")
public class User {
private String _id;
private String name;
private String password;
private String gender;
private String job;
private String hobby;
private int age;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
5.user接口
package com.service.serviceInf;
import com.pojo.User;
import java.util.List;
public interface UserServiceInf {
void addUser(User user);
void delUser(String id);
void updateUser(User user);
User findById(String id);
List<User> findByUserName(String name);
List<User> findAll();
String login(String id,String password);
void register(User user);
}
6.userServiceImpl
package com.service.impl;
import com.service.serviceInf.UserServiceInf;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.pojo.User;
import java.util.List;
@Repository
public class UserServiceImpl implements UserServiceInf {
@Autowired
private MongoTemplate mongoTemplate;
public void delUser(String id){
User user = findById(id);
mongoTemplate.remove(user);
}
public void updateUser(User user) {
mongoTemplate.save(user);
}
public void addUser(User user) {
mongoTemplate.save(user);
}
public User findById(String id) {
return mongoTemplate.findById(id,User.class);
}
public List<User> findByUserName(String name) {
Query query = new Query(Criteria.where("name").is(name));
return mongoTemplate.find(query,User.class);
}
public List<User> findAll() {
return mongoTemplate.findAll(User.class);
}
public String login(String id,String password) {
User user = mongoTemplate.findById(id,User.class);
if(user.getPassword().equals(password)){
return "登陆成功";
}else {
return "登陆失败";
}
}
public void register(User user){
mongoTemplate.insert(user);
}
}
7.userController
package com.controller.manageController.userController;
import com.pojo.User;
import com.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
public class MyController {
private UserServiceImpl userService;
@Autowired
public void setUserService(UserServiceImpl userServiceInf){
this.userService = userServiceInf;
}
/**
* 使用json响应内容
*/
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping(value = "/Main",method = RequestMethod.GET)
public @ResponseBody List<User> showUser(){
List<User> list = userService.findAll();
return list;
}
}
8.拦截器
package com.controller.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class CommonInterceptor implements HandlerInterceptor{
private List<String> excludedUrls;
public List<String> getExcludedUrls(){
return excludedUrls;
}
public void setExcludedUrls(List<String> excludedUrls){
this.excludedUrls = excludedUrls;
}
/**
* 在业务处理器处理请求之前被调用,如果返回false
* 从当前得拦截器往回执行所有拦截器的afterCompletion(),
* 再退出拦截器链,如果返回true执行下一个拦截器
* 直到所有的拦截器都执行完毕,再执行被拦截的controller
* 然后进入拦截器链
* 从最后一个拦截器往回执行所有的post Handler()
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
return true;
}
/**
* 在业务处理器处理请求执行完成后,生成视图之前执行的动作
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception{
}
public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex)throws Exception{
}
}
9.下载tomcat并配置到项目中
2.mongo篇
1. 下载mongo
2. mongo新手教程
3. 创建数据库test,创建Collection user
4. 如图
3.vue篇
3.1 脚手架搭建vue
npm install --global vue-cli
vue init webpack token
cd token
npm install
npm run dev
3.2 前端代码
<template>
<div id="fundFlow">
<div v-for="item in vm.user" :key="item._id">
<div>
{{item.name}}
</div>
<div>
{{item.password}}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'FundFlow',
data () {
return {
vm: {
user: []
}
}
},
created () {
this._initUseList()
},
methods: {
_initUseList () {
this.$http.get('http://localhost:8088/Main', {emulateJSON: true}).then(response => {
this.vm.user = response.data
}, response => {
console.log('error')
})
}
}
}
</script>
<style scoped>
</style>
3.3 查看接口数据返回(输入http://localhost:8088/Main)
3.4 页面渲染结果(只显示了名字)
如果有疑问请留言,项目git地址
大家可以一起写