SpringMVC+Spring+mybatis 项目实践
码云地址:https://gitee.com/ZeroLuo328/java2enews.git
注意是javaEESSM这个项目文件
创建项目,并整合ssm
项目结构:
将MVCModel2的网页资源copy过来
导入要用到的包的坐标
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zero</groupId> <artifactId>javaEESSM</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>javaEESSM Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</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-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.0</version> </dependency> </dependencies> <build> <finalName>javaEESSM</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
创建spring的配置文件applicationContext.xml,并整合SpringMVC和Mybatis
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理--> <context:component-scan base-package="com.zero" > <!--配置哪些注解不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--Spring整合MyBatis框架--> <!--配置连接池--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/java2ee"/> <property name="username" value="root"/> <property name="password" value="47LfQlFq"/> </bean> <!--配置SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置Dao接口所在包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zero.dao"/> </bean> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zero.service.impl.*ServiceImpl.*(..))"/> </aop:config> </beans>
创建SpringMVC配置文件springmvc.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理--> <context:component-scan base-package="com.zero" > <!--配置哪些注解不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--Spring整合MyBatis框架--> <!--配置连接池--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/java2ee"/> <property name="username" value="root"/> <property name="password" value="47LfQlFq"/> </bean> <!--配置SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置Dao接口所在包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zero.dao"/> </bean> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!--配置AOP增强--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.zero.service.impl.*ServiceImpl.*(..))"/> </aop:config> </beans>
编写dao层
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.dao; import com.zero.domain.User; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; @Repository public interface UserDao { /** * 通过名字查询用户 * @param username 要查询用户的姓名 * @return */ @Select("select * from user where username=#{username}") User findUserByName(String username); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.dao; import com.zero.domain.News; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface NewsDao { /** * 查询所有的新闻 * @return 所有新闻的内容 */ @Select("select * from news") List<News> findAllNews(); /** * 根据id删除新闻 * @param id 新闻的id */ @Delete("delete from news where id=#{id}") void deleteById(int id); /** * 根据id查询新闻 * @param id 要查询新闻的id * @return 新闻 */ @Select("select * from news where id=#{id}") News findNewsById(int id); /** * 插入新闻数据 * @param news */ @Insert("INSERT INTO news(title,content,author,cdate) VALUES(#{title},#{content},#{author},#{cdate})") void saveNews(News news); /** * 修改新闻 * @param news 要修改的新闻 */ @Update("update news set title=#{title},content=#{content},author=#{author},cdate=#{cdate} where id=#{id}") void updateNews(News news); }
编写实体类,其实和上一个作业的一样
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.domain; import java.io.Serializable; public class User implements Serializable { private String username; private String userpwd; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + userpwd + '\'' + '}'; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.domain; import java.io.Serializable; import java.util.Date; public class News implements Serializable { private int id; private String title; private String content; private String author; private Date cdate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getCdate() { return cdate; } public void setCdate(Date cdate) { this.cdate = cdate; } }
然后是编写Service层
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.service; import com.zero.domain.User; public interface UserService { /** * 用于判断登录的用户名和密码是否正确 * @param user 浏览器传过来的用户 * @return 返回登录结果 */ boolean loginUser(User user); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.service.impl; import com.zero.dao.UserDao; import com.zero.domain.User; import com.zero.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public boolean loginUser(User user) { User u = userDao.findUserByName(user.getUsername()); if (user.getUsername().equals(u.getUsername()) && user.getUserpwd().equals(u.getUserpwd())){ return true; } return false; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.service; import com.zero.domain.News; import com.zero.domain.User; import java.util.List; public interface NewsService { /** * 得到所有的新闻 * @return 所有的新闻 */ List<News> showNewsList(); /** * 根据id得到新闻 * @param id * @return */ News findNewsById(int id); /** * 删除新闻 * @param id 要删除新闻的id */ void deleteNews(int id); /** * 保存添加的新闻 * @param news */ void saveNews(News news); /** * 修改新闻 * @param news */ void updateNews(News news); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.service.impl; import com.zero.dao.NewsDao; import com.zero.domain.News; import com.zero.service.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("newsService") public class NewsServiceImpl implements NewsService { @Autowired private NewsDao newsDao; @Override public List<News> showNewsList() { List<News> newsList = newsDao.findAllNews(); return newsList; } @Override public News findNewsById(int id) { News news = newsDao.findNewsById(id); return news; } @Override public void deleteNews(int id) { newsDao.deleteById(id); } @Override public void saveNews(News news) { newsDao.saveNews(news); } @Override public void updateNews(News news) { newsDao.updateNews(news); } }
接着是写Controller
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.controller; import com.zero.domain.User; import com.zero.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Controller public class UserController { @Autowired private UserService userService; /** * 验证登录 * @return */ @RequestMapping("/login") public void login(HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = new User(); user.setUsername(username); user.setUserpwd(password); boolean b = userService.loginUser(user); if(b){ Cookie userNameCo= new Cookie("username", username); userNameCo.setMaxAge(60*60*24*30); response.addCookie(userNameCo); Cookie userPwdCo= new Cookie("userpwd", password); userPwdCo.setMaxAge(60*60*24*30); response.addCookie(userPwdCo); // 这里添加一个error的cookie,用来判断用户名密码是否正确,200正确,400不正确 Cookie errorCo = new Cookie("error","200"); response.addCookie(errorCo); // 用户名密码正确跳转到主页面 response.sendRedirect(request.getContextPath() + "/showlist"); return; } // 不正确则继续返回登录界面 Cookie errorCo = new Cookie("error","400"); response.addCookie(errorCo); response.sendRedirect("/login.jsp"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.controller; import com.zero.domain.News; import com.zero.service.NewsService; import org.apache.commons.beanutils.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; @Controller public class NewsController { @Autowired private NewsService newsService; /** * 展示所有新闻 * @return */ @RequestMapping("/showlist") public void showList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException { List<News> newsList = newsService.showNewsList(); request.setAttribute("newsList",newsList); request.getRequestDispatcher("/showlist.jsp").forward(request,response); } @RequestMapping("/edit") public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id=Integer.valueOf( request.getParameter("id")); News news = newsService.findNewsById(id); request.setAttribute("news",news); request.getRequestDispatcher("/edit.jsp").forward(request,response); } @RequestMapping("/save") public void save(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, ParseException, IOException { Map parameterMap = request.getParameterMap(); News news = new News(); BeanUtils.populate(news,parameterMap); news.setCdate(new Date()); if(news.getId() != 0){ newsService.updateNews(news); response.sendRedirect( request.getContextPath() + "/showlist"); return; } newsService.saveNews(news); response.sendRedirect(request.getContextPath() + "/showlist"); } @RequestMapping("/delete") public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException { int id=Integer.valueOf( request.getParameter("id")); newsService.deleteNews(id); response.sendRedirect(request.getContextPath() + "/showlist"); } @RequestMapping("/view") public void view(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException { int id=Integer.valueOf( request.getParameter("id")); News news = newsService.findNewsById(id); request.setAttribute("news",news); request.getRequestDispatcher("/showone.jsp").forward(request,response); } }
还写了个过滤器,用来初始化index.jsp的数据用的,这里为了查数据写了个DBUtil
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.controller; import com.zero.domain.News; import com.zero.service.NewsService; import com.zero.service.impl.NewsServiceImpl; import com.zero.util.DBUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.servlet.*; import java.io.IOException; import java.util.List; public class IndexFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { Object newsList = req.getAttribute("newsList"); if (newsList == null){ List<News> list = DBUtil.getNewsList(); req.setAttribute("newsList",list); } chain.doFilter(req, resp); } @Override public void init(FilterConfig config) throws ServletException { } @Override public void destroy() { } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.zero.util; import com.zero.domain.News; import com.zero.service.NewsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; @Component public class DBUtil { @Autowired private NewsService newsService; public static DBUtil dbUtil; @PostConstruct public void init() { dbUtil = this; } public static List<News> getNewsList(){ List<News> newsList = dbUtil.newsService.showNewsList(); return newsList; } }
web.xml的内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <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_4_0.xsd" version="4.0"> <display-name>Archetype Created Web Application</display-name> <!-- 配置Spring的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置加载类路径的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 服务器启动的时候,让DispatcherServlet对象创建 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--解决中文乱码的过滤器--> <filter> <filter-name>characterEncodingFilter</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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>indexFilter</filter-name> <filter-class>com.zero.controller.IndexFilter</filter-class> </filter> <filter-mapping> <filter-name>indexFilter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> </web-app>
最后的项目结构
最后的效果和MVC2一样
增删改查都没问题。
到此所有工作完成