初入公司,处于被闲置自力更生的状态,看到公司项目有使用ssh的架构,之前只接触过ssm的,便尝试一番,大有所获,特来总结一下。
搭建基本的maven项目,之后的目录基本如下,不需急于创建详细的目录,一步一步来!
在之前很长一段时间,一直搞不清spring应该有哪些依赖,看到很多博客上也是直接就丢一堆上去,后来去花时间查了下,我们在web项目上使用springmvc,只需要一个即可
<!-- springmvc依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
对了,为了方便,版本如下
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.6.RELEASE</spring.version>
<hibernate.version>5.1.7.Final</hibernate.version>
</properties>
因为spring-webmvc依赖于其它的spring核心的包,所以上面本身就包含它们了,具体可到:点击打开链接 学习spring各依赖之间的关系。
下面是web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
version="2.5">
<display-name>ssh</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Filter 定义 编码过滤器-->
<!-- Character Encoding filter -->
<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>
<!--configure the setting of springmvcDispatcherServlet and configure the
mapping -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
随后是spring-mvc.xml这里我直接放在resources下,即classpath直接访问到的位置
<?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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven>
</mvc:annotation-driven>
<!-- scan the package and the sub package -->
<context:component-scan
base-package="ssh.mvc.controller,ssh.mvc.service,ssh.mvc.dao" />
<!-- don't handle the static resource -->
<mvc:default-servlet-handler />
<!-- configure the InternalResourceViewResolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/view/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
主目录src/main/java下包ssh.mvc.controller创建测试类TestController.java
package ssh.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/test")
public String test() {
return "test";
}
}
在WEB-INF下新建文件夹view,之后创建一个jsp文件 test.jsp这里的文件名(上面return 后双引号里面部分即为要访问的jsp文件名) 该文件随意在body输入点内容
使用tomocat启动项目,正常启动后,访问 http://localhost:8080/ssh/test 可以看到刚才随意输入的内容即为成功
至此,springmvc环境搭建好了!之后需要加入的依赖就多一些了
<!-- Hibernate 核心依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- c3p0连接池 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
这里的依赖具体自行查明用意,lombok可不用,不过相应的实体类自行添加get、set、toString等
我们添加spring监听器来配置dao层的东西,避免混乱
在web.xml下添加以下代码
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:dao.xml</param-value>
</context-param>
在spring-mvc.xml的位置新建文件jdbc.properties和dao.xml
jdbc.properties
user=root
password=root
url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<!-- 导入资源文件 -->
<context:property-placeholder
location="classpath:jdbc.properties" />
<!-- 配置数据源 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="ssh.mvc.entity"></property>
</bean>
</beans>
新建包ssh.mvc.entity下面新建实体类User
package ssh.mvc.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Table(name="user")
@Entity
@Data
public class User {
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
private Integer id;
private String username;
private String password;
private String nickname;
}
@Data即为lombok的一个注解,使用后可省下生成getset方法的时间等,@GeneratedValue后的设置为主键自增
至此,保存后启动服务器,可以看到在数据库中自动生成了表user
ssh.mvc.dao下UserDao
package ssh.mvc.dao;
import ssh.mvc.entity.User;
public interface UserDao {
public void addUser(User user);
}
在建子包impl,即(ssh.mvc.dao.impl)下UserDaoImpl
package ssh.mvc.dao.impl;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ssh.mvc.dao.UserDao;
import ssh.mvc.entity.User;
@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao{
@Autowired
private SessionFactory sessionFactory;
public void addUser(User user) {
sessionFactory.openSession().save(user);
}
}
同理,service层面也是如此
package ssh.mvc.service;
import ssh.mvc.entity.User;
public interface UserService {
void addOne(User user);
}
package ssh.mvc.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ssh.mvc.dao.UserDao;
import ssh.mvc.entity.User;
import ssh.mvc.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
public void addOne(User user) {
userDao.addUser(user);
}
}
最后是控制层
package ssh.mvc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ssh.mvc.entity.User;
import ssh.mvc.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/addOne")
@ResponseBody
public String register(User user) {
System.out.println(user.getUsername());
userService.addOne(user);
return "注册成功!";
}
}
OK,来一个简单的测试,保存启动服务器
http://localhost:8080/ssh/user/addOne?username=张三&password=2&nickname=2
可以看到返回了几个????,数据成功插入了数据库
这明显是没有弄好乱码处理的结果
在spring-mvc.xml中的<mvc:annotation-driven>标签里添加处理配置
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven>
<!-- 解决@ResponseBody中文乱码 -->
<mvc:message-converters>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
<!-- 用于避免响应头过大 -->
<property name="writeAcceptCharset" value="false" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
注意:这里必须放在<context:component-scan>标签之前,即扫描包之前
OK,再次测试即可看到返回注册成功,并且数据库也插入成功!
注意的是:当你多玩了些别的操作就会发现问题,我们需要做个措施防止
org.hibernate.HibernateException: Could not obtain transaction-synchronized
Session for current 出错问题
pom.xml加入相关依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ依赖 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
dao.xml配置事务管理
<!-- 启动AspectJ支持 -->
<aop:aspectj-autoproxy />
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 使用注解配置事务 -->
<tx:annotation-driven
transaction-manager="transactionManager" />
在web.xml中加入如下代码
<!-- 解决 org.hibernate.HibernateException: Could not obtain transaction-synchronized
Session for current 出错问题 -->
<filter>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
并在相应方法或者控制类上添加@Transactional注解,具体可~自己查
新人总结,如有问题,大佬勿喷~Thanks♪(・ω・)ノ