搭建Spring框架,实现添加数据到数据库

原创链接:http://www.cnblogs.com/yanqin/p/5284400.html (允许转载,但请注明原创链接) 

1.在myeclipse中建立一个web项目

项目名 :spring01

我建立的项目配置是 j2ee6、java版本1.7,让他自动生成web.xml。

我的mysql数据库里已经有 一个名叫spring的库了和tz_user表。

2.引入jar包

spring jar包如下:

spring-aop-4.1.5.RELEASE.jar
spring-beans-4.1.5.RELEASE.jar
spring-context-4.1.5.RELEASE.jar
spring-context-support-4.1.5.RELEASE.jar
spring-core-4.1.5.RELEASE.jar
spring-expression-4.1.5.RELEASE.jar
spring-jdbc-4.1.5.RELEASE.jar
spring-test-4.1.5.RELEASE.jar
spring-tx-4.1.5.RELEASE.jar
spring-web-4.1.5.RELEASE.jar
spring-webmvc-4.1.5.RELEASE.jar

其他 jar:

commons-collections-3.1.jar
commons-dbcp-1.2.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
commons-pool-1.2.jar
mysql-connector-java-5.1.6-bin.jar

引入log4j配置文件

3.配置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_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>spring01</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>


	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

4.创建applicationContext.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:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
 ">
	<!-- 配置spring去扫描包下的文件 -->
	<context:component-scan base-package="com.yq.dao"></context:component-scan>
	<context:component-scan base-package="com.yq.service"></context:component-scan>

	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=utf-8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

5.创建model dao层

package com.yq.model;


/**
 * 
 * 
 * User 
 * 创建人:yq 
 * 时间:2016年3月16日-下午4:18:13
 * @version 1.0.0
 *
 */
public class User implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	// id
	private Integer id;
	// 用户名
	private String username;
	// 密码
	private String password;
	// 年龄
	private Integer age;
	// 地址
	private String address;
	// 邮箱
	private String email;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAge() {
		return age;
	}

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

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}
package com.yq.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.yq.model.User;

/**
 * 
 * 
 * UserDao 
 * 创建人:yq 
 * @version 1.0.0
 *
 */
@Repository
public class UserDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 
	 * 保存
	 * com.yq.dao 
	 * 方法名:saveUser
	 * 创建人:yq
	 * @param user
	 * @return boolean
	 * @exception 
	 * @since  1.0.0
	 */
	public boolean saveUser(User user) {
		String sql = "insert into tz_user(username,password,age,address,email) VALUES(?,?,?,?,?)";
		int count = jdbcTemplate.update(sql, user.getUsername(),
				user.getPassword(), user.getAge(), user.getAddress(),
				user.getEmail());
		return count>0?true:false;
	}
}

6.在web.xml配置下

在listener下面添加

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>namespace</param-name>
			<param-value>spring</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>

7.web-inf下创建spring.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:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	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-4.0.xsd
 ">

	<context:component-scan base-package="com.yq.web"></context:component-scan>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/WEB-INF/pages/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
</beans>

  

8.web-inf下创建pages文件夹和jsp页面

addUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>

</head>

<body>
<form action="user/save.html" method="post">
	<div>用户名<input name="username"></div>
	<div>密码<input name="password"></div>
	<div>年龄<input name="age"></div>
	<div>地址<input name="address"></div>
	<div>邮箱<input name="email"></div>
	<div><input type="submit" vlaue="添加"></div>
</form>
</body>
</html>

  

success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
success
</body>
</html>

fail.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
fail
</body>
</html>

9.web包下创建controller

package com.yq.web;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

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.yq.model.User;
import com.yq.service.UserService;

/**
 * 
 * 
 * UserController
 * 创建人:yq
 * @version 1.0.0
 *
 */
@Controller
public class UserController extends HttpServlet {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/user")
	public ModelAndView user(){
		ModelAndView mav = new ModelAndView();
		mav.setViewName("user");
		return mav;
	}
	
	@RequestMapping("/user/save")
	public ModelAndView userSave(HttpServletRequest req){
		ModelAndView mav = new ModelAndView();
		/*
		 * 获取前台传来的数据并封装到对象中
		 */
		User user = new User();
		user.setUsername(req.getParameter("username"));
		user.setPassword(req.getParameter("password"));
		user.setAge(Integer.parseInt(req.getParameter("age")));
		user.setAddress(req.getParameter("address"));
		user.setEmail(req.getParameter("email"));
		
		/*
		 * 调用service
		 */
		boolean flag = userService.saveUser(user);
		if(flag){
			mav.setViewName("success");
		}else{
			mav.setViewName("fail");
		}
		return mav;
	}
}

10.测试

打开  localhost/spring/adduser.html ,并填入信息  (我的tomcat将端口设置成了80了,所以我的链接不需要加端口号)

 

点击提交后,跳转success页面,显示success

 

然后查看数据库,显示数据已经添加进去了。

 

现在一个简单的spring框架已经搭建完成,并且而且向数据库添加数据了。

 

posted @ 2016-03-16 17:33  抱明月  阅读(7927)  评论(1编辑  收藏  举报