day03
    
   Struts2+Spring整合
   整合结构
  
   整合步骤
  1:搭建Struts2的框架      1:导包     2:配置启动容器web.xml     3:增加配置文件struts.xml    2:搭建Spring的框架      1:导包          spring-webMVC      2:配置启动容器web.xml          connect-param      3:增加配置文件信息applicationcontext.xml          扫描包@controller   3:增加struts-spring-plugin.jar包 
   整合请求流程
  原来:       请求---filter控制器----action----reslut---jsp  现在:         请求---filter控制器(struts2-web.xml)---spring(applicationcontext.xml----id-----action(controller))---result(struts2)---jsp 
   重构代码
  1:导包      <!-- springMVC的依赖包  -->     <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-webmvc</artifactId>         <version>4.3.7.RELEASE</version>     </dependency>      <!-- 整合struts2和spring的插件包 -->     <dependency>         <groupId>org.apache.struts</groupId>         <artifactId>struts2-spring-plugin</artifactId>         <version>2.5.13</version>     </dependency>  2:修改web.xml      <!-- 配置spring的属性文件信息 -->     <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>   3:增加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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">     <!-- 扫描包 -->     <context:component-scan base-package="com.xdl.action"/> </beans>  4:修改action,增加注解      @Controller     //id------helloAction     @Scope(value = "prototype")     public class HelloAction {......     }  5:修改struts.xml,class修改为spring的bean组件ID      <action name="list" class="listAction" method="execute">         <result name="success" type="dispatcher">/WEB-INF/jsp/list.jsp</result>     </action> 
   结合jdbc实现查询功能
  数据库脚本:
  新建一个笔记表note:  CREATE TABLE `note` (   `id` int(30) NOT NULL AUTO_INCREMENT,   `context` varchar(200) DEFAULT NULL,   `publishTime` date DEFAULT NULL,   `likeCount` int(11) DEFAULT NULL,   `userId` int(11) DEFAULT NULL,   PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8  增加并初始化一些测试数据 
  1:导包(mysql驱动包、c3p0连接池包、spring-jdbc包)
      <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-jdbc</artifactId>         <version>4.3.7.RELEASE</version>     </dependency>      <!-- c3p0 -->     <dependency>         <groupId>c3p0</groupId>         <artifactId>c3p0</artifactId>         <version>0.9.1.2</version>     </dependency>      <!-- mysql驱动包 -->     <dependency>         <groupId>mysql</groupId>         <artifactId>mysql-connector-java</artifactId>         <version>5.1.24</version>     </dependency> 
  2:根据数据库表note字段信息,添加note对应的实体类对象信息Note.java
  private Integer id; //主键ID private String context;//内容 private Date publishTime;//发布时间 private Integer likeCount;//收藏人数 private Integer userId;//发布人ID      增加getter和setter方法 
  3:添加数据库连接信息和扫描包信息applicationcontext.xml中
  <context:component-scan base-package="com.xdl.dao"/>  <!-- 数据库连接信息配置 --> <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">     <property name="dataSource" ref="c3p0"/> </bean>  <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">     <property name="user" value="root"/>     <property name="password" value="123456"/>     <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>     <property name="driverClass" value="com.mysql.jdbc.Driver"/> </bean> 
  4:编写NoteDao接口类
  /**  * 根据用户id,查询用户的笔记列表  * @param userId  * @return  */ public List<Note> queryNoteByuserId(Integer userId); 
  5:编写NoteDaoImpl.java来实现NoteDao接口类
  @Repository public class NoteDaoImpl implements NoteDao{  //  @Autowired  //按照类型匹配     @Resource  // 首先按照名称匹配 ,然后按照类型匹配     private JdbcTemplate template;      @Override     public List<Note> queryNoteByuserId(Integer userId) {         String sql = "select id,context,publishTime,likeCount,userId from note where userID=?";         Object[] params = {userId};         List<Note> list = template.query(sql, params, new NoteMapper());         return list;     } } 
  6:添加NoteMapper类
  public class NoteMapper implements RowMapper{      @Override     public Object mapRow(ResultSet rs, int rownum) throws SQLException {         Note note = new Note();         note.setId(rs.getInt("id"));         note.setContext(rs.getString("context"));         note.setLikeCount(rs.getInt("likeCount"));         note.setPublishTime(rs.getDate("publishTime"));         note.setUserId(rs.getInt("userId"));         return note;     } } 
  7:修改ListAction
  /**  * 列表展示  * @author likang  * @date   2018-1-8 下午2:43:23  */ @Controller//id-----listAction @Scope(value = "prototype") public class ListAction {  //  public List<Dept> listDept;     public List<Note> listNote;      @Resource     private NoteDao noteDao;      public String execute(){ //      listDept = new ArrayList<Dept>(); //      for (int i = 0; i < 10; i++) { //          Dept dept = new Dept(); //          dept.setId(Long.valueOf(i)); //          dept.setDeptName("java13_"+i); //          dept.setDeptNote("BeiJing"+i); //          listDept.add(dept); //      }          listNote = noteDao.queryNoteByuserId(1);         return "success";     }      public List<Note> getListNote() {         return listNote;     }      public void setListNote(List<Note> listNote) {         this.listNote = listNote;     }  //  public List<Dept> getListDept() { //      return listDept; //  } // //  public void setListDept(List<Dept> listDept) { //      this.listDept = listDept; //  } } 
  8:修改list.jsp文件
  <table>     <c:forEach items="${listNote }" var="note">         <tr>             <td>${note.id }</td>             <td>${note.context }</td>             <td>${note.publishTime }</td>                </tr>     </c:forEach> </table> 
  9:重新部署启动,并访问
   结合jdbc实现删除功能(使用redirectAction)
  1:修改list.jsp页面,增加删除功能按钮
  <td><a href="delete.do?id=${note.id }" />删除</td> 
  2:修改struts.xml配置文件信息,增加delete的action
  <!-- 删除操作 -->     <!-- <action name="delete" class="deleteAction" method="execute">         <result name="success" type="dispatcher">/WEB-INF/jsp/list.jsp</result>         <result name="error" type="dispatcher">/WEB-INF/jsp/error.jsp</result>     </action> -->     <action name="delete" class="deleteAction" method="execute">         <result name="success" type="redirectAction">             <param name="namespace">/demo</param><!-- 代表的是执行成功后的action命名空间  -->             <param name="actionName">list</param><!-- 代表的是执行成功后重定向的action中的name值  -->         </result>         <result name="error" type="dispatcher">/WEB-INF/jsp/error.jsp</result>     </action>      <!-- 前提:两个action在同一个namespace下面,不建议使用 -->     <!-- <action name="delete" class="deleteAction" method="execute">         <result name="success" type="redirectAction">             list         </result>         <result name="error" type="dispatcher">/WEB-INF/jsp/error.jsp</result>     </action> --> 
  3:添加DeleteAction.java
  /**  * 删除功能操作  * @author likang  * @date   2018-1-9 下午2:22:02  */ @Controller @Scope(value="prototype") public class DeleteAction {      private Integer id;//接收请求中删除操作的数据ID      @Resource     private NoteDao noteDao;      public String execute(){         int count = noteDao.deleteNoteById(id);         if (count > 0) {             return "success";         }         return "error";     }      public Integer getId() {         return id;     }      public void setId(Integer id) {         this.id = id;     }  } 
  4:在接口NoteDao中增加删除的方法接口
  /**  * 根据主键ID,删除笔记信息  * @param id 主键ID  * @return  */ public int deleteNoteById(Integer id); 
  5:实现接口中的方法
  @Override public int deleteNoteById(Integer id) {     String sql = "delete from note where id=?";     return template.update(sql, id); } 
  6:添加错误提示页面error.jsp
  <h1>程序处理异常.....</h1> 
  7:部署、启动、访问
   抽取数据库属性文件
  jdbc.properties
  user=root password=123456 jdbcUrl=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=utf-8 driverClass=com.mysql.jdbc.Driver 
  applicationcontext.xml:
  <!-- 引用外部的属性文件到spring的配置文件中 --> <context:property-placeholder location="classpath:jdbc.properties"/>  <!-- 数据库连接信息配置 --> <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">     <property name="dataSource" ref="c3p0"/> </bean>  <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">     <property name="user" value="${user}"/>     <property name="password" value="${password}"/>     <property name="jdbcUrl" value="${jdbcUrl}"/>     <property name="driverClass" value="${driverClass}"/> </bean> 
   登录页面功能、登录按钮实现
  需求:
  
  struts.xml:
  <!-- 登录、用户功能 --> <package name="user" extends="struts-default" namespace="/user">     <!-- 跳转登录页,使用默认配置 -->     <action name="toLogin">         <result>/WEB-INF/jsp/login.jsp</result>     </action>      <!-- 登录按钮功能 -->     <action name="login" class="loginAction" method="execute">         <result name="success" type="dispatcher">/WEB-INF/jsp/ok.jsp</result>         <!-- <result name="error" type="dispatcher">/WEB-INF/jsp/error.jsp</result> -->         <!-- <result name="error" type="redirectAction">             toLogin         </result> -->         <result name="error" type="dispatcher">/WEB-INF/jsp/login.jsp</result>     </action> </package> 
  LoginAction.java:
  /**  * 登录功能  * @author likang  * @date   2018-1-9 下午4:37:09  */ @Controller @Scope("prototype") public class LoginAction {      private String username;//接收请求参数用户名     private String password;//接收请求参数密码      private String msg;//将错误信息,传输到前端页面      public String execute(){          if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {             if ("admin".equals(username) && "123123".equals(password)) {                 return "success";             }         }         msg="用户名或者密码错误";         return "error";     }      public String getMsg() {         return msg;     }     public void setMsg(String msg) {         this.msg = msg;     }     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;     } } 
  login.jsp:
  <body>      <h1>登录页面</h1>     <span style="color: red;">${msg }</span>     <form action="login.do" method="post">         用户名:<input id="username" name="username" type="text"><br/>         密码:<input id="password" name="password" type="password"><br/>         <input type="submit" value="登录">     </form>  </body> 
  ok.jsp:
  <h1>登录成功,欢迎访问</h1> <a href="toLogin.do">退出</a> 
   登录使用session
   struts2组件列表