需要的jar包:
项目结构:
配置文件的配置:
beans.xml(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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
>
<!-- 数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springmvc?useUnicode=true&characterEncoding=UTF-8"/><property name="user" value="root"/><property name="password" value="123"/><property name="initialPoolSize" value="5"></property><property name="minPoolSize" value="5"></property><property name="maxPoolSize" value="15"/><property name="checkoutTimeout" value="1000"/> </bean><!-- 配置sessionfactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=true hibernate.format_sql=false </value> </property> <property name="configLocations"> <list> <value> classpath*:config/hibernate.cfg.xml </value> </list> </property></bean> <!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /></bean><tx:annotation-driven transaction-manager="transactionManager"/><!-- 自动扫描(自动注入) --><context:component-scan base-package="com.springmvc" /></beans>
springmvc-servlet.xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
<context:component-scan base-package="com.springmvc.controller" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />
</beans>
hibernate配置文件的配置:(分离开来主要是为了复杂项目管理更加方便)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 可以配置一个项目的多个映射类-->
<session-factory> <mapping class="com.springmvc.bean.User"/> </session-factory> </hibernate-configuration>
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>SpringMVC</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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/beans.xml</param-value>
</context-param>
<!-- 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*:config/Springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
<!-- 防止出现session异常-->
<filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
至此,所有的配置文件就配置好了,剩下的就是业务逻辑代码了。
springmvc的controller:
usercontroller.java:
package com.springmvc.controller;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.springmvc.bean.User;
import com.springmvc.dao.IUserDao;
/**springmvc的控制类
*
* @author 董政
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserDao userservice;
/**
* 更新用户操作
* @param user 用户对象
* @param req
* @param rep
*/
@RequestMapping("/update")
public void update(User user,HttpServletRequest req,HttpServletResponse rep){
try {
rep.setContentType("text/html;charset=UTF-8");
//获得输出流
OutputStream printWriter=null;
printWriter=rep.getOutputStream();
//对字符串进行转码操作
User newuser=null;
//转码字符串 ,防止乱码
newuser=new User(Integer.parseInt(URLDecoder.decode(user.getUserId().toString(), "utf-8")), URLDecoder.decode(user.getUserName(), "utf-8"), URLDecoder.decode(user.getAge(), "utf-8"));
userservice.update(newuser);
printWriter.write("su".getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 初始化界面
* @return
*/
@RequestMapping("/index")
public String toIndex(HttpServletRequest req,HttpServletResponse rep){
//查找集合
List<User> users=userservice.getAllUsers();
//放入作用域中
req.setAttribute("userlist", users);
return "Index";
}
/**
* 进入添加界面
* @return
*/
@RequestMapping("/toadd")
public String toAdd(){
return "add";
}
/**
* 初始化更新界面
* @param req
* @param id
* @return
*/
@RequestMapping("/toUpdate")
public String toUpdate(HttpServletRequest req,Integer id){
//查找要更新的数据
User user=userservice.getUsrById(id);
//放入作用域
req.setAttribute("user", user);
return "Userinfo";
}
/**
* 删除操作
* @param req 请求
* @param id 删除的id
* @param rep 响应
* @return
*/
@RequestMapping("/del")
public String del(HttpServletRequest req,Integer id,HttpServletResponse rep){
//删除对应的数据库数据
userservice.delUser(id);
//获取数据集合
List<User> users=userservice.getAllUsers();
//放入作用域
req.setAttribute("userlist", users);
return "Index";
}
/**
* 添加操作
* @param name 用户名
* @param age 年龄
* @param rep 响应
*/
@RequestMapping("/add")
public void add(String name,String age,HttpServletResponse rep){
try {
//设置ajax的返回类型
rep.setContentType("text/html;charset=UTF-8");
//获得输出流
OutputStream printWriter=null;
//ʵ实例化输出流
printWriter=rep.getOutputStream();
User user=null;
user = new User(null, URLDecoder.decode(name,"utf-8"), URLDecoder.decode(age,"utf-8"));
userservice.addUser(user);
//提示信息
printWriter.write("su".getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
userdao接口:
package com.springmvc.dao;
import java.util.List;
import com.springmvc.bean.User;
public interface IUserDao {
/**
* 添加用户操作
* @param user 用户
*/
public void addUser(User user);
/**
* 用户集合
* @return 集合类型
*/
public List<User> getAllUsers();
/**
* ͨ根据用户iD查询
* @param id
* @return user
*/
public User getUsrById(Integer UserId);
/**
* ɾ删除用户
* @param userId
*/
public void delUser(Integer user);
/**
* 更新用户
* @param user
*/
public void update(User user);
}
实现类我就不贴出来了。junit测试类:
package com.test;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springmvc.bean.User;
import com.springmvc.dao.IUserDao;
public class TestUser {
private static IUserDao userDao;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext cxt=new ClassPathXmlApplicationContext("/config/beans.xml");
userDao= (IUserDao) cxt.getBean("userService");
}
@Test
public void test() {
userDao.addUser(new User(null, "董政", "26"));
}
@Test
public void update(){
userDao.update(new User(1, "sss", "11"));
}
@Test
public void getAll(){
List<User> list=userDao.getAllUsers();
System.out.println(list.size());
}
@Test
public void getOne(){
System.out.println(userDao.getUsrById(1).getAge());
}
@Test
public void del(){
userDao.delUser(3);
}
}
截图: