废话不多,先来相关配置文件:
pom.xml:
<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>oasystem</groupId><artifactId>oasystem</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>oasystem</name><description/><properties><webVersion>3.1</webVersion><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version><scope>provided</scope></dependency><!--mybatis-generator --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>1.3.7</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.7</version></dependency><dependency><groupId>org.apache.tomcat</groupId><artifactId>tomcat-jdbc</artifactId><version>8.0.52</version></dependency><!--dbcp --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><dependency><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId><version>1.6</version></dependency><!--json --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.6</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.6</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.6</version></dependency><!--sprig 依赖 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jms</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-messaging</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.7.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.7.RELEASE</version><scope>test</scope></dependency><!--============= c3p0刚开始用的这个数据源,后来换成dbcp了,这个也留着了--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!-- Commons --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.6</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.11</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><!--aopalliance --><dependency><groupId>aopalliance</groupId><artifactId>aopalliance</artifactId><version>1.0</version></dependency><!--cglib-nodep --><dependency><groupId>cglib</groupId><artifactId>cglib-nodep</artifactId><version>3.2.6</version></dependency><!--log4j <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>--><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-slf4j-impl</artifactId><version>2.11.0</version></dependency><!-- slf4j依赖 --><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.25</version></dependency><!--mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency><!--mybatis-spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.2</version></dependency><!--mysql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.40</version></dependency><dependency><groupId>org.glassfish.web</groupId><artifactId>javax.servlet.jsp.jstl</artifactId><version>1.2.2</version></dependency></dependencies><build><sourceDirectory>src</sourceDirectory><resources><resource><directory>src</directory><excludes><exclude>**/*.java</exclude></excludes></resource></resources><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>2.3.2</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>2.6</version><configuration><warSourceDirectory>${basedir}/WebRoot</warSourceDirectory><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins></build></project>
spring-myabtis.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:aop="/schema/aop"xmlns:tx="/schema/tx" xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-3.2.xsd/schema/aop /schema/aop/spring-aop-3.2.xsd/schema/tx /schema/tx/spring-tx-3.2.xsd/schema/context /schema/context/spring-context-3.2.xsd"><!--配置注解扫描,扫描service,dao接口所在的包 --><context:component-scan base-package="com.oa.dao" /><context:component-scan base-package="com.oa.service" /><!-- 开启扫描 --><context:annotation-config /><!--=================== 配置dbcp数据源 --><bean id="dataSource" class="mons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/oa"/><property name="username" value="root"/><property name="password" value="545117953"/><!--initialSize: 初始化连接--> <property name="initialSize" value="5"/> <!--maxIdle: 最大空闲连接--> <property name="maxIdle" value="10"/> <!--minIdle: 最小空闲连接--> <property name="minIdle" value="5"/> <!--maxActive: 最大连接数量--> <property name="maxActive" value="15"/><!--removeAbandoned: 是否自动回收超时连接--> <property name="removeAbandoned" value="true"/> <!--removeAbandonedTimeout: 超时时间(以秒数为单位)--> <property name="removeAbandonedTimeout" value="180"/> <!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒--> <property name="maxWait" value="3000"/> <!-- 在空闲连接回收器执行周期(毫秒) --><property name="timeBetweenEvictionRunsMillis" value="10000"/><!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 --><property name="numTestsPerEvictionRun" value="10"/><!-- 最小空闲时间--><property name="minEvictableIdleTimeMillis" value="10000"/><!-- 验证链接是否有效的sql语句 --><property name="validationQuery" value="select 1" /><!-- 获取链接之前是否测试链接的可用性 --><property name="testOnBorrow" value="true"/> </bean> <!--====================== --><!-- 一、使用原生数据库 <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/oa"/><property name="username" value="root"/><property name="password" value="545117953"/></bean>--><!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 ,使用dao接口配置sql语句 ,可以不用该配置<property name="mapperLocations" value="classpath:com/oa/mapper/*.xml"></property> --></bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 ,自动扫描了所有的XxxxMapper接口类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.oa.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- ======================== 配置mapper接口,配置单个Mapper的方式<bean id="adminMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="com.oa.dao.AdminMapper" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>--><!-- =========================== --><!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--======= 事务配置 End =================== --><!-- 配置基于注解的声明式事务 --><!-- enables scanning for @Transactional annotations --><tx:annotation-driven transaction-manager="transactionManager" /></beans>
spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:p="/schema/p"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/mvc/schema/mvc/spring-mvc-3.2.xsd"><!-- 扫描controller(controller层注入) --><context:component-scan base-package="com.oa.controller" /><!--开启MVC注解扫描 --><mvc:annotation-driven /><!-- 内容协商管理器 --><!--1、首先检查路径扩展名(如my.pdf);2、其次检查Parameter(如my?format=pdf);3、检查Accept Header--><bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"><!-- 扩展名至mimeType的映射,即 /user.json => application/json --><property name="favorPathExtension" value="true"/><!-- 用于开启 /userinfo/123?format=json 的支持 --><property name="favorParameter" value="true"/><property name="parameterName" value="format"/><!-- 是否忽略Accept Header --><property name="ignoreAcceptHeader" value="false"/><property name="mediaTypes"> <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用 --><value>json=application/jsonxml=application/xmlhtml=text/html</value></property> <!-- 默认的content type --><property name="defaultContentType" value="text/html"/></bean><!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --><mvc:default-servlet-handler /> <!-- 静态资源映射 --><mvc:resources mapping="/**" location="/"/><!--自己定义的登录拦截器 --><mvc:interceptors><mvc:interceptor><!-- 拦截所有URL中包含/user/的请求 --><mvc:mapping path="/user/**"/><bean class="com.oa.base.LoginInterceptor"></bean></mvc:interceptor></mvc:interceptors><!-- 对模型视图添加前后缀 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/" p:suffix=".jsp"/></beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance" xmlns="/xml/ns/javaee" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><display-name>oa</display-name><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><!--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-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><url-pattern>/</url-pattern></servlet-mapping><!--log4j --><context-param><param-name>log4jConfigLocation</param-name><param-value>classpath:log4j.properties</param-value></context-param><context-param><param-name>log4jRefreshInterval</param-name><param-value>10000</param-value></context-param><!-- 加载Spring框架中的log4j监听器Log4jConfigListener <listener><listener-class>mons.logging.Log</listener-class></listener><context-param><param-name>webAppRootKey</param-name><param-value>scheduleProject</param-value></context-param>--><welcome-file-list><welcome-file>/login.jsp</welcome-file></welcome-file-list></web-app>
代码:实体类 User.java
package com.oa.bean;import java.io.Serializable;import java.util.Date;public class User implements Serializable{/*** */private static final long serialVersionUID = 1L;private int id;private String name;private String account;private String pwd;private String tel;private int age;private Date w_date;private Date j_date;private String role;private int dept_id;private int leval;public User(){}public User(int id, String name, String account, String pwd, String tel, int age, Date w_date, Date j_date,String role, int dept_id, int leval) {super();this.id = id;this.name = name;this.account = account;this.pwd = pwd;this.tel = tel;this.age = age;this.w_date = w_date;this.j_date = j_date;this.role = role;this.dept_id = dept_id;this.leval = leval;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getW_date() {return w_date;}public void setW_date(Date w_date) {this.w_date = w_date;}public Date getJ_date() {return j_date;}public void setJ_date(Date j_date) {this.j_date = j_date;}public String getRole() {return role;}public void setRole(String role) {this.role = role;}public int getDept_id() {return dept_id;}public void setDept_id(int dept_id) {this.dept_id = dept_id;}public int getLeval() {return leval;}public void setLeval(int leval) {this.leval = leval;}}
DAO层的Mapper, 使用的是mybatis注解方式,因此不需要相对应的xml
package com.oa.dao;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import com.oa.bean.User;public interface UserMapper{@Select("select * from user where account=#{account} and pwd=#{pwd}")public User login(@Param("account")String account,@Param("pwd")String pwd);@Select("select * from user")public List<User> selectAll();@Select("select * from user where dept_id=#{dept_id}")public List<User> selectByID(@Param("dept_id") int dept_id);@Select("select * from user where id=#{id}")public User selectById(@Param("id")int id);@Select("select * from user where name=#{name}")public User selectByName(@Param("name") String name);@Select("select * from user where account=#{account}")public User selectByAccount(@Param("account") String account);@Insert("insert into user(name,account,pwd,tel,age,w_date,j_date,role,"+ "dept_id,leval)"+ " values(#{user.name},#{user.account},#{user.pwd},#{user.tel},"+ "#{user.age},#{user.w_date},"+ "#{user.j_date},#{user.role},#{user.dept_id},#{user.leval})")public void add(@Param("user")User user);@Update("update user set name=#{user.name},tel=#{user.tel},age=#{user.age},"+ "dept_id=#{user.dept_id},"+ "role=#{user.role},leval=#{user.leval} where id=#{user.id}")public void update(@Param("user")User user);@Update("update user set name=#{user.name},tel=#{user.tel},age=#{user.age},"+"pwd=#{user.pwd} where id=#{user.id}")public void updateInfo(@Param("user")User user);@Delete("delete from user where id=#{id}")public void deleteById(@Param("id")int id);@Delete("delete from user where name=#{name}")public void deleteByName(@Param("name")String name);@Update("update user set pwd=#{pwd} where id=#{id}")public void updatePwd(@Param("pwd")String pwd,@Param("id")int id);}
service层 userSrvice.java
package com.oa.service;import java.util.List;import com.oa.bean.User;public interface UserService {public User login(String account,String pwd);public List<User> selectAll();public User selectById(int id);public void updateInfo(User user);public User selectByName(String name);public User selectByAccount(String account);public void add(User user);public List<User> selectByID(int id);public void update(User user);public void deleteById(int id);public void deleteByName(String name);public void updatePwd(String pwd,int id);}
service实现类 UserSerciceImpl.java
package com.oa.service.Impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.oa.bean.User;import com.oa.dao.UserMapper;import com.oa.service.UserService;@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User login(String account, String pwd) {// TODO Auto-generated method stubreturn userMapper.login(account, pwd);}@Overridepublic List<User> selectAll() {// TODO Auto-generated method stubreturn userMapper.selectAll();}@Overridepublic User selectById(int id) {// TODO Auto-generated method stubreturn userMapper.selectById(id);}@Overridepublic User selectByName(String name) {// TODO Auto-generated method stubreturn userMapper.selectByName(name);}@Overridepublic User selectByAccount(String account) {// TODO Auto-generated method stubreturn userMapper.selectByAccount(account);}@Overridepublic void add(User user) {// TODO Auto-generated method stubuserMapper.add(user);}@Overridepublic void updateInfo(User user) {// TODO Auto-generated method stubuserMapper.updateInfo(user);}@Overridepublic void update(User user) {// TODO Auto-generated method stubuserMapper.update(user);}@Overridepublic void deleteById(int id) {// TODO Auto-generated method stubuserMapper.deleteById(id);}@Overridepublic void deleteByName(String name) {// TODO Auto-generated method stubuserMapper.deleteByName(name);}@Overridepublic void updatePwd(String pwd, int id) {// TODO Auto-generated method stubuserMapper.updatePwd(pwd, id);}@Overridepublic List<User> selectByID(int id) {// TODO Auto-generated method stubreturn userMapper.selectByID(id);}}
UserController.java
package com.oa.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.oa.bean.User;import com.oa.service.UserService;@Controller@RequestMapping("/user")public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/login")public ModelAndView login(String account,String pwd,HttpServletRequest request,HttpServletResponse response){ModelAndView modelAndView = new ModelAndView();if(account==null || pwd==null){modelAndView.addObject("msg", "用户名或密码不能为空");modelAndView.setViewName("login");return modelAndView;}if(userService.selectByAccount(account)==null){modelAndView.addObject("msg1", "用户名不存在");modelAndView.setViewName("login");return modelAndView;}User user = userService.selectByAccount(account);if(!user.getPwd().equals(pwd)){modelAndView.addObject("msg2", "用户名或密码错误");modelAndView.setViewName("login");return modelAndView;}request.getSession().setAttribute("user", user);request.getSession().setMaxInactiveInterval(1000*60*10);modelAndView.addObject("user", user);modelAndView.setViewName("info");return modelAndView;}@RequestMapping("/selectByName")@ResponseBodypublic User select(String name){if(userService.selectByName(name)==null){return null;}return userService.selectByName(name);}}
自定义的登录拦截器:
package com.oa.base;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;public class LoginInterceptor implements HandlerInterceptor {@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {// TODO Auto-generated method stubHandlerInterceptor.super.afterCompletion(request, response, handler, ex);}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stubHandlerInterceptor.super.postHandle(request, response, handler, modelAndView);}//登录校验拦截器@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {/** 对所有 "/user/**"路径的请求,进行登录校验,* 如果session中存有user对象,则进行放行,反之返回 登录页面*/System.out.println(request.getRequestURI());System.out.println(request.getSession().getAttribute("user"));if(!request.getRequestURI().contains("/login")){if(request.getSession().getAttribute("user")==null){response.sendRedirect("/oa/login.jsp");return false;}}return true;}}
由于某些原因,以上只是项目中完整的一条线,dao层、service层、controller层以及配置文件均完整可以运行。
欢迎大家提出宝贵意见,鄙人很希望能有机会向各位大神学习