spring mvc随笔

一、SpringMvc学习笔记 1、使用SpringMvc时需在web.xml文件中添加配置

<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>*.do</url-pattern>
</servlet-mapping>

2、SpringMvc配置文件:spring-mvc.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"
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">


<context:component-scan base-package="com.controller"/>
<-- 视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

3、controller配置:@Controller(注解形式)

@Controller
public class HelloWorldController {

@RequestMapping("/helloWorld")
public String helloWorld(Model model){
model.addAttribute("message", "问候SpringMvc他大爷");
return "helloWorld";  //直接返回 /WEB-INF/jsp/helloWorld.jsp
}
}

4、防止乱码:在web.xml文件中加入

<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>

5、<mvc:annotation-driven />   <!-- 加入注解驱动 -->

<!-- 使用注解的包,包括子集 -->
    <context:component-scan base-package="com.controller"/>
    <context:component-scan base-package="com.model"/>

6、ModelAndView详解:

@RequestMapping("/list")
public ModelAndView list(){
ModelAndView mav=new ModelAndView();
mav.addObject("studentList", studentList);
mav.setViewName("student/list");
return mav;
}

@RequestMapping("/preSave")
public ModelAndView preSave(@RequestParam(value="id",required=false) String id){
ModelAndView mav=new ModelAndView();
if (id != null) {
mav.addObject("student", studentList.get(Integer.parseInt(id)-1));
mav.setViewName("student/update");
}else {
mav.setViewName("student/add");
}
return mav;
}

@RequestMapping("/save")
public String save(Student student){
if (student.getId() != 0) {
Student s = studentList.get(student.getId()-1);
s.setName(student.getName());
s.setAge(student.getAge());
}else {
studentList.add(student);
}
return "redirect:/student/list.do";//重定向
}


@RequestMapping("/delete")
public String delete(@RequestParam(value="id",required=false) int id){
studentList.remove(id-1);
return "redirect:/student/list.do";//重定向
}

7、

@RequestMapping("/login")
public String login(HttpServletRequest request,HttpServletResponse response){
System.out.println("---------登录验证--------");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
Cookie cookie = new Cookie("user", userName+"-"+password);

User currentUser = new User(userName, password);

cookie.setMaxAge(1*60*60*24*7);
response.addCookie(cookie);

HttpSession session = request.getSession();
session.setAttribute("currentUser", currentUser);

return "redirect:/main.jsp";
} 

@RequestMapping("/login2")
public String login2(HttpServletRequest request){
System.out.println("---------登录验证--------");
return "redirect:/main.jsp";
} 

@RequestMapping("/login3")
public String login3(HttpSession session){
System.out.println("---------登录验证--------");

session.setAttribute("currentUser", "");

return "redirect:/main.jsp";
} 

//直接返回user对象的ajax形式信息
@RequestMapping("/ajax")
public @ResponseBody User ajax(){
User user = new User("张三", "admin");
return user;
}

@RequestMapping("/list")
public String list(Model model){
return "article/list";
}

//restful风格的url
//请求地址形式为:
//<a href="${pageContext.request.contextPath}/article/details/1" target="_blank">文章一</a>
//<a href="${pageContext.request.contextPath}/article/details/2" target="_blank">文章二</a>

@RequestMapping("/details/{id}")
public ModelAndView details(@PathVariable("id") int id){
ModelAndView mav=new ModelAndView();
if(id==1){
mav.addObject("article", new Article("文章一","文章一的内容"));
}else if(id==2){
mav.addObject("article", new Article("文章二","文章二的内容"));
}
mav.setViewName("article/details");
return mav;
}

8、SpringMvc配置支持文件上传:

<!-- 支持文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760" /><!-- maxsize 10M -->
</bean>

<!-- SpringMvc特殊处理,防止静态图片资源被拦截,将其映射到/resources/**路径 -->
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="UTF-8"/>  
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="20000000"/>  
    </bean>

前台页面: 1、单文件上传 前台页面配置:

<form action="upLoad.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<th colspan="2">上传文件</th>
</tr>
<tr>
<td>文件一</td>
<td>
<input type="file" name="file"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传文件"/>
</td>
</tr>
</table>
</form>

后台controller:

@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
return "redirect:success.html";
}

2、多文件上传 前台页面:

<form action="upLoadPic2.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<th colspan="2">上传文件</th>
</tr>
<tr>
<td>文件一</td>
<td>
<input type="file" name="file"/>
</td>
</tr>
<tr>
<td>文件二</td>
<td>
<input type="file" name="file"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="上传文件"/>
</td>
</tr>
</table>
</form>

后台controller:

@RequestMapping("/upLoadPic2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
for(MultipartFile file:files){
file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
}
return "redirect:success.html";
}

二、Spring学习笔记 1、bean配置

<bean id="zhangsan" class="com.service.ZhangSan"></bean>
    <bean id="lisi" class="com.service.LiSi"></bean>
    <bean id="javaWork" class="com.service.JavaWork">
    <property name="tester" ref="zhangsan"></property>
    </bean>

2、获取ApplicationContext对象:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");

3、bean的注入方法: 属性注入、构造注入(通过类型、索引、联合使用类型和索引)、非静态工厂注入、工厂注入、泛型依赖注入

<bean id="people" class="com.entity.People"></bean>
   
   <bean id="people2" class="com.entity.People">
    <!-- 属性注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
   </bean>
   
   <bean id="people3" class="com.entity.People">
    <!-- 构造注入,通过类型 -->
    <constructor-arg type="int" value="2"></constructor-arg>
    <constructor-arg type="String" value="李四"></constructor-arg>
    <constructor-arg type="int" value="22"></constructor-arg>
   </bean>
   
   <bean id="people4" class="com.entity.People">
    <!-- 构造注入,通过索引 -->
    <constructor-arg index="0" value="3"></constructor-arg>
    <constructor-arg index="1" value="王五"></constructor-arg>
    <constructor-arg index="2" value="24"></constructor-arg>
   </bean>
   
   <bean id="people5" class="com.entity.People">
    <!-- 构造注入,联合使用 -->
    <constructor-arg index="0" type="int" value="4"></constructor-arg>
    <constructor-arg index="1" type="String" value="赵六"></constructor-arg>
    <constructor-arg index="2" type="int" value="21"></constructor-arg>
   </bean>
   
   <!-- 非静态工厂注入 -->
   <bean id="peopleFactory" class="com.factory.PeopleFactory"></bean>
   <bean id="people6" factory-bean="peopleFactory" factory-method="createPeople"></bean>
   
    <!-- 静态工厂注入 -->
   <bean id="people7" class="com.factory.PeopleFactory2" factory-method="createPeople"></bean>

<!-- 泛型依赖注入,后边讲 -->

public class PeopleFactory {
public People createPeople(){
People people = new People();
people.setId(6);
people.setAge(29);
people.setName("李伟");
return people;
}
}

public class PeopleFactory2 {
public static People createPeople(){
People people = new People();
people.setId(5);
people.setAge(23);
people.setName("刘锡");
return people;
}
}

4、各种类型注入(包括集合属性)

<bean id="people1" class="com.entity.People">
    <!-- 基本属性注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
   </bean>
   
   <bean id="people2" class="com.entity.People">
    <!-- bean注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog" ref="dog"></property>
   </bean>
   <bean id="dog" class="com.entity.Dog">
    <property name="name" value="jack"></property>
   </bean>
   
   <bean id="people3" class="com.entity.People">
    <!-- 内部bean注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog">
  <bean class="com.entity.Dog">
  <property name="name" value="tom"></property>
  </bean>
  </property>
   </bean>
   
   <bean id="people4" class="com.entity.People">
    <!-- null值,即没有dog属性 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog">
  <null></null>
  </property>
   </bean>
   
   <!-- <bean id="people5" class="com.entity.People">
    级联属性,dog必须先new
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog.name" value="jerry"></property>
   </bean> -->
   
   <bean id="people6" class="com.entity.People">
    <!-- list集合注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog" ref="dog"></property>
    <property name="hobbies">
    <list>
    <value>唱歌</value>
    <value>跳舞</value>
    </list>
    </property>
   </bean>
   
   <bean id="people7" class="com.entity.People">
    <!-- set集合注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog" ref="dog"></property>
    <property name="hobbies">
    <list>
    <value>唱歌</value>
    <value>跳舞</value>
    </list>
    </property>
    <property name="loves">
    <set>
    <value>唱歌2</value>
    <value>跳舞2</value>
    </set>
    </property>
   </bean>
   
    <bean id="people8" class="com.entity.People">
    <!-- map集合注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog" ref="dog"></property>
    <property name="hobbies">
    <list>
    <value>唱歌</value>
    <value>跳舞</value>
    </list>
    </property>
    <property name="loves">
    <set>
    <value>唱歌2</value>
    <value>跳舞2</value>
    </set>
    </property>
    <property name="works">
    <map>
    <entry>
    <key><value>上午</value></key>
    <value>写代码</value>
    </entry>
    <entry>
    <key><value>中午</value></key>
    <value>喝茶</value>
    </entry>
    <entry>
    <key><value>下午</value></key>
    <value>睡觉</value>
    </entry>
    </map>
    </property>
   </bean>
   
   <bean id="people9" class="com.entity.People">
    <!-- properties属性注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <property name="dog" ref="dog"></property>
    <property name="hobbies">
    <list>
    <value>唱歌</value>
    <value>跳舞</value>
    </list>
    </property>
    <property name="loves">
    <set>
    <value>唱歌2</value>
    <value>跳舞2</value>
    </set>
    </property>
    <property name="works">
    <map>
    <entry>
    <key><value>上午</value></key>
    <value>写代码</value>
    </entry>
    <entry>
    <key><value>中午</value></key>
    <value>喝茶</value>
    </entry>
    <entry>
    <key><value>下午</value></key>
    <value>睡觉</value>
    </entry>
    </map>
    </property>
    <property name="address">
    <props>
    <prop key="address1">address1</prop>
    <prop key="address2">address2</prop>
    </props>
    </property>
   </bean>

People类主体:

private int id;
private String name;
private int age;
private Dog dog;
private List<String> hobbies = new ArrayList<String>();
private Set<String> loves = new HashSet<String>();
private Map<String, String> works = new HashMap<String, String>();
private Properties address = new Properties();

//测试类主体
private ApplicationContext ac;


@Before
public void setUp() throws Exception {
ac = new ClassPathXmlApplicationContext("beans.xml");
}

/*注入基本类型值*/
@Test
public void test() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people1 = (People) ac.getBean("people1");
System.out.println(people1);
}

/*注入bean*/
@Test
public void test2() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people2 = (People) ac.getBean("people2");
System.out.println(people2);
}

/*注入内部bean*/
@Test
public void test3() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people3 = (People) ac.getBean("people3");
System.out.println(people3);
}

/*注入null*/
@Test
public void test4() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people4 = (People) ac.getBean("people4");
System.out.println(people4);
}

/*级联属性*/
@Test
public void test5() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people5 = (People) ac.getBean("people5");
System.out.println(people5);
}

/*注入list集合*/
@Test
public void test6() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people6 = (People) ac.getBean("people6");
System.out.println(people6);
}

/*注入set集合*/
@Test
public void test7() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people7 = (People) ac.getBean("people7");
System.out.println(people7);
}

/*注入map集合*/
@Test
public void test8() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people8 = (People) ac.getBean("people8");
System.out.println(people8);
}

/*注入properties属性*/
@Test
public void test9() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people9 = (People) ac.getBean("people9");
System.out.println(people9);
}


5、自动注入:
default-autowire="byType"><!-- 自动注入,byName、byType -->
    <!-- 
    byName时,根据people中的dog属性去寻找beans.xml中匹配的dog对象注入
    byType时,根据type类型自动注入,如果beans.xml中有两个dog对象,则报错
    constructor,和byType类似,在people中生成单独dog的构造方法即可
    -->

6、设置bean实例为多例:

<bean id="people1" class="com.entity.People">
    <!-- bean注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <!-- <property name="dog" ref="dog"></property> -->
    <!-- 虽然引用的dog为prototype多例,但是每次一个新的people生成的dog均为同一条dog,即注入之后已经固定死,不能动态改变 -->
    
    <lookup-method name="getDog" bean="dog"/>
    <!-- 加入lookup配置之后,每个people生成的dog都是多例的 -->
   </bean>
   <bean id="dog" class="com.entity.Dog" scope="prototype"><!-- prototype,设置bean为多例 -->
    <property name="name" value="jack"></property>
   </bean>

   public abstract Dog getDog();//让srping去动态实现dog的多例

7、Spring中的方法替换:

<bean id="people1" class="com.entity.People">
    <!-- bean注入 -->
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="20"></property>
    <replaced-method name="getDog" replacer="people2"></replaced-method>
    <!-- 方法替换:将people里面的getDog方法替换为people2中的实现的方法 -->
   </bean>
   
   <bean id="people2" class="com.entity.People2"></bean>

People实体类:

public class People {
private int id;
private String name;
private int age;
private Dog dog;//byName时,自动注入beans中名称为dog的属性

public int getId() {
return id;
}

public Dog getDog(){
Dog dog = new Dog();
dog.setName("jack");
return dog;
}

public void setDog(Dog dog) {
this.dog = dog;
}
public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

People2实体类,实现接口org.springframework.beans.factory.support.MethodReplacerMethodReplacer
public class People2 implements MethodReplacer{
@Override
public Object reimplement(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
Dog dog = new Dog();
dog.setName("tom");
return dog;
}
}

8、bean的作用范围:prototype多例,request即每次请求创建一个新的bean,session,global session,         application,singleton单例 ,request

<bean id="abstractPeople" class="com.entity.People" abstract="true" scope="prototype" >
    <property name="className" value="高三五班"></property>
    <property name="age" value="19"></property>
   </bean>


<!-- bean之间的继承 ,加入depends-on属性后,则优先寻找authority的bean并初始化-->
<bean id="zhangsan" parent="abstractPeople" depends-on="authority">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
</bean>
<!-- bean继承并覆盖父bean属性值age -->
<bean id="lisi" parent="abstractPeople">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="20"></property>
</bean>

<bean id="authority" class="com.authority.Authority"></bean>

Authority实体类:

public class Authority {
public Authority() {
System.out.println("获取权限");
}
} 

9、Spring AOP

public class StudentServiceImpl implements StudentService {
@Override
public void addStudent(String name) {
//未使用aop的话,只会增加代码耦合度
System.out.println("开始添加学生:"+name);
System.out.println("添加学生:"+name);
System.out.println("完成学生"+name+"添加");
}
}

AOP配置:

<bean id="studentService" class="com.service.impl.StudentServiceImpl"></bean>
    <!-- aspect的定义 -->
    <bean id="studentServiceAspect" class="com.advice.StudentServiceAspect"></bean>
    <aop:config>
    <aop:aspect id="studentServiceAspect" ref="studentServiceAspect">
    <!-- *代表任意,第一个*代表返回值,第二个代表类名,第三个代表方法名,括号..代表方法参数任意 -->
    <aop:pointcut expression="execution(* com.service.*.*(..))" id="businessService"/>
    <aop:before method="doBefore" pointcut-ref="businessService"/>
    <aop:after method="doAfter" pointcut-ref="businessService"/>
    <aop:around method="doAround" pointcut-ref="businessService"/>
    <aop:after-returning method="doAfterReturning" pointcut-ref="businessService"/>
    <aop:after-throwing method="doAfterThrowing" pointcut-ref="businessService" throwing="ex"/>
    </aop:aspect>
    </aop:config>

StudentServiceAspect实体类:

public class StudentServiceAspect {
//前置通知
public void doBefore(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("开始添加学生:"+jp.getArgs()[0]);
}
//后置通知
public void doAfter(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("学生添加完成:"+jp.getArgs()[0]);
}
//环绕通知
public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("添加学生前");
Object retVal = pjp.proceed();//代表方法执行,如果配置了环绕通知,则不必在配置前后置通知,
//retVal即为所执行的方法的返回值
System.out.println(retVal);
System.out.println("添加学生后");
return retVal;
}

//返回通知,方法return之前调用
public void doAfterReturning(JoinPoint jp) throws Throwable{
System.out.println("返回通知");
}

//异常通知,方法return之前调用
public void doAfterThrowing(JoinPoint jp,Throwable ex) throws Throwable{
System.out.println("异常通知");
System.out.println("异常信息:"+ex.getMessage());
}
} 

10、Spring JDBC的支持 1)JdbcTemplate使用:

<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
    </bean>


<bean id="studentDao" class="dao.impl.StudentDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean> 

<bean id="studentService" class="service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> 

jdbc.properties文件:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring
jdbc.username=root
jdbc.password=123

StudentDaoImpl类实体:

public class StudentDaoImpl implements StudentDao{


private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}


@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,?,?)";
Object []params=new Object[]{student.getName(),student.getAge()};
return jdbcTemplate.update(sql,params);
}


@Override
public int updateStudent(Student student) {
String sql="update t_student set name=?,age=? where id=?";
Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
return jdbcTemplate.update(sql,params);
}


@Override
public int deleteStudent(int id) {
String sql="delete from t_student where id=?";
Object []params=new Object[]{id};
return jdbcTemplate.update(sql,params);
}


@Override
public List<Student> findStudents() {
String sql="select * from t_student";
final List<Student> studentList=new ArrayList<Student>();
jdbcTemplate.query(sql, new RowCallbackHandler(){


@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}

});
return studentList;
}
}

2)JdbcDaoSupport使用

<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="studentDao" class="dao.impl.StudentDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean> 

<bean id="studentService" class="service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> 

StudentDaoImpl实体类:

public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao{
//extends之后 只需为id=studentDao的bean添加dataSource即可

@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,?,?)";
Object []params=new Object[]{student.getName(),student.getAge()};
return this.getJdbcTemplate().update(sql,params);
}


@Override
public int updateStudent(Student student) {
String sql="update t_student set name=?,age=? where id=?";
Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
return this.getJdbcTemplate().update(sql,params);
}


@Override
public int deleteStudent(int id) {
String sql="delete from t_student where id=?";
Object []params=new Object[]{id};
return this.getJdbcTemplate().update(sql,params);
}


@Override
public List<Student> findStudents() {
String sql="select * from t_student";
final List<Student> studentList=new ArrayList<Student>();
this.getJdbcTemplate().query(sql, new RowCallbackHandler(){


@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}

});
return studentList;
}
}

3)使用namedParameterJdbcTemplate

<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="studentDao" class="dao.impl.StudentDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> 
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
<bean id="studentService" class="service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean> 

StudentDaoImpl实体类:

public class StudentDaoImpl implements StudentDao{

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}


public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}


@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,:name,:age)";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("name", student.getName());
mps.addValue("age", student.getAge());
return namedParameterJdbcTemplate.update(sql, mps);
}


@Override
public int updateStudent(Student student) {
String sql="update t_student set name=:name,age=:age where id=:id";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("name", student.getName());
mps.addValue("age", student.getAge());
mps.addValue("id", student.getId());
return namedParameterJdbcTemplate.update(sql,mps);
}


@Override
public int deleteStudent(int id) {
MapSqlParameterSource mps = new MapSqlParameterSource();
String sql="delete from t_student where id=:id";
mps.addValue("id", id);
return namedParameterJdbcTemplate.update(sql,mps);
}


@Override
public List<Student> findStudents() {
String sql="select * from t_student";
final List<Student> studentList=new ArrayList<Student>();
namedParameterJdbcTemplate.query(sql, new RowCallbackHandler(){


@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}

});
return studentList;
}
}

测试类:

public class T {


private ApplicationContext ac;


@Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
}


@Test
public void addStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int addNums=studentService.addStudent(new Student("王五", 1));
if(addNums==1){
System.out.println("添加成功");
}
}

@Test
public void updateStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int updateNums=studentService.updateStudent(new Student(6,"王五2", 2));
if(updateNums==1){
System.out.println("更新成功");
}
}

@Test
public void deleteStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int deleteNums=studentService.deleteStudent(6);
if(deleteNums==1){
System.out.println("删除成功");
}
}

@Test
public void findStudents() {
StudentService studentService=(StudentService)ac.getBean("studentService");
List<Student> studentList=studentService.findStudents();
for(Student student:studentList){
System.out.println(student);
}
}
}

11、Spring 事务管理器

<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
    <!-- jdbc事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 事务管理模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="bankDao" class="dao.impl.BankDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> 
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
<bean id="bankService" class="service.impl.BankServiceImpl">
<property name="bankDao" ref="bankDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean> 

BankDaoImpl实体类:

public class BankDaoImpl implements BankDao {

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}


public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}


@Override
public void inMoney(int money, int userId) {
String sql = "update t_count set count = count + :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}


@Override
public void outMoney(int money, int userId) {
String sql = "update t_count set count = count - :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
}

BankServiceImpl实体类:

public class BankServiceImpl implements BankService{

private BankDao bankDao;
private TransactionTemplate transactionTemplate;
/*要使用TransactionTemplate,需要加jdbc事务管理器*/

/*编程式事务管理*/
@Override
public void transferAccounts(final int count,final int userIdA,final int userIdB) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {

@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
bankDao.outMoney(count, userIdA);
bankDao.inMoney(count, userIdB);
}
});
}
public void setBankDao(BankDao bankDao) {
this.bankDao = bankDao;
}
public TransactionTemplate getTransactionTemplate() {
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
}
<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
    <!-- jdbc事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="*"/><!-- 所有方法 -->
    </tx:attributes>
    </tx:advice>
    <!-- 配置事务切面 -->
    <aop:config>
    <!-- 配置切点 -->
    <aop:pointcut expression="execution(* com.service.*.*(..))" id="serviceMethod"/>
    <!-- 配置事务通知 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
    </aop:config>
    <!-- 事务管理模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="bankDao" class="dao.impl.BankDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> 
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
<bean id="bankService" class="service.impl.BankServiceImpl">
<property name="bankDao" ref="bankDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
public class BankDaoImpl implements BankDao {

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}


public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}


@Override
public void inMoney(int money, int userId) {
String sql = "update t_count2 set count = count + :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}


@Override
public void outMoney(int money, int userId) {
String sql = "update t_count set count = count - :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
}

public class BankServiceImpl implements BankService{

private BankDao bankDao;
@Override
public void transferAccounts(final int count,final int userIdA,final int userIdB) {
bankDao.outMoney(count, userIdA);
bankDao.inMoney(count, userIdB);
}
public void setBankDao(BankDao bankDao) {
this.bankDao = bankDao;
}
}
<!-- jdbc事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 事务管理模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
    </bean>
    
    <!-- 事务管理注解驱动 --> 
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="bankDao" class="dao.impl.BankDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> 
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
<bean id="bankService" class="service.impl.BankServiceImpl">
<property name="bankDao" ref="bankDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean> 

<bean id="dataSource" class="org.apache.commons.dbcp.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}"/>
    </bean>
    
    <!-- jdbc事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <!-- <tx:method name="*"/>所有方法配置事务通知,适应于service较多情况下 -->
    <!-- 配置事务传播特性 -->
    <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="edit*" propagation="REQUIRED" />  
            <tx:method name="save*" propagation="REQUIRED" />  
            <tx:method name="add*" propagation="REQUIRED" />  
            <tx:method name="new*" propagation="REQUIRED" />  
            <tx:method name="set*" propagation="REQUIRED" />  
            <tx:method name="remove*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />  
            <tx:method name="change*" propagation="REQUIRED" />  
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />  
            <tx:method name="*" propagation="REQUIRED" read-only="true" />  
    </tx:attributes>
    </tx:advice>
    <!-- 配置事务切面 -->
    <aop:config>
    <!-- 配置切点 -->
    <aop:pointcut expression="execution(* com.service.*.*(..))" id="serviceMethod"/>
    <!-- 配置事务通知 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
    </aop:config>
    <!-- 事务管理模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="transactionManager" ref="transactionManager"></property>
    </bean>
    
<context:property-placeholder location="jdbc.properties"/>

<bean id="bankDao" class="dao.impl.BankDaoImpl">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean> 
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dataSource"></constructor-arg>
    </bean>
    
<bean id="bankService" class="service.impl.BankServiceImpl">
<property name="bankDao" ref="bankDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean> 

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Java帮帮-微信公众号-技术文章全总结

Java开发Spring第一天

今日内容 Spring框架的概述 Spring的快速入门 IoC容器装配Bean(xml配置方式) Ioc容器装配Bean(注解方式) 在web项目中集成Sp...

2759
来自专栏扎心了老铁

Hadoop通过HCatalog编写Mapreduce任务访问hive库中schema数据

1、dirver package com.kangaroo.hadoop.drive; import java.util.Map; import java.u...

4895
来自专栏扎心了老铁

SpringMVC拦截器Interceptor

SpringMVC拦截器(Interceptor)实现对每一个请求处理前后进行相关的业务处理,类似与servlet中的Filter。 SpringMVC 中的I...

3486
来自专栏码匠的流水账

聊聊springboot2的MappingsEndpoint

spring-boot-actuator-autoconfigure-2.0.1.RELEASE-sources.jar!/org/springframewor...

481
来自专栏Netkiller

Spring boot with MySQL 实例参考

节选择《Netkiller Java 手札》· Spring 框架 9.7. Spring boot with MySQL 9.7.1. Maven pom.x...

2715
来自专栏pangguoming

在Spring MVC中使用注解的方式校验RequestParams

1744
来自专栏Netkiller

Spring boot with Oracle

本文节选自《Netkiller Java 手札》 地址: http://www.netkiller.cn/java/index.html 9.11. Sprin...

2764
来自专栏JAVA技术站

基于MyBatis注解扩展,实现无需配置就可拥有增删改 顶

      如果项目本身基于SpringMVC+Mybatis构建,不需添加任何配置Mapper类只需继承

803
来自专栏云霄雨霁

SpringMVC--处理器映射器和处理器适配器笔记

1210
来自专栏一枝花算不算浪漫

[Spring框架]Spring JDBCTmplate基础入门总结.

3178

扫码关注云+社区