一、首先说一下javaWeb的三层架构。
表现层:通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。
业务逻辑层:针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
数据访问层:该层所做事务直接操作数据库,针对数据的增添、删除、修改、更新、查找等。
(通俗的讲,表现层展现给用户的界面,例:用户点击登录(login),将login请求发送到业务逻辑层寻找所对应的login方法,service接收到login方法以后进行一些操作之后,调用dao层中的方法,insert,select,update,delete从而对数据库进行操作)。
二、下边一起来搭建一个小工程。
- 首先新建web工程
搭建之前先把所需jar包准备好。
在web-inf下建一个lib目录,将jar包全都放进去。这里jar包不够,需要下载自行下载,此处包括ssm所需要的大部分jar包。
插播一句,在web-inf下建立一个jsp目录,用来存放jsp页面。
点击finish结束。
2,建立包结构
controller包存放我们的控制器,
mapper包即对应数据访问层所需要的接口,以及mybatis所需的xml映射文件(sql语句填写处)
pojo包用来存放我们的实体类,
service即我们的业务逻辑层,里边的方法供controller调用。
3,建立source folder
用来放mybatis,spring,springMVC等properties所需的配置文件 。
(1)在resource目录下边建立两个包,
(2)mybatis包下放mybatis的文件
SQLMapConfig.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>
</configuration>
只需要此段代码即可。
(3)spring包下放spring及springMVC配置文件
applicationContext-dao.xml
用来管理连接池、sqlSessionFactory
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:*.properties"/>
<!-- 配置数据连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 让spring管理sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
</bean>
<!-- 自动扫描 将Mapper接口生成代理注入到Spring -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper" ></property>
</bean>
</beans>
applicationContext-service.xml
管理service层类
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- spring自动去扫描base-pack下面或者子包下面的java文件-->
<!--管理Service实现类-->
<context:component-scan base-package="com.service"></context:component-scan>
</beans>
applicationContext-trans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 事务管理器 -->
<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="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.service.*.*(..))" />
</aop:config>
</beans>
springmvc.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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描controller -->
<context:component-scan base-package="com.controller"></context:component-scan>
<!-- Spring 来扫描指定包下的类,并注册被@Component,@Controller,@Service,@Repository等注解标记的组件 -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
(4)在resources下边新建dbconfig.properties文件
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:XE 此处我用的Oracle,不同数据库url写法不同
jdbc.username=你的数据库用户名
jdbc.password=你的密码
(5)最后配置一下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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 加载spring容器 ,即我们写的application-dao,application-service,application-trans-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post乱码 -->
<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>
<!-- <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value>
</init-param> -->
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- springmvc的前端控制器 -->
<!-- <servlet> <servlet-name>taotao-manager</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml"
<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value>
</init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping>
<servlet-name>SSM</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> -->
<!-- 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:spring/springmvc.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>
三、建立所需要的类。
(1)Person.java
package com.pojo;
public class Person {
private String id;
private String username;
private String password;
private String company;
private Integer age;
private Integer sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company == null ? null : company.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
}
(2)Mapper
PersonMapper.java
package com.mapper;
import java.util.List;
import com.pojo.Person;
public interface PersonMapper {
public Person findPerson(String id);
public void addPerson(Person person);
public List<Person> findAllPerson();
}
PersonMapper.xml
这里PersonMapper.java中方法名要和对应XML文件中select,insert中的id一样!!
<?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.PersonMapper" >
<resultMap id="BaseResultMap" type="com.pojo.Person" >
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="company" property="company" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="sex" property="sex" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password, company, age, sex
</sql>
<select id="findPerson" resultMap="BaseResultMap" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from person
where id = #{id,jdbcType=VARCHAR}
</select>
<insert id="addPerson" parameterType="com.pojo.Person">
insert into person (id, username, password,
company, age, sex)
values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{company,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{sex,jdbcType=INTEGER})
</insert>
<select id="findAllPerson" resultType="com.pojo.Person">
select * from person
</select>
</mapper>
(3)service包中
PersonService.java
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mapper.PersonMapper;
import com.pojo.Person;
import sun.util.logging.resources.logging;
@Service("personService")
public class PersonService {
@Autowired
private PersonMapper dao;
/*
* 根据ID查询person
*/
public Person findById(String id){
return (Person)dao.findPerson(id);
}
/*
* 插入一个person
*/
public void insertPerson(Person person){
dao.addPerson(person);
}
/*
* 查询所有的person
*/
public List<Person> selectAll(){
List<Person> personList = dao.findAllPerson();
return personList;
}
}
(4)controller
PersonController.java
package com.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.pojo.Person;
import com.service.PersonService;
import net.sf.json.JSONObject;
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@Autowired
private Person person;
/*
* 根据ID查询
*/
@RequestMapping(value="/queryById")
public ModelAndView queryById(HttpServletRequest request){
ModelAndView mv = new ModelAndView();
String id = request.getParameter("id");
try{
Person person = personService.findById(id);
mv.setViewName("index");
mv.addObject("person", person);
}catch(Exception e){
e.printStackTrace();
}
return mv;
}
/*
* 插入人员
*/
@RequestMapping(value="/queryInsert")
public String queryInsert(HttpServletRequest request){
//ModelAndView mv = new ModelAndView();
//Person person = new Person();
person.setId(request.getParameter("id"));
person.setUsername(request.getParameter("username"));
person.setPassword(request.getParameter("pwd"));
person.setCompany(request.getParameter("company"));
person.setAge(Integer.parseInt(request.getParameter("age")));
person.setSex(1);
try{
personService.insertPerson(person);
}catch(Exception e ){
e.printStackTrace();
}
return "AllPerson";//返回AllPerson页面
}
/*
* 为插入学生做页面跳转
*/
@RequestMapping(value="/continueButton")
public ModelAndView continueButton(HttpServletRequest request){
ModelAndView mv = new ModelAndView();
mv.setViewName("addPerson");
return mv;
}
/*
*跳转到AllPerson页面
*/
@RequestMapping("/toFindAll")
public ModelAndView toFindAll(){
ModelAndView mv = new ModelAndView();
mv.setViewName("AllPerson");
return mv;
}
/*
* 查询所有人员
*/
@RequestMapping(value="/queryFindAll")
public ModelAndView queryFindAll(){
ModelAndView mv = new ModelAndView();
List<Person> personList = personService.selectAll();
mv.setViewName("AllPerson");//此处AllPerson即为要返回的页面
mv.addObject("AllPerson", personList);//jsp页面中${}中即为AllPerson
return mv;
}
}
这里@Controller即表示PersonController为控制器,@RequestMapping("/person")写在PersonController类名上边, @RequestMapping(value="queryById")写在方法是,因此,我们在jsp页面中可用/person/queryById来直接调用queryById()方法,这是spring的注解使用。@Autowired创建对象,也可以用@Resource。
四、jsp页面
在webcontent下边建立一个index.jsp,为我们工程入口页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>查询用户</title>
<style type="text/css">
</style>
<script type="text/javascript">
</script>
</head>
<body>
<div>
<div id="submitDiv" align="center">
<form id="login" action="person/queryById.do" method="post">
输入要查询的id: <input type="text" name="id" />
<button type="submit">提交</button>
</form>
</div>
<div id="submitDiv" align="center">
<form action="person/continueButton.do" method="post">
<button type="submit">添加一个伙计吧</button>
</form>
</div>
<div id="submitDiv" align="center">
<form action="person/toFindAll.do" method="post">
<button type="submit">查询所有人员</button>
</form>
</div>
</div>
</body>
</html>
页面的结构图
web-inf/jsp/index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="com.pojo.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<style type="text/css">
.td td{
width: 100px;
}
.table{
text-align: center;
margin: 0 auto;
}
</style>
</head>
<body>
<%
Person person = ((Person)request.getAttribute("person"));
%>
<table class="table">
<tr class="td">
<td>ID</td>
<td>用户名</td>
<td>密码</td>
<td style="width: 200px">公司</td>
<td>年龄</td>
<td>性别</td>
</tr>
<%if(person!=null){%>
<tr class="td">
<td><%=person.getId()%></td>
<td><%=person.getUsername()%></td>
<td><%=person.getPassword()%></td>
<td><%=person.getCompany()%></td>
<td><%=person.getAge()%></td>
<td><%=person.getSex()==1?"男":"女"%></td>
</tr>
<%}else{ %>
<tr class="td">
<td style="color: red;">暂无相关数据</td>
</tr>
<%} %>
</table>
</body>
</html>
效果图,哈哈,很丑。。将就着看吧。。
web-inf/jsp/addPerson.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>add person</title>
<style type="text/css">
#d{
width:700px;
text-align: right;
}
</style>
</head>
<body>
<h1 align="center" >请您填写信息</h1>
<div id="d">
<form action="queryInsert" method="post" >
i d:<input name="id" type="text" ><br/>
username:<input name="username" type="text"><br/>
pwd:<input name="pwd" type="text" ><br/>
company:<input name="company" type="text" ><br/>
age:<input name="age" type="text" ><br/>
sex:<input sex="sex" type="text" ><br/>
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
web-inf/jsp/AllPerson.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>人员列表</title>
</head>
<body>
<form
action="queryFindAll"
method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询" /></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>人员编号</td>
<td>人员姓名</td>
<td>人员密码</td>
<td>人员部门</td>
<td>人员年龄</td>
<td>人员性别</td>
</tr>
<c:forEach items="${AllPerson}" var="person">
<tr>
<td>${person.id }</td>
<td>${person.username}</td>
<td>${person.password}</td>
<td>${person.company }</td>
<td>${person.age}</td>
<td>${person.sex}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
最后总结一下,例:当我们输入id并且点击提交,此时提交按钮触发person/queryById.do找到queryById()方法,接着该方法中personService对象调用PersonService类中findById()方法,接着调用PersonMapper中findPerson(String id)方法,从而映射到PersonMapper.xml中findPerson查询并返回Person对象,mv.setViewName("index")返回页面为index.jsp,mv.addObject("person",person),将对象添加到mv对象中,最后返回到web-inf/jsp/index.jsp页面中并展示。
其实很多同学可能在想,为什么不直接使用 Dao 类而是还要在上面封装一层 Service 层呢?
原因是这样的:
基于责任分离的原则,Dao 层就应该专注于对数据库的操作,而在 Service 层我们可以增加一些“数据库操作的方法“(对应mapper.xml文件中增删改查的方法)去更好的完成本身抽离出来的 service 服务(业务处理)。
至此,就成功搭建一个ssm的项目了,如果对此有疑问可以发邮件至我的邮箱:15514565275@163.com。