Maven+ssm框架简单增删改查

语录:在开发一个项目时,一定要注意细节,谨慎严密,多查多问,保持足够耐心。

         世上无难事,只怕有心人


一:创建一个Maven项目

      

    注意: 1.Build Path-Configure Build Path   修改成对应的jdk版本

二:pom.xml导入相应的包

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.test</groupId>
	<artifactId>String_fate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<!-- spring版本号 -->
		<spring.version>4.0.2.RELEASE</spring.version>
		<!-- mybatis版本号 -->
		<mybatis.version>3.2.6</mybatis.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.7.7</slf4j.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>

		</dependency>
		<!-- spring核心包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- mybatis核心包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- 导入java ee jar 包 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
		</dependency>
		<!-- 导入Mysql数据库链接jar包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.30</version>
		</dependency>
		<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<!-- JSTL标签类 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>

		<!-- 格式化对象,方便输出日志 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.41</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.7</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<!-- log end -->
		<!-- 映入JSON -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<!-- 上传组件包 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>SSMDemo</finalName>
		<plugins>
			<!-- 生成代码工具 -->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<verbose>true</verbose>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>utf8</encoding>
				</configuration>
			</plugin>

		</plugins>

		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
	</build>

</project>


三.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"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
                        
   <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
   <context:component-scan base-package="com.test.controller" />
   <context:component-scan base-package="com.test.service" />    
     
   <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
   <bean id="mappingJacksonHttpMessageConverter"
      class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
      <property name="supportedMediaTypes">
         <list>
            <value>text/html;charset=UTF-8</value>
         </list>
      </property>
   </bean>
   <!-- 启动SpringMVC的注解功能,完成请求和注解ENTITY的映射 -->
   <bean
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="messageConverters">
         <list>
            <ref bean="mappingJacksonHttpMessageConverter" />  <!-- JSON转换器 -->
         </list>
      </property>
   </bean>
   <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
      <!-- <property name="prefix" value="/WEB-INF/view" /> -->
      <!--jsp、html文件所在的目录  -->
      <property name="prefix" value="/WEB-INF/view/" />
      <property name="suffix" value=".jsp" />
      <property name="order" value="1" />
   </bean>
   <!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 -->
   <!-- 启用基于Spring的注解 -->
   <context:annotation-config/>
   <!--<!– 静态资源处理 –>
   <!– 比如图片 js,css文件等静态资源 –>
   <mvc:resources mapping="/css/**" location="/styset/css/" />
   <mvc:resources mapping="/js/**" location="/styset/js/" />
   <mvc:resources mapping="/imgs/**" location="/styset/imgs/" />--> 
</beans> 


四.创建generatorConfig.xml文件并maven-build

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<classPathEntry
            location="G:\spring-framework-4.2.8.RELEASE\mysql-connector-java-5.0.8.tar\mysql-connector-java-5.0.8\mysql-connector-java-5.0.8-bin.jar"/>
  <context id="context1" >

<!-- 数据库连接 修改数据库名 账号 密码-->

    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/mysql" userId="root" password="199701" />

<!--在 src下创建的model包里生成model实体类文件,在包mapper里面生成配置文件,在包dao里面生成dao接口-->

<!--tableName对应数据库表-->

    <javaModelGenerator targetPackage="model" targetProject="src\main\java" />
    <sqlMapGenerator targetPackage="mapper" targetProject="src\main\java" />
    <javaClientGenerator targetPackage="dao" targetProject="src\main\java" type="XMLMAPPER" />
    <table schema="" tableName="user2" >
      <columnOverride column="user2" property="user2" />
    </table>
  </context>
</generatorConfiguration>



五.在eclipse对generatorConfig.xml进行Maven-build,生成表对应的model以及dao接口以及配置文件 

   

       代码就不写下来了

六.整合mabaties,在spring-mabaties.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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd  
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
    <!-- 自动扫描 -->  
    <context:component-scan base-package="com.test" />
    <!-- 告知Spring启用注解驱动 -->
    <mvc:annotation-driven />


    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driverClassName}"/>  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        <!-- 初始化连接大小 -->  
        <property name="initialSize" value="${initialSize}"></property>  
        <!-- 连接池最大数量 -->  
        <property name="maxActive" value="${maxActive}"></property>  
        <!-- 连接池最大空闲 -->  
        <property name="maxIdle" value="${maxIdle}"></property>  
        <!-- 连接池最小空闲 -->  
        <property name="minIdle" value="${minIdle}"></property>  
        <!-- 获取连接最大等待时间 -->  
        <property name="maxWait" value="${maxWait}"></property> 
    </bean>  
  
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>  
  
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>    
    

</beans>


七.配置日志文件log4j.properties和common-logging.properties,以及jdbc.properties

1.log4j.properties

   ### set log levels ###
log4j.rootLogger = debug , stdout , D , E


### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
## \u8F93\u51FAINFO\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n


### \u8F93\u51FA\u5230\u65E5\u5FD7\u6587\u4EF6 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D:/logs/log.log
log4j.appender.D.Append = true
## \u8F93\u51FADEBUG\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n


### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
## \u5F02\u5E38\u65E5\u5FD7\u6587\u4EF6\u540D
log4j.appender.E.File = D:/logs/error.log
log4j.appender.E.Append = true
## \u53EA\u8F93\u51FAERROR\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7!!!
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout

log4j.rootLogger = debug , stdout , D , E


### \u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
## \u8F93\u51FAINFO\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{1}:%L - %m%n


### \u8F93\u51FA\u5230\u65E5\u5FD7\u6587\u4EF6 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D:/logs/log.log
log4j.appender.D.Append = true
## \u8F93\u51FADEBUG\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n


### \u4FDD\u5B58\u5F02\u5E38\u4FE1\u606F\u5230\u5355\u72EC\u6587\u4EF6 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
## \u5F02\u5E38\u65E5\u5FD7\u6587\u4EF6\u540D
log4j.appender.E.File = D:/logs/error.log
log4j.appender.E.Append = true
## \u53EA\u8F93\u51FAERROR\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7!!!
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

2.common-logging.properties

 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

3.jdbc.properties 

 #创建连接
driverClassName=com.mysql.jdbc.Driver
#地址
url=jdbc:mysql://localhost:3306/mysql
#用户名
username=root
#密码
password=199701

##以下可以不配
#初始化连接
initialSize=10
#最大连接数量
maxActive=300
#最大空闲连接
maxIdle=20
#最大空闲连接
minIdle=1
#等待时间

maxWait=60000


八.配置web.xml

 

<web-app version="3.0" 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_3_0.xsd">
	<display-name>spring_fate</display-name>
	<!-- 加载Spring容器配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>


	<!-- 设置Spring容器加载所有的配置文件的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<!-- <param-value>classpath:config/spring-*.xml</param-value> -->
		<param-value>classpath:spring-mybatis.xml,classpath:spring-mvc.xml</param-value>

	</context-param>

	<!-- 配置SpringMVC核心控制器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mybatis.xml,classpath:spring-mvc.xml</param-value>
		</init-param>
		<!-- 启动加载一次 -->
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!--为DispatcherServlet建立映射 -->
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- 解决工程编码过滤器 -->
	<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>

</web-app>


九.建立service以及service实现(Userservice.java UserserviceImpl)

 package com.test.service;
import java.util.List;
import model.User2;

public interface UserService {
	 void insert(User2 user2);
	 boolean update(User2 user2);
	 boolean delete(int user2Id);
	 User2 select(int user2Id);
	 List<User2> findAll();

}

 

package com.test.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dao.User2Mapper;
import model.User2;
@Service  
@Transactional 
//此处不再进行创建SqlSession和提交事务,都已交由spring去管理了。  
public class UserServiceImpl implements UserService {
    @Resource  
    private User2Mapper mapper;  
	
	public void insert(User2 user2) {
		mapper.insert(user2);
	}
	public boolean update(User2 user2) {
		return mapper.update(user2);
	}
	public boolean delete(int user2Id) {
		return mapper.delete(user2Id);
	}
	public User2 select(int user2Id) {
	User2 user2=mapper.select(user2Id);
	return user2;
	}
	public List<User2> findAll() {
	List<User2> findlist=mapper.findAll();
	return findlist;
	}

}


十.建立控制层(Usercontroller.java)

 

package com.test.controller;

import java.util.List;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.test.service.UserService;

import model.User2;



@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	/**
	 * 获取所有用户列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getAllUser")
	public String getAlluser(HttpServletRequest request, Model model) {
		List<User2> user = userService.findAll();
		System.out.println(user);
		model.addAttribute("userlist", user);
		request.setAttribute("userlist", user);
		return "/allUser";
	}
	/**
	 * 跳转到添加用户界面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddUser")
	public String toAddUser() {
		return "/addUser";
	}
	/**
	 * 添加用户并重定向
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/addUser")
	public String addUser(User2 user, Model model) {
		userService.insert(user);
		 return "redirect:/user/getAllUser"; 
	}
	/*
	 * 编辑用户
	 * 
	 * @param user
	 * 
	 * @param request
	 * 
	 * @return
	 */
	@RequestMapping("/updateUser")
	public String updateUser(User2 user2, HttpServletRequest request, Model model) {
		if (userService.update(user2)) {
			user2 = userService.select(user2.getUser2Id());
			request.setAttribute("user", user2);
			model.addAttribute("user", user2);
			return "redirect:/user/getAllUser";
		} else {
			return "/error";
		}
	}

	/*
	 * 根据id查询单个用户
	 * 
	 * @param id
	 * 
	 * @param request
	 * 
	 * @return
	 */
	@RequestMapping("/getUser")
	public String getUser(int id, HttpServletRequest request, Model model) {
		request.setAttribute("user", userService.select(id));
		model.addAttribute("user", userService.select(id));
		return "/editUser";
	}
	/**
	 * 删除用户
	 * 
	 * @param id
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delUser")
	public String delUser(int id, HttpServletRequest request, HttpServletResponse response) {
		String result = "/error";  
        if(userService.delete(id)){  
            result = "forward:/user/getAllUser";  
        } 
        return result;
		}	
}


十一.创建视图层(index.jsp,addUser,allUser,editUser)

  1.index.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path=request.getContextPath();
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
     %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>首页</title>
</head>
<body>
  <h2 align="center">
        <a href="<%=basePath%>user/getAllUser">进入用户管理系统</a>
  </h2>
</body>

</html>

 2.allUser.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path=request.getContextPath();
    String basePath = request.getScheme() + "://"  
    + request.getServerName() + ":" + request.getServerPort() + path + "/";%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <base href="<%=basePath%>">  
    <script type="text/javascript" src="webapp/jquery-3.3.1.js"></script>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title> 
</head>
<body>
      <h3 align="right"><a href="<%=basePath%>user/toAddUser">添加用户</a></h3>
      <table border="1">
      <tbody> 
      <tr>
      <th>姓名</th>
      <th>职位</th>
      <th>操作</th>
      </tr>
      <c:if test="${!empty userlist }">
      <c:forEach items="${userlist }" var="user1">
      <tr>
      <td>${user1.userName }</td>
      <td>${user1.passWord }</td>
       <td><a href="<%=basePath%>user/getUser?id=${user1.user2Id }">编辑</a>  
           <a href="<%=basePath%>user/delUser?id=${user1.user2Id }">删除</a>   
           </td> 
      </tr> 
      </c:forEach>
      </c:if>
      </tbody>
      </table>
</body>

</html>

 3.editUser.jsp 

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path=request.getContextPath();
    String basePath = request.getScheme() + "://"  
    + request.getServerName() + ":" + request.getServerPort() + path + "/";%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">  
    <script type="text/javascript" src="webapp/jquery-3.3.1.js"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
#ch{
width: 100px;
height: 50px;
}
</style>
<title>编辑用户</title>
</head>
<body>
<form action="<%=basePath%>user/updateUser" method="post">
    <h1 align="center">编辑用户</h1>
    <input type="hidden" name="user2Id" value="${user.user2Id }"/>  
    <h3>姓名:</h3><input type="text" name="userName" value=${user.userName }>
    <h3>职位:</h3><input type="text" name="passWord" value=${user.passWord }>
    <input type="submit" value="编辑" id="ch">
    </form>
</body>

</html>

4.addUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path=request.getContextPath();
    String basePath = request.getScheme() + "://"  
    + request.getServerName() + ":" + request.getServerPort() + path + "/";%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>添加用户</title>
<style type="text/css">
#ch{
width: 100px;
height: 50px;
}
</style>
</head>
<body> 
  <h1 align="center">添加用户</h1>
  <form action="<%=basePath%>user/addUser" method="post">
      <p align="center"> 姓名:<input type="text" name="userName"></p>
      <p align="center"> 职位:<input type="text" name="passWord"></p>
      <input type="submit" value="增加" id="ch">
  </form>

</body>

</html>

以上就是所有代码,目录如下


需要从外导入的有 jQuery-3.31.min.js

数据库如下:


展示:




展开阅读全文

没有更多推荐了,返回首页