一、框架简介
(1)Spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。(2)SpringMVC
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
(3)MyBatis
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
二、项目结构
介绍:
(1)com.controller为控制层,负责视图和业务的转向,实现MVC的核心。
(2)com.service是业务层接口,com.service.impl是业务层实现类。
(3)com.mapper相当于DAO层,其中.java文件为Dao层接口,.xml文件是Dao层实现类。
(4)config包用来存放Spring配置和SpringMVC的配置以及Mybatis配置
二、一点一点的配置起来
步骤1、web.xml
<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 加载Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置Spring容器加载所有的配置文件的路径 -->
<!-- classpath*:config/spring-*.xml意义是加载config目录下所有以spring-前缀的xml文件-->
<!-- classpath:config/spring-*.xml意义是加载config目录下以spring-前缀的xml文件,仅仅匹配第一个-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>
<!-- 配置SpringMVC核心控制器 -->
<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:config/spring-mvc.xml</param-value>
</init-param>
<!-- 启动加载一次 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--为DispatcherServlet建立映射 -->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--拦截所有请求, 此处可以可以配置成*.do,仅仅拦截do后缀请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 解决工程编码过滤器 -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app></span>
步骤2、Spring 配置 spring-common.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 1. 数据源 : DriverManagerDataSource -->
<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/test" />
<property name="username" value="root" />
<property name="password" value="666" />
</bean>
<!-- 2. DAO层 mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
</bean>
<!-- 3.<span style="font-family: Arial, Helvetica, sans-serif;">DAO层配置:</span><span style="font-family: Arial, Helvetica, sans-serif;"> mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory ,basePackage:指定sql映射文件/接口所在的包(自动扫描) --></span>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property> <!-- 也可不配置,会自动扫描加载sqlSessionFactory -->
</bean>
<!-- 4. Service层:事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 5. 使用声明式事务 transaction-manager:引用上面定义的事务管理器 -->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
步骤3、mybatis配置 mybartis-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>
<typeAliases>
<typeAlias alias="User" type="com.model.User"/> <!--给com.model.User 起个别名-->
</typeAliases>
<mappers>
<mapper resource="com/mapper/UserMapper.xml" /> <!--加载UserMapper.xml文件-->
</mappers>
</configuration>
步骤4、springmvc配置 spring-mvc.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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com" />
<!-- 开启注解 -->
<mvc:annotation-driven />
<!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理,3.04新增功能,需要重新设置spring-mvc-3.0.xsd -->
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/html/**" location="/html/" />
<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<!-- <property name="prefix" value="/WEB-INF/jsp/" /> -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
三、功能源码看一看
Dao接口层:com.mapper.UserMapper
package com.mapper;
import java.util.List;
import com.model.User;
public interface UserMapper {
public List<User> findUserByName(String username);
public List<User> findAllUser();
public void AddUser(User user);
}
dao接口实现
和其他框架不同,mybatis框架与数据库打交道的是xml文件,属于半自动化
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
<!-- 解决表名与字段不匹配 -->
<resultMap type="User" id="userResultMap">
<id property="id" column="user_id"/>
<result property="username" column="user_name"/>
<result property="password" column="user_pass"/>
<result property="age" column="user_age"/>
</resultMap>
<select id="findAllUser" resultMap="userResultMap" resultType="User">
select * from d_user
</select>
<select id="findUserByName" resultMap="userResultMap" resultType="User" parameterType="java.lang.String">
select * from d_user where user_name=#{username,jdbcType=VARCHAR}
</select>
<insert id="AddUser" parameterType="User">
insert into d_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
user_name,
</if>
<if test="password != null">
user_pass,
</if>
<if test="age!= null">
user_age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
</mapper>
service 接口层:com.mapper.service.UserService.java
package com.service;
import java.util.List;
import com.model.User;
public interface UserService {
List<User> findAllUser();
public List<User> findUserByName(String username);
public void registUser(User user);
}
service接口实现“ com.service.impl.UserServiceImpl.java
package com.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.mapper.UserMapper;
import com.model.User;
import com.service.UserService;
@Service("userService")
@Transactional(propagation=Propagation.REQUIRES_NEW)
public class UserServiceImpl implements UserService{
@Resource
public UserMapper userMapper;
@Override
public List<User> findAllUser() {
List<User> findAllUser = userMapper.findAllUser();
return findAllUser;
}
@Override
public List<User> findUserByName(String username) {
List<User> list=userMapper.findUserByName(username);
return list;
}
@Override
public void registUser(User user) {
userMapper.AddUser(user);
}
}
controller(控制)层:
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.model.User;
import com.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource(name="userService")
private UserService userService;
@RequestMapping("/findAllUser")
public String findAllUser(HttpServletRequest request){
List<User> listUser = userService.findAllUser();
request.setAttribute("listUser", listUser);
return "/index";
}
@RequestMapping("/findUserByName")
public ModelAndView findUserById(HttpServletRequest request,@RequestParam(value="username")String username){
List listUser =userService.findUserByName(username);
request.setAttribute("listUser", listUser);
ModelAndView mov=new ModelAndView();
mov.setViewName("/index");
return mov;
}
@RequestMapping("/registUser")
public String registUser(HttpServletRequest request,User user){
userService.registUser(user);
return "redirect:/user/findAllUser";
}
@RequestMapping("/login")
public String login( HttpServletResponse response,User user) throws IOException{
List list=userService.findUserByName(user.getUsername());
User user1=new User();
String result;
if(list.size()<=0){
/*result="错误";*/
user1=null;
}else{
String password=((User)list.get(0)).getPassword();
if(!password.equals(user.getPassword())){
/*result="2";*/
user1.setUsername(user.getUsername());
}else{
/*result="3";*/
user1=(User)list.get(0);
}
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
JSONObject json=JSONObject.fromObject(user1);
out.println(json.toString());
return null;
}
}
view视图界面: index.jsp
<form action="<%=request.getContextPath() %>/user/findUserByName" method="post">
<input type="text" name="username" required="required">
<input type="submit" value="查询">
</form>
<form action="<%=request.getContextPath() %>/user/findAllUser" method="post">
<input type="submit" value="查询全部">
</form>
<form action="<%=request.getContextPath() %>/user/registUser" method="post">
<input type="text" name="username" required="required">
<input type="text" name="password" required="required">
<input type="number" name="age" required="required">
<input type="submit" value="注册">
</form>
<table border="1">
<tbody>
<tr>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
</tr>
<c:if test="${!empty listUser }">
<c:forEach items="${listUser}" var="list">
<tr>
<td>${list.username }</td>
<td>${list.password }</td>
<td>${list.age }</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
运行截图:
源码位置:https://yunpan.cn/cBQAnCtSf9TG7 访问密码 7159