项目计划使用spring+springMVC+shiro+log4j2进行简单搭建,并完成增删改查目标,数据访问层采用
mybatis和hibernate两种方式分别与上述环境组合,适应不同的企业开发环境。
Eclipse Java EE IDE for Web Developers.
Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1552
Server version: 5.7.17-log MySQL Community Server (GPL)
java version “1.8.0_111”
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00)
Maven home: D:\apache-maven-3.5.0\bin..
Java version: 1.8.0_111, vendor: Oracle Corporation
Java home: C:\Java\jdk1.8.0_111\jre
Default locale: zh_CN, platform encoding: GBK
OS name: “windows 10”, version: “10.0”, arch: “amd64”, family: “windows”
1、打开eclipse工程的Navigator视图,找到新建maven项目的.settings目录,修改如下:
- 修改org.eclipse.jdt.core.prefs的版本为JDK版本
- 修改org.eclipse.wst.common.project.facet.core.xml版本3.0
- 添加maven项目必须的目录source folder:src/test/resources
- java build path选项source下,四个文件夹要全
- 修改src/test/resources的output folder为test-classes
- 修改libraries的JRE为当前JDK版本
- pom.xml添加javax.servlet-api(或者指定tomcat目录下的server runtime)
(大概就是新建maven项目所需要的流程)
修改完项目编译器版本,动态网站为最新的3.0版本,使用新特性,然后添加maven的四个默认文件
夹,在项目的java build path查看是否有默认的四个文件夹,缺少哪个就添加哪个。同时指定输出文件夹。
JRE版本一定要与JDK版本对应,不然会存在项目报错却找不到错误点的情况。
综上如此,项目基本不会报错了。
2、pom.xml添加jar包
项目必须的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.0modelVersion>
<groupId>com.wangjikaigroupId>
<artifactId>ssmartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.9.RELEASEversion>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.18version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>4.3.11.Finalversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>4.3.9.RELEASEversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>4.3.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.mongodbgroupId>
<artifactId>mongo-java-driverartifactId>
<version>3.2.2version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-mongodbartifactId>
<version>1.10.4.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-slf4j-implartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-jclartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.8.1version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.1version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>ssmfinalName>
build>
project>
3、Eclipse编码设置
Eclipse的所有项目编码:
Window->Preferences->General->Workspace->Text file encoding->UTF-8->Apply->OK
项目JSP文件的默认编码
Window->Preferences->Web->JSP Files->Encoding>ISO10646/Unicode(UTF-8)->Apply->OK
1、首先是web.xml的配置,它是web项目最先执行的配置文件。
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true" version="3.0">
<display-name>Archetype Created Web Applicationdisplay-name>
<description>spring项目description>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:application-context.xmlparam-value>
context-param>
<filter>
<filter-name>openSessionfilter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
filter>
<filter-mapping>
<filter-name>openSessionfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>spring_ssmservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:application-web.xmlparam-value>
init-param>
<load-on-startup>0load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>spring_ssmservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<servlet>
<servlet-name>DruidStatViewservlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>DruidStatViewservlet-name>
<url-pattern>/druid/*url-pattern>
servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<error-page>
<error-code>404error-code>
<location>/errorPages/404error.htmllocation>
error-page>
<error-page>
<error-code>500error-code>
<location>/errorPages/500error.htmllocation>
error-page>
<error-page>
<exception-type>java.lang.NullExceptionexception-type>
<location>/errorPages/nullParam.htmllocation>
error-page>
<session-config>
<tracking-mode>COOKIEtracking-mode>
session-config>
web-app>
2、spring配置文件,application-context.xml(ORM:hibernate)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="filters" value="stat" />
<property name="initialSize" value="1" />
<property name="minIdle" value="10" />
<property name="maxActive" value="20" />
<property name="maxWait" value="60000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.format_sql">trueprop>
props>
property>
<property name="packagesToScan">
<list>
<value>com.domainvalue>
list>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="*" propagation="REQUIRED" />
tx:attributes>
tx:advice>
<aop:config expose-proxy="true">
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service.*.*(..))" />
aop:config>
beans>
3、springMVC配置文件,application-web.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<mvc:resources location="/errorPages/" mapping="/errorPages/**" />
<mvc:annotation-driven />
<context:component-scan base-package="com" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/">property>
<property name="suffix" value=".jsp">property>
bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="NumberFormatException">/errorPages/defaultErrorprop>
<prop key="NullPointerException">/errorPages/nullParamprop>
props>
property>
<property name="defaultErrorView" value="exception" />
<property name="statusCodes">
<props>
<prop key="/errorPages/defaultError">500prop>
<prop key="/errorPages/nullParam">405prop>
props>
property>
<property name="defaultStatusCode" value="404" />
bean>
beans>
4、log4j2配置文件,log4j2.xml
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n" />
Console>
Appenders>
<Loggers>
<Root level="fatal">
<AppenderRef ref="Console" />
Root>
<logger name="com" level="info" additivity="false">
<AppenderRef ref="Console"/>
logger>
Loggers>
Configuration>
5、数据库连接参数,jdbc.properties
useSSL=false 是mysql5.7要求使用更安全的验证方式的体现。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/wjk?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=root
1、domain领域对象–pojo实体类
package com.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
@Column(name = "name")
private String name;
@Column(name = "age")
private String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
对应的数据库模型:
2、dao数据访问层
package com.dao;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.domain.User;
@Repository
public class UserSaveDao implements Serializable{
private static final long serialVersionUID = 1L;
@Resource
private SessionFactory sessionFactory;
/**
*用户数据保存
*/
public void saveUserDao(User user){
getSession().save(user);
}
/**
* 公共获取session方法
* @return
*/
public Session getSession(){
return sessionFactory.getCurrentSession();
}
}
3、service数据服务层
package com.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dao.MongoSearchDao;
import com.dao.UserSaveDao;
import com.domain.MongoUser;
import com.domain.User;
@Service
public class UserSaveService {
@Resource
private UserSaveDao userSaveDao;
public void saveUserService(User user) {
userSaveDao.saveUserDao(user);
}
}
4、controller控制器层
package com.controller;
import javax.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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 com.domain.MongoUser;
import com.domain.User;
import com.service.UserSaveService;
@Controller
public class UserSaveController {
//日志
private static Logger logger = LogManager.getLogger(UserSaveController.class.getName());
@Resource
private UserSaveService usersaveservice;
@RequestMapping(value="/")
public String aa(){
logger.info("springMVC");
return "index";
}
@RequestMapping(value="addUser")
public String addUserPage(String name,String age) {
logger.info("info level");
// User user = new User();
// user.setName(name);
// user.setAge(age);
// usersaveservice.saveUserService(user);
return "addUser";
}
@RequestMapping(value="addUser",method=RequestMethod.POST)
public String addUser(String add_name,String add_age) {
User user = new User();
user.setName(add_name);
user.setAge(add_age);
usersaveservice.saveUserService(user);
return "index";
}
}
5、前台addUser.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增用户title>
<script type="text/javascript">
function addUser() {
var form = document.forms[0];
form.action = "${ctx}/addUser";
form.method = "post";
form.submit();
}
script>
head>
<body>
<h2>请填写h2>
<form name="addUserForm">
<a>namea><input type="text" name="add_name"><br/>
<a>agea><input type="text" name="add_age"><br/>
<input type="button" value="确定" onclick="addUser()">
form>
body>
html>
项目大概结构就是这样的,随着业务的不断增加,基本上都是在此结构上增加的。配置文件的代码注释是目前已知的都加上了,方便他人查阅,同时自己做一个备忘。
如果您觉得我写的还不错,就赏脸请杯咖啡吧~(❤ ω ❤),您的支持是我最大的动力o( ̄▽ ̄)ブ