您的位置:首页 > 编程语言 > Java开发

spring mvc和jdbcTemplate例子

2015-10-30 14:17 591 查看
用到的包大家可以百度上找,稍后给出所有源代码

jar包下载

1. 建立mysql数据库 名称
test
CREATE TABLE `person` (
`id`  int(11) NOT NULL ,
`name`  varchar(100) ,
`password`  varchar(100),
PRIMARY KEY (`id`)
)

2.在 net.spring.bean下面建立一个实体Person
package net.spring.bean;

public class Person {
int id;
String name;
String password;
public Person(int id,String name,String password){
this.id=id;
this.name=name;
this.password=password;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.建立一个dao以及imp
package net.spring.dao;

import net.spring.bean.Person;

public interface PersonDAO {
void save(Person person);
void del(Person person);
void update(Person person);
void searchAll();
}

package net.spring.dao.imp;

import org.springframework.jdbc.core.JdbcTemplate;
import net.spring.bean.Person;
import net.spring.dao.PersonDAO;

public class PersonDAOIMP implements PersonDAO{

JdbcTemplate jdbcTemplate;
public void del(Person person) {
// TODO Auto-generated method stub
}

public void save(Person person) {
// TODO Auto-generated method stub
jdbcTemplate.update("insert into person values(?,?,?)",
new Object[]{person.getId(),person.getName(),person.getPassword()});
}

public void searchAll() {
// TODO Auto-generated method stub

}

public void update(Person person) {
// TODO Auto-generated method stub

}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
<span style="font-family: Simsun; font-size: 14px; line-height: 21px; background-color: rgb(244, 251, 244);"><pre name="code" class="java" style="font-size: 14px;"></span>
4.修改web.xml
<span style="font-family: Simsun; font-size: 14px; line-height: 21px; background-color: rgb(244, 251, 244);"></span><pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Spring3MVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-servlet.xml</param-value>
</init-param>

<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


5.建立一个配置文件spring-servlet.xml 路径在web.xml已经定义。在classpath也就是src根目录

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd"> <!-- apache.dbcp连接池的配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="199288"></property>
<!-- 最大活动连接数 -->
<property name="maxActive" value="100"></property>
<!-- 最大可空闲连接数 -->
<property name="maxIdle" value="30"></property>
<!-- 最大可等待连接数 -->
<property name="maxWait" value="500"></property>
<!-- 默认的提交方式(如果不需要事务可以设置成true,在实际应用中一般设置为false,默认为false) -->
<property name="defaultAutoCommit" value="true"></property>
</bean>
<!-- jdbc注入 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- 启动Spring注解功能 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<context:component-scan base-package="net.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- dao注入 -->
<bean id="personDAO" class="net.spring.dao.imp.PersonDAOIMP">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>


6.现在离成功还有一步之遥。但是我们得先测试下,jdbc是否能正常工作。这是个良好习惯,

对了,之前的配置文件里面defaultAutoCommit需要配置成true。不然你得再加很大一段事务代码,现在只是举例从简。

没有加入junit.jar包的自己下载来加入

然后创建个测试类
package test;
import net.spring.bean.Person;
import net.spring.dao.PersonDAO;
import net.spring.dao.imp.PersonDAOIMP;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public class personTest extends TestCase {

public void testSave(){
ApplicationContext aContext=new ClassPathXmlApplicationContext("classpath:spring*.xml");
PersonDAO personDAO=(PersonDAOIMP)aContext.getBean("personDAO");
Person p=new Person(2,"你好hello","world");
personDAO.save(p);
}
}


右键 testSave这个方法运行 作为junit运行。成功

然后接下来加上spring mvc

先在webroot下面写一个index.jsp


<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>

<body>
<form action="add.html">
id:<input name="id" type="text"/>
name:<input name="name" type="text"/>
password:<input name="password" type="text"/>
<input value="提交" type="submit"/>
</form>
</body>
</html>

再在web-inf/jsp/下面写一个hello.jsp当做视图
[/code]
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
${person.name}
</body>
</html>
最后是controld代码
package net.spring.controller;

import net.spring.bean.Person;
import net.spring.dao.PersonDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

@Controller
public class HelloWorldController {
@Autowired
PersonDAO personDAO;
@RequestMapping(value="/add",method={RequestMethod.POST})
public String helloWorld(Person person,ModelMap modelMap){
personDAO.save(person);
System.out.println(person.getName());
modelMap.put("person",person);

return "/hello";
}
}


到这里就完了。由于这个是一边编辑,一边修改的文章,因为独到这里,把前面的重写copy一下,我改了几处代码,不然会bug
[/code]


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: