注意:这里使用jdk1.7版本
文件报错是因为jdk版本太高jdk1.7版本就不报错

框架搭建

一、web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>SSM03</display-name>
 4   <!-- 运行欢迎页 -->
 5   <welcome-file-list>
 6     <welcome-file>index.jsp</welcome-file>
 7   </welcome-file-list>
 8   
 9   <!--SSM整合框架  -->
10   <!-- spring的核心配置 -->
11       <!--配置spring上下文 -->
12           <context-param>
13                 <param-name>contextConfigLocation</param-name>
14                   <!-- 这里要扫描spring设置 和spring里mybatis的设置-->
15                 <param-value>classpath:applicationContext.xml</param-value>
16             </context-param>        
17         <!-- 配置spring监听器 -->
18               <listener>
19                 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
20             </listener>
21     <!-- SpringMVC核心配置 -->
22         <!--  配置SpringMVC核心控制器  -->
23         <servlet>
24                
25                 <servlet-name>springmvc</servlet-name>
26                 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27             
28             
29                 <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 
30                    如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
31                
32                 <init-param>
33                     <param-name>contextConfigLocation</param-name>
34                                  <!-- 这里要扫描springmvc的跳转和传输设置 -->
35                              
36                     <param-value>classpath:spring-mvc.xml</param-value>
37                 </init-param>
38                 <!-- 优先等及 -->
39                         <load-on-startup>1</load-on-startup>
40             </servlet> 
41         
42         <servlet-mapping>
43                 <servlet-name>springmvc</servlet-name>
44                 <url-pattern>*.do</url-pattern>
45         </servlet-mapping>
46         
47          <!-- post乱码过虑器 -->
48         <filter>
49             <filter-name>CharacterEncodingFilter</filter-name>
50             <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
51             <init-param>
52                 <param-name>encoding</param-name>
53                 <param-value>utf-8</param-value>
54             </init-param>
55         </filter>
56         <filter-mapping>
57             <filter-name>CharacterEncodingFilter</filter-name>
58             <url-pattern>/*</url-pattern>
59         </filter-mapping>
60 
61 
62     
63     <!-- Mybatis核心配置 -->
64     <!-- 对于数据持久层的框架而言,都交给spring处理 -->
65 
66   
67   
68 </web-app>

二、配置spring-mvc.xml

<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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-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/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        
    <!-- 开启springmvc -->                      
    <context:annotation-config />
    <!-- 注解扫描包 -->
    <context:component-scan base-package="com.ssm.controller" />
    <context:component-scan base-package="com.ssm.service" />
     <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
        
        
</beans>

三、配置spring(applicationContext.xml)

 1 <beans xmlns="http://www.springframework.org/schema/beans"
 2     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 3     xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
 7         http://www.springframework.org/schema/mvc 
 8         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
 9         http://www.springframework.org/schema/context 
10         http://www.springframework.org/schema/context/spring-context-3.2.xsd 
11         http://www.springframework.org/schema/aop 
12         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
13         http://www.springframework.org/schema/tx 
14         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15         
16         
17         <!-- IOC -->
18         <!-- web.xml交给spring配置的东西 -->
19         <!-- 配置mybatis -->
20         <!-- 导入数据源 ,dbcp -->
21         <context:property-placeholder location="classpath:db.properties" />
22         <!-- 配置数据源 ,dbcp -->
23     
24         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
25             destroy-method="close">
26             <property name="driverClassName" value="${jdbc.driver}" />
27             <property name="url" value="${jdbc.url}" />
28             <property name="username" value="${jdbc.username}" />
29             <property name="password" value="${jdbc.password}" />
30         </bean>
31 
32         <!-- 创建sqlSessionFactory -->
33         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
34             <!-- 数据源(数据库连接池) -->
35             <property name="dataSource" ref="dataSource" />
36             <!-- 加载mybatis的全局配置文件 -->
37             <property name="configLocation" value="classpath:mybatis-Config.xml" />
38         </bean>
39         
40         <!-- mapper扫描器 -->
41         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
42             <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
43             <property name="basePackage" value="com.ssm.mapper"></property>
44             <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
45         </bean>
46 
47         <!-- AOP:16个字 -->
48         <!-- 事务管理 -->
49         <!-- 创建事务管理器 -->
50         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
51             <!-- 数据源  -->
52             <property name="dataSource" ref="dataSource"/>
53         </bean>
54 
55         <!-- 创建通知:事务管理器管理通知 -->
56         <tx:advice id="txAdvice" transaction-manager="transactionManager">
57             <tx:attributes>
58                 <!-- 传播行为 -->
59                 <tx:method name="save*" propagation="REQUIRED"/>
60                 <tx:method name="delete*" propagation="REQUIRED"/>
61                 <tx:method name="insert*" propagation="REQUIRED"/>
62                 <tx:method name="update*" propagation="REQUIRED"/>
63                 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
64                 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
65                 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
66             </tx:attributes>
67         </tx:advice>
68 
69         <!-- 要扫描的serviceImpl包 aop -->
70         <aop:config>
71             <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ssm.service.*.*(..))"/>
72         </aop:config>
73         
74 </beans>

四、

1.创建db.properties,并赋值

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hahaha
jdbc.username=root
jdbc.password=123456

2.mybatis的全局配置文件(mybatis-config.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 全局setting配置,根据需要添加 -->

    <!-- 配置别名 -->
    <typeAliases>
        <!-- 批量扫描别名 -->
        <package name="com.ssm.po"/>
    </typeAliases>

    <!-- 配置mapper
    由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
    必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
     -->

    <!-- <mappers>

    </mappers> --> 
</configuration>

 

写入项目

如图

一、创建实例对象(t_role.java)

 1 package com.ssm.entity;
 2 
 3 public class t_role {
 4     private int id;
 5     private String tname;
 6     private String phon;
 7     private String endtimes;
 8     private String sname;
 9     public int getId() {
10         return id;
11     }
12     public void setId(int id) {
13         this.id = id;
14     }
15     public String getTname() {
16         return tname;
17     }
18     public void setTname(String tname) {
19         this.tname = tname;
20     }
21     public String getPhon() {
22         return phon;
23     }
24     public void setPhon(String phon) {
25         this.phon = phon;
26     }
27     public String getEndtimes() {
28         return endtimes;
29     }
30     public void setEndtimes(String endtimes) {
31         this.endtimes = endtimes;
32     }
33     public String getSname() {
34         return sname;
35     }
36     public void setSname(String sname) {
37         this.sname = sname;
38     }
39     public t_role() {
40         
41     }
42     public t_role(int id, String tname, String phon, String endtimes, String sname) {
43         this.id = id;
44         this.tname = tname;
45         this.phon = phon;
46         this.endtimes = endtimes;
47         this.sname = sname;
48     }
49     @Override
50     public String toString() {
51         return "t_role [id=" + id + ", tname=" + tname + ", phon=" + phon + ", endtimes=" + endtimes + ", sname="
52                 + sname + "]";
53     }
54     
55     
56     
57     
58    
59 }

二、创建tMapper.java和tMapper.xml

 

tMapper.java

package com.ssm.mapper;

import java.util.List;

import com.ssm.entity.t_role;


public interface tMapper {
    void save(t_role t_role); 
    int update(t_role t_role);
    boolean delete(int id);
    t_role findById(int id);
    List<t_role> findAll();
}

tMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper 
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.mapper.tMapper">
    <!-- 添加 -->
    <insert id="save" parameterType="com.ssm.entity.t_role">
        INSERT INTO t_role(id,tname,phon,endtimes,sname) VALUES(#{id},#{tname},#{phon},#{endtimes},#{sname})
    </insert>
    <!-- 修改 -->
    <update id="update" parameterType="com.ssm.entity.t_role">
        UPDATE t_role SET tname=#{tname},phon=#{phon},endtimes=#{endtimes},sname=#{sname} where id=#{id}
    </update>
    <!-- 删除 -->
    <delete id="delete" parameterType="int">
        DELETE FROM t_role WHERE id=#{id}
    </delete>
    <!-- 查询 -->
    <select id="findById" parameterType="int" resultType="com.ssm.entity.t_role">
        SELECT * FROM t_role WHERE id=#{id}
    </select>
    <!-- 查询 -->
    <select id="findAll" resultType="com.ssm.entity.t_role">
        SELECT * FROM t_role
    </select>
    <!-- 分页 -->
    <select id="selectUsersByPage" parameterType="int" resultType="com.ssm.entity.t_role">
           SELECT TOP 10 * FROM
        (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROWNUMBER,* FROM t_role )
        AS A WHERE ROWNUMBER>10*(#{page}-1)
    </select>
</mapper>

 

 

三、创建tservice.java和tserviceImpl.java

tservice.java

package com.ssm.service;

import java.util.List;

import com.ssm.entity.t_role;

public interface tservice {
         void save(t_role t_role); 
        int update(t_role t_role);
        boolean delete(int id);
        t_role findById(int id);
        List<t_role> findAll();
}

tserviceImpl.java

 1 package com.ssm.service;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Service;
 9 import org.springframework.transaction.annotation.Transactional;
10 
11 import com.ssm.entity.t_role;
12 import com.ssm.mapper.tMapper;
13 //声明是service层
14 @Service
15 public class tserviceImpl implements tservice {
16     @Autowired
17  //相当于servlet的 service service=new service();
18     private tMapper tMapper;
19     public void save(t_role t_role) {
20         tMapper.save(t_role);
21         
22     }
23 
24     @Override
25     public int update(t_role t_role) {
26         
27         return tMapper.update(t_role);
28     }
29 
30     @Override
31     public boolean delete(int id) {
32 
33         return tMapper.delete(id);
34         
35     }
36 
37     @Override
38     public t_role findById(int id) {
39         
40         return tMapper.findById(id);
41     }
42 
43     @Override
44     public List<t_role> findAll() {
45         
46         return tMapper.findAll();
47     }
48 
49 }

四、tcontroller.java

 1 package com.ssm.controller;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.List;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.ui.Model;
13 import org.springframework.web.bind.annotation.RequestMapping;
14 
15 import com.ssm.entity.t_role;
16 import com.ssm.service.tservice;
17 //声明是控制层
18 @Controller
19 public class tcontroller {
20     //相当于servlet的 service service=new service();
21     @Autowired
22     private tservice tservice;
23     @RequestMapping("/findall.do")
24      public String getAllUser(HttpServletRequest request,Model model){
25         List<t_role> tlist=tservice.findAll();
26         model.addAttribute("List",tlist);
27         request.setAttribute("List",tlist);
28         return "/findall";
29     }
30     @RequestMapping("/toadd.do")
31     public String toAddUser()
32     {
33         return "/toadd";
34     }
35     @RequestMapping("/add.do")
36     public String add(t_role t_role){
37         tservice.save(t_role);
38         return "redirect:/findall.do";
39     }
40     @RequestMapping("/toupdate.do")
41     public String toupdate(t_role t_role,HttpServletRequest request,Model model){
42         
43             t_role=tservice.findById(t_role.getId());
44             request.setAttribute("t_role",t_role);
45             model.addAttribute("t_role",t_role);
46             return "toupdate";
47        
48     }
49     @RequestMapping("/update.do")
50     public String update(t_role t_role,HttpServletRequest request,Model model){
51         if(tservice.update(t_role)!=0)
52         {
53             t_role=tservice.findById(t_role.getId());
54             request.setAttribute("t_role",t_role);
55             model.addAttribute("t_role",t_role);
56             return "redirect:/findall.do";
57         }
58         else {
59             return "/error";                    
60         }
61     }
62     @RequestMapping("/delete.do")
63     public void delUser(int id,HttpServletRequest request,HttpServletResponse response){
64         String result="{"result":"error"}";
65         if(tservice.delete(id))
66         {
67             result="{"result":"success"}";
68         }else {
69             result="{"result":"error"}";
70         }
71         response.setContentType("application/json");
72         try {
73             PrintWriter out=response.getWriter();
74             out.write(result);
75         } catch (IOException e) {
76             // TODO Auto-generated catch block
77             e.printStackTrace();
78         }
79     }
80     
81 
82 }

五、jsp文件和index欢迎页

findall.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'allUser.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22     <script type="text/javascript" src="/js/jquery-1.8.2.min.js"></script>
23     <script type="text/javascript">  
24       
25       </script>
26   </head>
27   
28   <body>
29     <h6><a href="<%=basePath%>toadd.do">添加用户</a></h6>
30     <table border="1">
31         <tbody>
32             <tr>
33                 <th>id</th>
34                 <th>登录名</th>
35                 <th>手机号</th>
36                 <th>最后一次修改时间</th>
37                 <th>所属角色</th>
38                 <th>操作</th>
39                 
40                
41             </tr>
42             <c:if test="${!empty List}">
43                 <c:forEach items="${List}" var="List">
44                     <tr>
45                         <td>${List.id}</td>
46                         <td>${List.tname}</td>
47                         <td>${List.phon}</td>
48                         <td>${List.endtimes}</td>
49                         <td>${List.sname}</td>
50                         <td>  
51                             <a href="<%=basePath%>toupdate.do?id=${List.id}">编辑</a>  
52                             <a href="javascript:del('${List.id}')">删除</a>  
53                         </td>
54                     </tr>
55                 </c:forEach>
56             </c:if>
57         </tbody>
58     </table>
59   </body>
60 </html>

 

toadd.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 7 <html>
 8   <head>
 9     <base href="<%=basePath%>">
10     
11     <title>My JSP 'addUser.jsp' starting page</title>
12     
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21     <script type="text/javascript" src="../js/jquery-1.8.2.min.js"></script>
22     <script type="text/javascript">
23             function add(){  
24             var form = document.forms[0];  
25             form.action = "<%=basePath%>add.do";  
26             form.method="post";  
27             form.submit();
28         }
29     </script>
30   </head>
31   
32   <body>
33     <h1><%=path%>添加用户<%=basePath%></h1>  
34     <form action="" name="userForm">  
35         ID:<input type="text" name="id">  
36         登录名:<input type="text" name="tname">  
37         手机号:<input type="text" name="phon">  
38         最后一次修改时间:<input type="text" name="endtimes"> 
39         所属角色<input type="text" name="sname"> 
40         <input type="button" value="添加" onclick="add()">  
41     </form> 
42   </body>
43 </html>

toupdate.jsp

<%@ page language="java" import="java.util.*" 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">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'editUser.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">
    -->
    <script type="text/javascript" src="../js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">  
        function update(){ 
            var form=document.forms[0];
            form.action="<%=basePath%>update.do";
            form.method="post";  
            form.submit() ; 
        }  
    </script>
    </head>
  
  <body>
  <h1>修改用户</h1>  
    <form action="" name="userForm">  
        <input type="hidden" name="id" value="${t_role.id}"/> 
        ID:<a>${t_role.id}</a> 
        登录名:<input type="text" name="tname" value="${t_role.tname}"/>  
        手机号:<input type="text" name="phon" value="${t_role.phon}"/>  
        最后一次修改时间:<input type="text" name="endtimes" value="${t_role.endtimes}"/> 
        所属角色:<input type="text" name="sname" value="${t_role.sname}"/> 
        <input type="button" value="编辑" onclick="update()"/>  
    </form> 
  </body>
</html>

 

index.jsp

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10      <form action="findall.do">
11          <input type="submit" value="查询">
12      </form>
13 
14 </body>
15 </html>

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/laogao2333/p/14884427.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!