初学ssm框架的信息
ssm框架,就是Spring ,SpringMVC ,mybstis 的简称,我们是从mybstis 开始学起的,mybatis的作用作为一个连接数据库的框架,可以很好配置连接好数据库, 有mybatis,我们对数据库增删改查的操作更为简便了。SSM框架,我们用MAVEN工具对他们进行管理,maven 工具的主要作用就是为我们的工程自动配置好我们所需的架包,是通过POM.xml 文件进行依赖管理的。
ssm02这个工程使用maven工具进行管理和配置的,他的主要作用是实现用户的登陆和注册!以及对学生信息的管理,当然其中包括了增删改查的四个基本的操作,详细的具体的过程直接看后面的代码!
1 首先是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.0</modelVersion> <groupId>com.zzty</groupId> <artifactId>ssm01</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm01 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.1.1</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-oxm</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>org.springframework</groupId> <artifactId>spring-webmvc</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-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.0</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <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>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</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 --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>ssm01</finalName> </build> </project>
2 、配置resource下面的四个文件。
3、首先对resource下的jdbc.properties进行配置 ,作用就是连接你的数据库的配置
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ssm01 username=root password=root #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大空闲 maxIdle=20 #定义最小空闲 minIdle=1 #定义最长等待时间 maxWait=60000
4、接着是log4.properties的配置,它的作用是用来记录运行时产生的信息。
#定义LOG输出级别 log4j.rootLogger=INFO,Console,File #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定输出目录 log4j.appender.File.File = logs/ssm.log #定义文件最大大小 log4j.appender.File.MaxFileSize = 10MB # 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
5、接着是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:p="http://www.springframework.org/schema/p" 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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="zizai.controller" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置-这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
6、spring mybatis.xml 他的作用就是整合Spring 和Mybatis。
<?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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="zizai.*" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:zizai/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="zizai.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
7、还有的就是webapp 下面的WEB-INF下面的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_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/resources/*</url-pattern> </servlet-mapping> <!-- Spring MVC servlet --> <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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 配置SESSION超时,单位是分钟 --> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
8、我们现在要写的就是Controller层,Service接口层,ServiceImp接口的实现层!就一个列子为例来说明的吧!这个UserController层,主要是实现用户的登陆和注册以及修改用户的密码。
package zizai.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import zizai.model.User; import zizai.service.StudentService; import zizai.service.UserService; @Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService; @Resource private StudentService studentService; @RequestMapping("/showUser") public String showUser(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); model.addAttribute("user", user); return "showUser"; } @RequestMapping("/table") public ModelAndView showTable(HttpServletRequest request){ ModelAndView view = new ModelAndView("tables"); return view; } @RequestMapping("/index") public ModelAndView toIndex(HttpServletRequest request){ ModelAndView view = new ModelAndView("login"); return view; } @RequestMapping("/login2") public ModelAndView login(HttpServletRequest request,Model model){ String username = request.getParameter("name"); String pwd = request.getParameter("pwd"); User user = this.userService.getUserByName(username); String url="login"; if(user!=null&&pwd.equals(user.getPwd())){ url="sucess"; }else{ url="fail"; } ModelAndView view = new ModelAndView(url); return view; } @RequestMapping("/register") public ModelAndView register(HttpServletRequest request,Model model){ String username = request.getParameter("name"); String pwd = request.getParameter("pwd"); User user = new User(); user.setName(username); user.setPwd(pwd); int i=this.userService.addUser(user); String url="register"; if(username!=null||pwd!=null){ if(i>0){ url="login"; }else{ url="fail"; } } ModelAndView view = new ModelAndView(url); return view; } @RequestMapping("/updateUserPwd") public String updateUserPwd(HttpServletRequest request,Model model){ String name=request.getParameter("name"); String pwd=request.getParameter("pwd"); String pwd1=request.getParameter("pwd1"); if(pwd1.equals(pwd)&&pwd1!=null){ User user=new User(); user.setPwd(pwd); user.setName(name); int i=this.userService.updateUserPwdByName(user); return "success"; } else{ return "fail2"; } } @RequestMapping("/getUserByName") public ModelAndView selectByName(HttpServletRequest request,Model model){ String name = request.getParameter("name"); User user=new User(); user=this.userService.getUserByName(name); String url="getUserByName"; if(name!=null){ url="updateUserPwd"; } ModelAndView view = new ModelAndView(); view.setViewName(url); view.addObject("xxx", user); return view; } }
useService 接口层
package zizai.service; import zizai.model.User; public interface UserService { public User getUserById(int id); public User getUserByName(String name); public int addUser(User user); public int updateUserPwdByName(User user); }
UserServiceImp 实现层
package zizai.serviceImp; import javax.annotation.Resource; import org.springframework.stereotype.Service; import zizai.dao.UserMapper; import zizai.model.User; import zizai.service.UserService; @Service("userService") public class UserServiceImp implements UserService { @Resource private UserMapper userMapper; public User getUserById(int id) { // TODO Auto-generated method stub return userMapper.selectByPrimaryKey(id); } public int addUser(User user) { // TODO Auto-generated method stub return userMapper.insert(user); } public User getUserByName(String name) { // TODO Auto-generated method stub return userMapper.selectByName(name); } public int updateUserPwdByName(User user) { // TODO Auto-generated method stub return userMapper.updateUserPwdByName(user); } }
model(USer model)层
package zizai.model; public class User { private Integer id; private String name; private String pwd; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } }
mapping (USer mapping)
<?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="zizai.dao.UserMapper" > <resultMap id="BaseResultMap" type="zizai.model.User" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="pwd" property="pwd" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, name, pwd </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from suser where id = #{id,jdbcType=INTEGER} </select> <select id="selectByName" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from suser where name = #{name,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from suser where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="zizai.model.User" > insert into suser (id, name, pwd ) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" parameterType="zizai.model.User" > insert into suser <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> <if test="pwd != null" > pwd, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> <if test="pwd != null" > #{pwd,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="zizai.model.User" > update suser <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> <if test="pwd != null" > pwd = #{pwd,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="zizai.model.User" > update suser set name = #{name,jdbcType=VARCHAR}, pwd = #{pwd,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <update id="updateUserPwdByName" parameterType="zizai.model.User"> update suser set pwd = #{pwd,jdbcType=VARCHAR} where name = #{name,jdbcType=VARCHAR} </update> </mapper>
dao (user Dao)
package zizai.dao; import zizai.model.User; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByName(String name); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); int updateUserPwdByName(User user); }
最后就是剩下WEB-INF 目录下的jsp文件夹下面的jsp 文件了。
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录</title> </head> <h3> 欢迎来到自在天原的登陆页面</h3> <body style="text-align:center"> <div > <form action="/ssm02/user/login2"> 用户名: <input type="text" name="name"><br><br>     密码: <input type="password" name="pwd"><br><br> <button type="submit">登陆</button> <a href="/ssm02/user/register"><button>注册</button> </div> </body> </html>
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>注册</title> </head> <body> <div > <form action="/ssm02/user/register"> 用户名:<input name = "name"><br> 密码:<input name = "pwd" type = "password"><br> <input type = "submit" value = "注册"> </form> </div> </body> </html>