control层
//增加
@RequestMapping(value="/useradd.html",method=RequestMethod.GET)
public String addUser(){
return "useradd";
}
@RequestMapping(value="/useraddsave.html",method=RequestMethod.POST)
public String addUserSave(User user,HttpSession session){
/* 这里的常量USER_SESSION,是上述 用户登录时候设置的:
* session.setAttribute(Constans.USER_SESSION, user);
* 登录者的id去添加信息,此时的登陆者也是修改者
* user.setCreatedBy(((User)session.getAttribute(Constans.USER_SESSION)).getId());
* 除了createdBy和creationDate,其他字段值通过jsp页面赋值。
* */
user.setCreatedBy(((User)session.getAttribute(Constans.USER_SESSION)).getId());
user.setCreationDate(new Date());
if(userService.add(user)){
return "redirect:/user/userlist.html";
}
return "useradd";
}
//修改操作
@RequestMapping(value="/usermodify.html",method=RequestMethod.GET)
public String getUserById(@RequestParam String uid,Model model){
User user = userService.getUserById(uid);
model.addAttribute(user);
return "usermodify";
}
@RequestMapping(value="/usermodifysave.html",method=RequestMethod.POST)
public String modifyUserSave(User user,HttpSession session){
user.setModifyBy(((User)session.getAttribute(Constans.USER_SESSION)).getId());
user.setModifyDate(new Date());
if(userService.modify(user)){
return "redirect:/user/userlist.html";
}
return "usermodify";
}
//通过id查询用户信息
@RequestMapping(value="/view/{id}",method=RequestMethod.GET)
public String viewUser(@PathVariable String id,Model model){
User user=userService.getUserById(id);
model.addAttribute("user",user);
return "viewPage";
}
service层
@Override
public boolean add(User user) {
// TODO Auto-generated method stub
boolean flag = false;
Connection connection = null;
try {
connection = BaseDao.getConnection();
connection.setAutoCommit(false);//开启JDBC事务管理
int updateRows = userDao.add(connection,user);
connection.commit();
if(updateRows > 0){
flag = true;
System.out.println("add success!");
}else{
System.out.println("add failed!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
System.out.println("rollback==================");
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally{
//在service层进行connection连接的关闭
BaseDao.closeResource(connection, null, null);
}
return flag;
}
@Override
public boolean modify(User user) {
// TODO Auto-generated method stub
Connection connection = null;
boolean flag = false;
try {
connection = BaseDao.getConnection();
if(userDao.modify(connection,user) > 0)
flag = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return flag;
}
dao层
@Override
public int add(Connection connection, User user) throws Exception {
// TODO Auto-generated method stub
PreparedStatement pstm = null;
int updateRows = 0;
if(null != connection){
String sql = "insert into smbms_user (userCode,userName,userPassword," +
"userRole,gender,birthday,phone,address,creationDate,createdBy) " +
"values(?,?,?,?,?,?,?,?,?,?)";
Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),
user.getUserRole(),user.getGender(),user.getBirthday(),
user.getPhone(),user.getAddress(),user.getCreationDate(),user.getCreatedBy()};
updateRows = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return updateRows;
}
@Override
public int modify(Connection connection, User user) throws Exception {
// TODO Auto-generated method stub
int flag = 0;
PreparedStatement pstm = null;
if(null != connection){
String sql = "update smbms_user set userName=?,"+
"gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),
user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),
user.getModifyDate(),user.getId()};
flag = BaseDao.execute(connection, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return flag;
}
BaseDao类
package cn.kgc.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import cn.kgc.tools.ConfigManager;
/**
* 操作数据库的基类--静态类
* @author Administrator
*
*/
public class BaseDao {
/**
* 获取数据库连接
* @return
*/
public static Connection getConnection(){
Connection connection = null;
String driver = ConfigManager.getInstance().getValue("driver");
String url = ConfigManager.getInstance().getValue("url");
String user = ConfigManager.getInstance().getValue("user");
String password = ConfigManager.getInstance().getValue("password");
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
/**
* 查询操作
* @param connection
* @param pstm
* @param rs
* @param sql
* @param params
* @return
*/
public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs,
String sql,Object[] params) throws Exception{
pstm = connection.prepareStatement(sql);
for(int i = 0; i < params.length; i++){
pstm.setObject(i+1, params[i]);
}
rs = pstm.executeQuery();
return rs;
}
/**
* 更新操作
* @param connection
* @param pstm
* @param sql
* @param params
* @return
* @throws Exception
*/
public static int execute(Connection connection,PreparedStatement pstm,
String sql,Object[] params) throws Exception{
int updateRows = 0;
pstm = connection.prepareStatement(sql);
for(int i = 0; i < params.length; i++){
pstm.setObject(i+1, params[i]);
}
updateRows = pstm.executeUpdate();
return updateRows;
}
/**
* 释放资源
* @param connection
* @param pstm
* @param rs
* @return
*/
public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){
boolean flag = true;
if(rs != null){
try {
rs.close();
rs = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(pstm != null){
try {
pstm.close();
pstm = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
if(connection != null){
try {
connection.close();
connection = null;//GC回收
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flag = false;
}
}
return flag;
}
}
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>mvc01</display-name>
<!--直接地址栏输入工程名就可以跳转到该路径,便捷方式 -->
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
<!--字符编码 添加操作是输入中文为出现乱码 -->
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<!--配置前端控制器DispatcherServlet,拦截url -->
<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: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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- spring扫描包下面所有的类 -->
<context:component-scan base-package="cn.kgc.service"></context:component-scan>
<context:component-scan base-package="cn.kgc.dao"></context:component-scan>
</beans>
springmvc配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="cn.kgc.controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源的文件 -->
<mvc:resources location="/statics/" mapping="/statics/**"/>
<!--全局异常的处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
</property>
</bean>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>