一、在pom.xml中加入spring/springmvc、mybatis的依賴jar包等css
<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>SSM06</groupId> <artifactId>SSM06</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.0.0</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> </configuration> </plugin> </plugins> </build> <dependencies> <!-- mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.1</version> </dependency> <!-- 數據庫鏈接池 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> <!-- spring及springmvc的依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.1.9.RELEASE</version> </dependency> <!-- 標準標籤庫 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 對json數據的支持jar --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.10</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.10</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.10</version> </dependency> </dependencies> </project>
二、在web.xml中加入spring監聽器,並將其指向配置文件spring-mvc.xml、spring-mybatis.xmlhtml
加入springmvc的核心攔截器Servlet,加入對字符集的過濾器filterjava
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>SSM06</display-name> <listener> <description>spring監聽器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml;classpath:spring-mybatis.xml</param-value> </context-param> <!-- spring提供的字符集的過濾器 --> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- springmvc的核心攔截器是一個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> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
三、建立springmvc的配置文件spring-mvc.xml,並配置對註解的掃描、對模型視圖的解析、對json數據的支持、對靜態資源的攔截放過;web
建立spring管理數據庫的配置文件spring-mybatis.xml,並配置對連接資源的引入及獲取、掃描映射文件及dao文件的位置、對事物的管理(服務層方法)。spring
spring-mvc.xmlsql
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自動掃描controller包下的全部類,使其認爲spring mvc的控制器 --> <context:component-scan base-package="com" /> <!--spring對註解的支持 這個配置和 <mvc:annotation-driven /> 是同一個意思,只不過是來自於不一樣的包 --> <!-- <context:annotation-config></context:annotation-config> --> <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> <!-- 讓springmvc放過對靜態資源的攔截 --> <mvc:annotation-driven /> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/img/" mapping="/img/**"></mvc:resources> <!-- 對josn數據的支持 --> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean id="stringConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringConverter" /> <ref bean="jsonConverter" /> </list> </property> </bean> </beans>
spring-mybatis.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 引入屬性文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- spring管理數據庫連接 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置鏈接池的初始值 --> <property name="initialSize" value="1" /> <!-- 鏈接池的最大值 --> <!-- <property name="maxActive" value="500"/> --> <!-- 最大空閒時,當通過一個高峯以後,鏈接池能夠將一些用不到的鏈接釋放,一直減小到maxIdle爲止 --> <!-- <property name="maxIdle" value="2"/> --> <!-- 當最小空閒時,當鏈接少於minIdle時會自動去申請一些鏈接 --> <property name="minIdle" value="1" /> <property name="maxTotal" value="100" /> <property name="maxIdle" value="20" /> <property name="maxWaitMillis" value="1000" /> </bean> <!-- Mybatis映射文件的位置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描entity目錄, 省掉Configuration.xml裏的手工配置 --> <property name="mapperLocations" value="classpath:com/mapping/*.xml" /> </bean> <!-- DAO接口文件的位置 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 配置Spring的事務處理 聲明式事務- --> <!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 註解方式配置事物 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 攔截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS"/> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置AOP,Spring是經過AOP來進行事務管理的,將事務切入點控制在服務層的方法中 --> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.service.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
jdbc.propertiesexpress
jdbc.driverClassName = oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username = java
jdbc.password = java123
四、建立pojo層實體類apache
Student.java
package com.pojo; import java.util.Date; //學員和專業 多對一 多方 public class Student { int stuid; String stuName; int stuAge; Date stuDate; String stuSex; String stuProfess;//專業外鍵字段,能夠保留 String status; String professName;//爲了方便業務,補充一個專業名字的屬性 Profess profess;//專業對象,作級聯查詢 public int getStuid() { return stuid; } public void setStuid(int stuid) { this.stuid = stuid; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public int getStuAge() { return stuAge; } public void setStuAge(int stuAge) { this.stuAge = stuAge; } public Date getStuDate() { return stuDate; } public void setStuDate(Date stuDate) { this.stuDate = stuDate; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this.stuSex = stuSex; } public String getStuProfess() { return stuProfess; } public void setStuProfess(String stuProfess) { this.stuProfess = stuProfess; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getProfessName() { return professName; } public void setProfessName(String professName) { this.professName = professName; } public Profess getProfess() { return profess; } public void setProfess(Profess profess) { this.profess = profess; } }
Profess.javajson
package com.pojo; //一對多 一方 import java.util.List; public class Profess { int proid; String professName; List<Student> stus; public int getProid() { return proid; } public void setProid(int proid) { this.proid = proid; } public String getProfessName() { return professName; } public void setProfessName(String professName) { this.professName = professName; } public List<Student> getStus() { return stus; } public void setStus(List<Student> stus) { this.stus = stus; } }
五、建立dao層接口
IStudentDAO.java
package com.dao; import java.util.List; import com.pojo.Student; public interface IStudentDAO { List<Student> manyToOne(); }
六、建立Mapping層映射文件
Student.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.dao.IStudentDAO"> <!-- 學員和專業的多對一映射 --> <resultMap type="com.pojo.Student" id="stu_profess"> <id property="stuid" column="stuid"/> <result property="stuName" column="stuName"/> <result property="stuAge" column="stuAge"/> <result property="stuDate" column="stuDate"/> <result property="stuSex" column="stuSex"/> <result property="stuProfess" column="stuProfess"/> <!--多對一 --> <association property="profess" javaType="com.pojo.Profess"> <id property="proid" column="proid"></id> <result property="professName" column="professName"/> </association> </resultMap> <!-- 多對一的查詢,查詢學員同時查出專業信息 --> <select id="manyToOne" resultMap="stu_profess"> select * from student a,profess b where a.stuProfess=b.proid </select> </mapper>
七、建立service層服務接口+實現類
IStudentService.java
package com.service; import java.util.List; import com.pojo.Student; public interface IStudentService { List<Student> findStudent(); }
StudentService.java
package com.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.IStudentDAO; import com.pojo.Student; @Service public class StudentService implements IStudentService { @Autowired IStudentDAO stuDAO; public List<Student> findStudent(){ List<Student> stus = stuDAO.manyToOne(); return stus; } }
八、建立controller層控制器
LoginController.java
package com.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.pojo.User; @Controller public class LoginController { @RequestMapping("/login") public String login(User user,HttpServletRequest req){ System.out.println(user.getUsername()); System.out.println(req.getRequestURI()); return "redirect:success";//重定向 } @RequestMapping(value="/login2", method = RequestMethod.POST) public ModelAndView login2(User user){ ModelAndView mav = new ModelAndView(); mav.setViewName("success");//設置要跳轉的視圖名 mav.addObject("user", user);//在request範圍保存數據 return mav;//默認是轉發 } }
StudentController.java
package com.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.pojo.Student; import com.service.IStudentService; @Controller public class StudentController { @Autowired IStudentService stuSer; public void setStuSer(IStudentService stuSer) { this.stuSer = stuSer; } @RequestMapping("/findstu") public ModelAndView findStu(){ ModelAndView mav = new ModelAndView(); List<Student> stus = stuSer.findStudent(); mav.addObject("list", stus); mav.setViewName("student"); return mav; } }
九、建立登陸頁面、登陸成功頁面、學員信息展現頁面
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="login2" method="post"> 用戶名:<input name="username"><br> 密碼:<input type="password" name="pwd"><br> <input type="submit" value="登陸"> </form> </body> </html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 歡迎${user.username}登陸 <p> <a href="findstu">查詢學員信息</a> </p> </body> </html>
student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html> <head> <base href="<%=basePath%>"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table style="width: 500px"> <c:forEach items="${list }" var="stu"> <tr> <td>${stu.stuName }</td> <td>${stu.profess.professName }</td> </tr> </c:forEach> </table> </body> </html>
十、運行項目。
登陸頁面==>點擊登陸==>登陸控制器==>登陸成功頁面==>點擊查詢學員信息==>學員管理控制器==>學員信息展現頁面