自学SSM框架搭建有一段时间了,写点代码,分享一下心得,希望能给自学的哥们,带点启发。不足之处,希望各位大神多指教。废话不多说,直接开撸代码。
package cn.tck.ssm.po;
/**
1. 实体类
2. @author tck
3. 4. 2016年8月25日 下午7:21:10
5. 6. @version 1.0
*/
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [" + "username=" + username + ", password=" + password + "]";
}
}
2 . 创建数据库配置文件db.properties,代码如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
3 .创建日志文件log4j.properties,代码如下:
log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
4 .建立spring与mybatis的配置文件,applicationContext-dao.xml,代码如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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 ">
<context:property-placeholder location="classpath:db.properties" />
<context:component-scan base-package="cn.tck.ssm" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:cn/tck/ssm/mapper/*.xml" />
<property name="configLocation" value="classpath:mybatis/mybatis.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.tck.ssm.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
bean>
beans>
我之前在学习这个的时候,老在想name的属性,可不可以随便起,而且经常发生错误,最后查看源码,发现,每个name的属性,参照源码都有规范的写法,希望小伙伴不要跟我犯同样的错误
5 . 写mybatis的配置文件,配置数据源工作都交给了spring,所以mybatis的配置文件,很简单,他的任务,我给给他安排个—给实体类起别名:
<configuration>
<typeAliases>
<typeAlias type="cn.tck.ssm.po.User" alias="User" />
typeAliases>
configuration>
6 . 写dao接口,代码如下:
package cn.tck.ssm.dao;
import cn.tck.ssm.po.User;
public interface IUserDao {
public User findUserById(String name);
public int insetUser(User user);
}
7 . 编写dao接口的映射文件,IUserMapper.xml,代码如下:
<mapper namespace="cn.tck.ssm.dao.IUserDao">
<select id="findUserById" parameterType="String" resultType="User">
select * from user where username = #{username}
select>
<insert id="insetUser" parameterType="User">
insert into user(username,password) values(#{username},#{password})
insert>
mapper>
8 .创建服务层接口,代码如下:
package cn.tck.ssm.service;
import cn.tck.ssm.po.User;
public interface IUservice {
public User findUserById(String name);
public boolean login(String username,String password);
}
9 . 创建服务层接口的实现类,使用注解,自动注入,代码如下:
package cn.tck.ssm.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.tck.ssm.dao.IUserDao;
import cn.tck.ssm.po.User;
import cn.tck.ssm.service.IUservice;
@Service
public class IUserviceImpl implements IUservice {
@Resource
private IUserDao userDao;
/**
* 根据用户名查询
*/
@Override
public User findUserById(String name) {
return this.userDao.findUserById(name);
}
/**
* 登录验证
*/
public boolean login(String username, String password) {
User user = userDao.findUserById(username);
if (user != null) {
if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
return true;
}
}
return false;
}
}
10 . 创建测试类,使用注解测试,代码如下:
package cn.tck.ssm.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import cn.tck.ssm.po.User;
import cn.tck.ssm.service.IUservice;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/applicationContext-dao.xml" })
public class TestSpringAndMyBatis {
@Resource
private IUservice userService;
@Test
public void testFindUserById() {
User user = userService.findUserById("tck");
System.out.println(user);
}
}
10 . 测试结果为:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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 ">
<context:component-scan base-package="cn.tck.ssm.controller" />
<mvc:annotation-driven/>
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
2 . 配置web.xml文件,代码如下:
<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"
id="WebApp_ID" version="2.5">
<display-name>ssm02display-name>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/applicationContext-*.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
到这里差不多结束啦,就差控制端和前端的业务没有编写啦,,先把项目添加到Tomcat里跑一下,看有木有报错,木有的话,进行下一步
3 . 编写jsp页面,index.jsp这是一个默认页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录title>
head>
<body>
<form action="login.do" method="post">
<table align="center">
<tr>
<td colspan="2" align="center"><font color="#ff0000" size="5sp">用户登录font>td>
tr>
<tr>
<td>用户名:td>
<td><input type="text" name="username">td>
tr>
<tr>
<td>密 码:td>
<td><input type="password" name="password">td>
tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="提交">td>
tr>
table>
form>
body>
html>
4 . 编写,登录结果界面 ,如果登录成功,则返回到成功界面 success.jsp,否则fail.jsp:
success.jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录成功title>
head>
<body>
${user}
body>
html>
fail.jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录失败title>
head>
<body>
${message}
body>
html>
5 . 控制端的编写,代码如下:
package cn.tck.ssm.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import cn.tck.ssm.po.User;
import cn.tck.ssm.service.IUservice;
/**
* 界面登录验证
*
* @author tck
*
* 2016年8月25日 下午8:13:46
*
* @version 1.0
*/
@Controller
public class LoginControll {
@Resource
private IUservice userService;
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
ModelAndView mav = new ModelAndView();
User user = new User(username, password);
if (userService.login(username, password)) {
mav.addObject("user", "恭喜" + user + "登录成功");
mav.setViewName("success");
} else {
mav.addObject("message", "登录失败,请检查用户名或者密码是否正确");
mav.setViewName("fail");
}
return mav;
}
}
启动Tomcat 浏览器输入地址:http://localhost:8080/ssmTest/回车,进入如下界面:
心得体会:整个整合过程,总的来说,整体主要的配置,基本是模板,关键在于细节的处理。细心很重要,某些配置不理解不明白的地方,翻翻源码,或者百度一下基本就能弄明白。如果需要源码,请留言,我会及时补上