springmvc&mybatis配置
程序员文章站
2022-03-04 14:30:09
...
pom文件配置
<dependencies>
<!--dom4j-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--DBCP-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.7.RELEASE</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</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>3.2.8.RELEASE</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8.1</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.8.0</version>
</dependency>
<!--upload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--upload -->
<!-- Excel文件的下载 --> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!-- codec加密 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!--jsp的标签 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>9.0.2</version>
</dependency>
</dependencies>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<!-- codec加密 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!--jsp的标签 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>9.0.2</version>
</dependency>
</dependencies>
<groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.16</version></dependency><!-- codec加密 --><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.9</version></dependency><!--jsp的标签 --><dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>9.0.2</version></dependency></dependencies>
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_2_5.xsd"
version="2.5">
<display-name>TestSpringMVC</display-name>
<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>
<servlet>
<description></description>
<display-name>DispatcherServlet</display-name>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description></description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/*</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter>
<display-name>CharacterEncodingFilter</display-name>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description></description>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>
spring文件的配置
<?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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<context:component-scan base-package="cn.ck.springdemo"></context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<util:properties id="dbConfig" location="classpath:db.properties" />
<bean id="dbs" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="#{dbConfig.driver}" />
<property name="url" value="#{dbConfig.url}" />
<property name="username" value="#{dbConfig.username}" />
<property name="password" value="#{dbConfig.password}" />
<property name="initialSize" value="#{dbConfig.initsize}" />
<property name="maxActive" value="#{dbConfig.maxsize}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dbs"></property>
<property name="mapperLocations" value="classpath:mybatis/*.xml"></property>
</bean>
<bean id="mapperscanconfig" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="basePackage" value="cn.ck.springdemo.mapper" />
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dbs"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/goods/**"/>
<mvc:exclude-mapping path="/goods_category/**"/>
<mvc:exclude-mapping path="/main/index.do"/>
<mvc:exclude-mapping path="/user/register.do"/>
<mvc:exclude-mapping path="/user/downloadImage.do"/>
<mvc:exclude-mapping path="/user/uploadForm.do"/>
<mvc:exclude-mapping path="/user/upload.do"/>
<mvc:exclude-mapping path="/user/uploadImages.do"/>
<mvc:exclude-mapping path="/user/downloadExcel.do"/>
<mvc:exclude-mapping path="/user/code.do"/>
<mvc:exclude-mapping path="/user/checkCode.do"/>
<mvc:exclude-mapping path="/user/handleRegister.do"/>
<mvc:exclude-mapping path="/user/login.do"/>
<mvc:exclude-mapping path="/user/handleLogin.do"/>
<mvc:exclude-mapping path="/user/checkUsername.do"/>
<mvc:exclude-mapping path="/user/checkLoginUsername.do"/>
<mvc:exclude-mapping path="/user/checkPhone.do"/>
<mvc:exclude-mapping path="/user/checkEmail.do"/>
<bean class="cn.tedu.store.interceptor.LoginInterceptor" />
</mvc:interceptor>
</beans>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/goods/**"/>
<mvc:exclude-mapping path="/goods_category/**"/>
<mvc:exclude-mapping path="/main/index.do"/>
<mvc:exclude-mapping path="/user/register.do"/>
<mvc:exclude-mapping path="/user/downloadImage.do"/>
<mvc:exclude-mapping path="/user/uploadForm.do"/>
<mvc:exclude-mapping path="/user/upload.do"/>
<mvc:exclude-mapping path="/user/uploadImages.do"/>
<mvc:exclude-mapping path="/user/downloadExcel.do"/>
<mvc:exclude-mapping path="/user/code.do"/>
<mvc:exclude-mapping path="/user/checkCode.do"/>
<mvc:exclude-mapping path="/user/handleRegister.do"/>
<mvc:exclude-mapping path="/user/login.do"/>
<mvc:exclude-mapping path="/user/handleLogin.do"/>
<mvc:exclude-mapping path="/user/checkUsername.do"/>
<mvc:exclude-mapping path="/user/checkLoginUsername.do"/>
<mvc:exclude-mapping path="/user/checkPhone.do"/>
<mvc:exclude-mapping path="/user/checkEmail.do"/>
<bean class="cn.tedu.store.interceptor.LoginInterceptor" />
</mvc:interceptor>
</beans>
mabatis文件的配置
<?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="cn.tedu.mybatis.dao.IUserDao">
<insert id="insertUser" parameterType="cn.tedu.mybatis.bean.User" useGeneratedKeys="true" keyProperty="id">
insert into user ( id, username, password, salary ) values ( null,#{username},#{password},#{salary})
</insert>
<update id="updateUser" parameterType="cn.ck.mybatis.bean.User">
update user set
username=#{username},password=#{password} where id=#{id}
</update>
<select id="findAllUser" resultType="cn.ck.mybatis.bean.User">
select id,username,password
from user
</select>
<delete id="deleteUser" parameterType="cn.ck.mybatis.bean.User">
delete from user where
username=#{username} and passwprd=#{password}
</delete>
<select id="findUserByMap" resultType="map">
select id,username,password from user
</select>
<select id="countUsers" resultType="int">
select count(*) from user;
</select>
<select id="findUserByUserName"
resultType="cn.tedu.store.entity.User">
select
id,username,password,phone,email,disabled,created_user
createUser,created_time createTime,
modified_user
modifiedUser,modified_time modifiedTime from
t_user where
${where}=#{username}
</select>
</mapper>
properties文件的配置
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/mine
username:root
password:11111
maxsize:50
initsize:50
controller应用举例
package cn.ck.spring.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.ck.spring.bean.User;
@Controller // 相当于@Compenet
@RequestMapping("/user") // 这个和HandlerMapping有关,配置了注解之后不需要再配置标签
public class UserController /* implements Controller */ {
@RequestMapping("/add.do")
// @ResponseBody//对ajax访问的返回
public String addUser() {
return "path:";
}
@RequestMapping("/register.do")
public ModelAndView handleRegister(User user) {
ModelAndView m = new ModelAndView();
m.setViewName("hello");// 1,转发的位置
m.getModel().put("username", user.getUsername());// 2,还可以放入参数
return m;
}
// 获取参数数据
public String handleRegister(User user, HttpServletRequest request) {
request.setAttribute("username", user.getUsername());
return "redirct:hello";
}
public String handleRegister(String username, @RequestParam("password") String password, int salary) {
return "hello";
}
public String handleRegister(HttpServletRequest request) {
String name = request.getParameter("username");
String password = request.getParameter("password");
return "hello";
}
// 发送参数
public String sendRequest(HttpServletRequest request, User user) {
// 封装数据,以转发到JSP
request.setAttribute("name", user.getUsername());
return "";
}
public ModelAndView sendModelAndView() {
String viewName = "user_register_info";
Map<String, Object> data = new HashMap<String, Object>();
data.put("pwd", "123456");
ModelAndView mav = new ModelAndView(viewName, data);
return mav;
}
public String sendMap(ModelMap map) {
map.addAttribute("name","value");
return "";
}
}
interceptor应用举例
package cn.ck.spring.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class UserInterceptor implements HandlerInterceptor {//必须实现该接口
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
// TODO Auto-generated method stub
//这里可以用来确认登录是否
System.out.println("Interceptor1");
HttpSession session=arg0.getSession();
System.out.println(session.getId());
if(session.getAttribute("username")==null) {
System.out.println("FALSE");
arg1.sendRedirect("#");
return false;
}else {
System.out.println("TRUE");
return true;
}
}
}
框架异常的两种处理方法
@ExceptionHandler
public String handleException(Exception e,
HttpServletRequest request) {
if (e instanceof ArithmeticException) {
request.setAttribute("errorMessage",
"算术运算异常,你是不是拿某个数字除以0了?");
return "error";
} else if (e instanceof ArrayIndexOutOfBoundsException) {
request.setAttribute("errorMessage",
"您使用的下标已经越界:" + e.getMessage());
return "error";
} else {
request.setAttribute("errorMessage",
"未知错误,请联系系统管理员!");
return "error";
}
}
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- key是异常名称 -->
<!-- 文本节点配置View组件 -->
<prop key="java.lang.ArithmeticException">
arithmeticException
</prop>
<prop key="java.lang.ArrayIndexOutOfBoundsException">
arrayException
</prop>
</props>
</property>
</bean>
AOP
package aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.springframework.stereotype.Component;
//<aop:..>
@Component
@Aspect
public class Knife {
// long a = 0;
// long b = 0;
//
// // 这里的说明使用多个切入点使用||
// @Before("bean(userService)||bean(DictService)") //
// public void test() {
// a = System.currentTimeMillis();
// System.out.println("HelloWord!");
// }
//
// // 这里用来表示所有的业务使用-这里突现出规范命名!!!的重要性
// @After("bean(*Service)") //
// public void test1() {
// b = System.currentTimeMillis();
// System.out.println((b - a) / 1000d);
// System.out.println("end");
// }
//
// // `within`的使用实现类
// @AfterReturning("within(cn.tedu.store.service.UserServiceImpl)") // store..*Impl的支持相同
// public void test2() {
// System.out.println("return");
// }
//
// // 修饰词 类名.方法名(参数列表)
// @Before("execution(* cn.tedu.store.service.UserService.login(..))")
// public void test5() {
// System.out.println("该方法的执行之前");
// }
//
// @AfterThrowing("bean(userService)")
// public void test3() {
// System.out.println("throwing");
// }
//
// /**
// * `@Around`
// *
// * @return 返回一个Object
// * @throws Throwable
// * 抛出一个异常
// */
// @Around("bean(userService)")
// public Object test4(ProceedingJoinPoint pjp) throws Throwable {
// System.out.println("around");
//
// System.out.println("before");
// // 执行任意一个指定bean的方法并返回值-ProceedingJoinPoint-
// Object object = pjp.proceed();
//
// System.out.println(pjp.getSignature().getName());
// System.out.println(object + "\nafter");
// // 返回给控制器
// return object;
// }
//
// /**
// * `Constructor`
// */
// public void example() {
// // try {
// // @Before
// // ......
// // @AfterReturning
// // }catch(Exception e) {
// // @Afterthrowing
// // }finally {
// // @After
// // }
// }
}