3、mybatis动态sql+struts2(通配符+全局配置+分页)

1.创建userinfo.sql数据库脚本

 1 create table USERINFO
 2 (
 3   id       NUMBER not null,
 4   uname    VARCHAR2(20),
 5   password VARCHAR2(20),
 6   age      NUMBER
 7 )
 8 ;
 9 alter table USERINFO add primary key (ID);
10
11 create sequence seq_userinfo;
12
13 insert into USERINFO (id, uname, password, age)
14 values (seq_userinfo.nextval, ‘holly‘, ‘123‘, 18);
15 insert into USERINFO (id, uname, password, age)
16 values (seq_userinfo.nextval, ‘石头‘, ‘123‘, 18);
17 insert into USERINFO (id, uname, password, age)
18 values (seq_userinfo.nextval, ‘朱亚楠‘, ‘123‘, 18);
19 insert into USERINFO (id, uname, password, age)
20 values (seq_userinfo.nextval, ‘大嘴‘, ‘123‘, null);
21 commit;

userinfo.sql

2.创建如下项目结构

3.在项目WebRoot的WEB-INF下的lib中加入如下jar文件

4.在com.entity包下创建UserInfo.java

 1 package com.entity;
 2
 3 import com.page.Page;
 4
 5 /**
 6  * 用户信息表
 7  * @author pc
 8  *
 9  */
10 public class UserInfo {
11     private Integer id;
12     private String uname;
13     private String password;
14     private Page page; //分页数据封装类
15
16     public UserInfo() {
17     }
18
19     public UserInfo(Integer id) {
20         this.id = id;
21     }
22
23
24     public UserInfo(Page page) {
25         this.page = page;
26     }
27
28     public UserInfo(String uname, String password) {
29         this.uname = uname;
30         this.password = password;
31     }
32     public UserInfo(Integer id, String uname, String password) {
33         this.id = id;
34         this.uname = uname;
35         this.password = password;
36     }
37     public Integer getId() {
38         return id;
39     }
40     public void setId(Integer id) {
41         this.id = id;
42     }
43     public String getUname() {
44         return uname;
45     }
46     public void setUname(String uname) {
47         this.uname = uname;
48     }
49     public String getPassword() {
50         return password;
51     }
52     public void setPassword(String password) {
53         this.password = password;
54     }
55
56     public Page getPage() {
57         return page;
58     }
59
60     public void setPage(Page page) {
61         this.page = page;
62     }
63
64     @Override
65     public String toString() {
66         return "UserInfo [id=" + id + ", password=" + password + ", uname="
67                 + uname + "]";
68     }
69
70
71 }

UserInfo.java

5.在com.mapper包下创建UserInfoMapper.java映射接口

 1 package com.mapper;
 2
 3 import java.util.List;
 4
 5 import com.entity.UserInfo;
 6
 7 public interface UserInfoMapper {
 8     /**
 9      * 根据id查询
10      * @param id
11      * @return
12      */
13     //public UserInfo getById(int id);
14     /**
15      * 根据对象查询对象
16      * @param user
17      * @return
18      */
19     //public UserInfo getByNamePwd(UserInfo user);
20     /**
21      * 查询所有和根据条件查询
22      * @return
23      */
24     public List<UserInfo> getAllAndWhere(UserInfo user);
25     /**
26      * 添加
27      * @param user
28      * @return
29      */
30     public Integer saveUser(UserInfo user);
31     /**
32      * 修改
33      * @param user
34      * @return
35      */
36     public Integer updateUser(UserInfo user);
37
38
39     /**
40      * 根据id删除
41      * @param id
42      * @return
43      */
44     public Integer deleteUser(int id);
45
46     /**
47      * 查询总记录数
48      * @return
49      */
50     public Integer getTotalCount();
51
52 }

UserInfoMapper.java

6.在com.mapper包下创建UserInfoMapper.xml映射文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="com.mapper.UserInfoMapper">
 4     <!-- 查询所有和根据条件查询 -->
 5     <select id="getAllAndWhere" parameterType="User" resultType="User">
 6         <choose>
 7             <!-- 分页查询 -->
 8             <when test="page!=null">
 9               <![CDATA[
10                select * from
11                 (
12                   select rownum r,id,uname,password from userinfo
13                    where rownum<=#{page.startrow}
14                 )u
15                 where u.r>#{page.endrow}
16                 ]]>
17             </when>
18             <otherwise>
19                 select * from userinfo
20                 <where>
21                     <choose>
22                         <!-- 根据用户名和密码查询 -->
23                         <when test="uname!=null and password!=null">
24                             and uname=#{uname} and password=#{password}
25                         </when>
26                         <otherwise>
27                             <!-- 根据id查询 -->
28                             <if test="id!=null">
29                                 and id=#{id}
30                             </if>
31                         </otherwise>
32                     </choose>
33                 </where>
34             </otherwise>
35         </choose>
36
37     </select>
38     <!-- 修改 -->
39     <update id="updateUser" parameterType="User">
40         update userinfo set uname=#{uname},password=#{password} where id=#{id}
41     </update>
42
43     <!-- 添加 -->
44     <insert id="saveUser" parameterType="User">
45         insert into userinfo(id,uname,password)
46         values(seq_userinfo.nextval,#{uname},#{password})
47    </insert>
48     <!-- 删除 -->
49     <delete id="deleteUser" parameterType="int">
50         delete from userinfo where id=#{id}
51    </delete>
52     <!-- 查询总条数 -->
53     <select id="getTotalCount" resultType="Integer">
54         select count(*) from userinfo
55    </select>
56
57 </mapper>

UserInfoMapper.xml

7.在src下创建jdbc.properties的连接数据库的属性文件

1 driver=oracle.jdbc.driver.OracleDriver
2 url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl
3 username=holly
4 password=sys

jdbc.properties

8.在src下创建日志文件log4j.properties属性文件

 1 log4j.rootLogger=DEBUG, Console
 2
 3 #Console
 4 log4j.appender.Console=org.apache.log4j.ConsoleAppender
 5 log4j.appender.Console.layout=org.apache.log4j.PatternLayout
 6 log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
 7
 8 log4j.logger.java.sql.ResultSet=INFO
 9 log4j.logger.org.apache=INFO
10 log4j.logger.java.sql.Connection=DEBUG
11 log4j.logger.java.sql.Statement=DEBUG
12 log4j.logger.java.sql.PreparedStatement=DEBUG   

log4j.properties

9.在src下创建mybatis的主配置文件configuration.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
 3 <configuration>
 4   <!-- 引用属性文件 -->
 5   <properties resource="jdbc.properties"/>
 6
 7   <!-- 定义别名 -->
 8   <typeAliases>
 9     <typeAlias type="com.entity.UserInfo" alias="User"/>
10   </typeAliases>
11
12   <!-- 数据源配置 -->
13   <environments default="development">
14     <environment id="development">
15       <transactionManager type="JDBC"/>
16       <dataSource type="POOLED">
17         <property name="driver" value="${driver}"/>
18         <property name="url" value="${url}"/>
19         <property name="username" value="${username}"/>
20         <property name="password" value="${password}"/>
21       </dataSource>
22     </environment>
23   </environments>
24 <!-- 注册映射文件 -->
25 <mappers>
26   <mapper resource="com/mapper/UserInfoMapper.xml"/>
27 </mappers>
28 </configuration>

configuration.xml

10.在com.util包下创建获取SqlSession对象的MyBatisUtil.java工具类

 1 package com.util;
 2
 3 import java.io.IOException;
 4 import java.io.Reader;
 5
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSession;
 8 import org.apache.ibatis.session.SqlSessionFactory;
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
10
11 /**
12  * 获取Sqlsession工具类
13  * @author pc
14  *
15  */
16 public class MyBatisUtil {
17     private static SqlSessionFactory sqlSessionFactory=null;
18     static{
19         try {
20             Reader reader=Resources.getResourceAsReader("configuration.xml");
21             sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
22         } catch (IOException e) {
23             e.printStackTrace();
24         }
25     }
26
27     public static SqlSession getSqlSession(boolean isCommit){
28         return sqlSessionFactory.openSession(isCommit);
29     }
30
31 }

MyBatisUtil.java

11.在com.mapper.impl包下创建UserInfoMapperImpl.java映射接口实现类

 1 package com.mapper.impl;
 2
 3 import java.util.List;
 4
 5 import org.apache.ibatis.session.SqlSession;
 6
 7 import com.entity.UserInfo;
 8 import com.mapper.UserInfoMapper;
 9 import com.util.MyBatisUtil;
10
11 public class UserinfoMapperImpl implements UserInfoMapper {
12     private SqlSession sqlsession=null;
13     /**
14      * 删除
15      */
16     public Integer deleteUser(int id) {
17         sqlsession=MyBatisUtil.getSqlSession(true);
18         UserInfoMapper mapper=sqlsession.getMapper(UserInfoMapper.class);
19         Integer num=mapper.deleteUser(id);
20         sqlsession.close();
21         return num;
22     }
23    /**
24     * 登录和各种查
25     */
26     public List<UserInfo> getAllAndWhere(UserInfo user) {
27         sqlsession=MyBatisUtil.getSqlSession(false);
28         UserInfoMapper mapper=sqlsession.getMapper(UserInfoMapper.class);
29         List<UserInfo> list=mapper.getAllAndWhere(user);
30         sqlsession.close();
31         return list;
32     }
33    /**
34     * 添加
35     */
36     public Integer saveUser(UserInfo user) {
37         sqlsession=MyBatisUtil.getSqlSession(true);
38         UserInfoMapper mapper=sqlsession.getMapper(UserInfoMapper.class);
39         Integer num=mapper.saveUser(user);
40         sqlsession.close();
41         return num;
42     }
43     /**
44      * 修改
45      */
46     public Integer updateUser(UserInfo user) {
47         sqlsession=MyBatisUtil.getSqlSession(true);
48         UserInfoMapper mapper=sqlsession.getMapper(UserInfoMapper.class);
49         Integer num=mapper.updateUser(user);
50         sqlsession.close();
51         return num;
52     }
53     /**
54      * 查询总条数
55      */
56     public Integer getTotalCount() {
57         sqlsession=MyBatisUtil.getSqlSession(true);
58         UserInfoMapper mapper=sqlsession.getMapper(UserInfoMapper.class);
59         Integer num=mapper.getTotalCount();
60         sqlsession.close();
61         return num;
62     }
63
64
65
66 }

UserinfoMapperImpl.java

12.在com.page包下创建Page.java分页数据封装类

 1 package com.page;
 2
 3 public class Page {
 4     private Integer pagesize; // 页面大小
 5     private Integer pageno; // 当前页
 6     private Integer totalcount; // 总记录数
 7     private Integer totalpage;
 8     private Integer startrow; // 开始行
 9     private Integer endrow; // 结束行
10
11     public Page() {
12     }
13
14
15     /*public Page(Integer totalcount) {
16         this.setTotalpage(totalcount);
17     }*/
18
19
20     public Page(Integer pagesize, Integer pageno,Integer totalcount) {
21         this.pageno=pageno;
22         this.pagesize=pagesize;
23         this.endrow = (pageno - 1) * pagesize;
24         this.startrow = pageno * pagesize;
25         this.setTotalpage(totalcount);
26     }
27
28     public Integer getPagesize() {
29         return pagesize;
30     }
31
32     public void setPagesize(Integer pagesize) {
33
34             this.pagesize = pagesize;
35
36     }
37
38     public Integer getPageno() {
39         return pageno;
40     }
41
42     public void setPageno(Integer pageno) {
43
44             this.pageno = pageno;
45
46
47     }
48
49     public Integer getTotalcount() {
50         return totalcount;
51     }
52
53     public void setTotalcount(Integer totalcount) {
54         this.totalcount = totalcount;
55     }
56
57     public Integer getTotalpage() {
58         return totalpage;
59     }
60
61     public void setTotalpage(Integer totalcount) {
62         this.setTotalcount(totalcount);
63         this.totalpage = totalcount % pagesize == 0 ? totalcount / pagesize
64                 : totalcount / pagesize + 1;
65
66     }
67
68     public Integer getStartrow() {
69         return startrow;
70     }
71
72     public void setStartrow(Integer startrow) {
73         this.startrow = startrow;
74     }
75
76     public Integer getEndrow() {
77         return endrow;
78     }
79
80     public void setEndrow(Integer endrow) {
81         this.endrow = endrow;
82     }
83
84     @Override
85     public String toString() {
86         return "Page [endrow=" + endrow + ", pageno=" + pageno + ", pagesize="
87                 + pagesize + ", startrow=" + startrow + ", totalcount="
88                 + totalcount + ", totalpage=" + totalpage + "]";
89     }
90
91 }

Page.java

13.在com.service包下创建UserInfoService.java业务接口

package com.service;

import java.util.List;

import com.entity.UserInfo;

/**
 * 服务层接口
 * @author pc
 *
 */
public interface UserInfoService {
    /**
     * 根据id查询
     * @param id
     * @return
     */
    //public UserInfo getById(int id);
    /**
     * 根据对象查询对象
     * @param user
     * @return
     */
    //public UserInfo getByNamePwd(UserInfo user);
    /**
     * 查询所有和根据条件查询
     * @return
     */
    public List<UserInfo> getAllAndWhere(UserInfo user);
    /**
     * 添加
     * @param user
     * @return
     */
    public Integer saveUser(UserInfo user);
    /**
     * 修改
     * @param user
     * @return
     */
    public Integer updateUser(UserInfo user);

    /**
     * 根据id删除
     * @param id
     * @return
     */
    public Integer deleteUser(int id);

    /**
     * 查询总记录数
     * @return
     */
    public Integer getTotalCount();

    }

UserInfoService.java

14.在com.service.impl包下创建UserInfoServiceImpl.java业务接口实现类

 1 package com.service.impl;
 2
 3 import java.util.List;
 4
 5 import com.entity.UserInfo;
 6 import com.mapper.UserInfoMapper;
 7 import com.mapper.impl.UserinfoMapperImpl;
 8 import com.service.UserInfoService;
 9
10 public class UserInfoServiceImpl implements UserInfoService {
11     UserInfoMapper mapper=new UserinfoMapperImpl();
12
13     public Integer deleteUser(int id) {
14         return mapper.deleteUser(id);
15     }
16
17     public Integer updateUser(UserInfo user) {
18         return mapper.updateUser(user);
19     }
20
21     public List<UserInfo> getAllAndWhere(UserInfo user) {
22         return mapper.getAllAndWhere(user);
23     }
24
25     public Integer saveUser(UserInfo user) {
26         return mapper.saveUser(user);
27     }
28
29     public Integer getTotalCount() {
30         // TODO Auto-generated method stub
31         return mapper.getTotalCount();
32     }
33
34 }

UserInfoServiceImpl.java

15.在com.action包下创建Struts2的控制器类UserInfoAction.java

  1 package com.action;
  2
  3 import java.util.List;
  4
  5 import javax.servlet.http.HttpServletRequest;
  6 import javax.servlet.http.HttpSession;
  7
  8 import org.apache.struts2.ServletActionContext;
  9
 10 import com.entity.UserInfo;
 11 import com.opensymphony.xwork2.ActionSupport;
 12 import com.page.Page;
 13 import com.service.UserInfoService;
 14 import com.service.impl.UserInfoServiceImpl;
 15 /**
 16  * //1.获取request,session的方法1:解耦方式 ActionContext ac=
 17  * ActionContext.getContext(); //1.1将数据放给request对象集合
 18  * Map<String, Object> requestMap=(Map<String, Object>)
 19  * ac.get("request"); //就相当于setAttribute(key,value);
 20  * requestMap.put("list", "list");
 21  *
 22  * //1.2.获取session对象集合 Map<String, Object>
 23  * sessionMap=ac.getSession(); sessionMap.put("uname",
 24  * loginlist.get(0).getUname());
 25  */
 26 public class UserInfoAction extends ActionSupport {
 27
 28     UserInfoService service = new UserInfoServiceImpl();
 29     /**
 30      * 该对象接受表单的值(代理对象通过setter和getter)
 31      */
 32     private UserInfo user;
 33     /**
 34      * 封装page对象的
 35      */
 36     private Page page;
 37
 38     /**
 39      * 1.登录
 40      *
 41      * @return
 42      */
 43     public String login() {
 44         if (user!= null) {
 45             System.out.println("参数已经接到");
 46             // 业务处理
 47             List<UserInfo> loginlist = service.getAllAndWhere(user);
 48              UserInfo useinfo=loginlist.get(0);
 49             if (useinfo != null) {
 50                 System.out.println("登录成功");
 51                     // 2.获取request,session的方法2:耦合方式
 52                     // 2.1获取request对象
 53                    HttpServletRequest request = ServletActionContext
 54                             .getRequest();
 55 //                    request.setAttribute("list", "list");
 56                     // 2.2获取session对象
 57                     HttpSession session = request.getSession();
 58                     session.setAttribute("uname", useinfo.getUname());
 59
 60               return SUCCESS;
 61
 62             } else {
 63                 System.out.println("登录失败");
 64                 return ERROR;
 65             }
 66         } else {
 67             System.out.println("参数没有接到");
 68             return ERROR;
 69         }
 70
 71     }
 72
 73     /**
 74     * 2.查询所有
 75     * @return
 76     */
 77     public String findAll(){
 78         HttpServletRequest request=ServletActionContext.getRequest();
 79
 80         //查单条
 81         Integer totalCount=service.getTotalCount();
 82         Integer pageNo=1;
 83         if(page!=null){
 84             pageNo=page.getPageno();
 85         }
 86
 87          page=new Page(2, pageNo, totalCount);
 88          System.out.println("page:"+page);
 89         //如果page对象为空=查询所有,如果page对象不为空=分页查询
 90         UserInfo u=new UserInfo(page);
 91         System.out.println("分页对象"+page);
 92         List<UserInfo> list=service.getAllAndWhere(u);
 93         if(list!=null){
 94             System.out.println("查询所有,查到了...");
 95             request.setAttribute("list", list);
 96             request.setAttribute("page", page);
 97             return SUCCESS;
 98         }else{
 99             System.out.println("查询所有,没有查到...");
100             return ERROR;
101         }
102     }
103     /**
104      *3. 根据id查询
105      * @return
106      */
107     public String findById(){
108         Integer id=user.getId();
109         if(id!=null){
110             System.out.println("id接到了..");
111
112             List<UserInfo> list=service.getAllAndWhere(user);
113             UserInfo userinfo=list.get(0);
114             if(userinfo!=null){
115                 System.out.println("根据id查到了");
116                 HttpServletRequest request=ServletActionContext.getRequest();
117                 request.setAttribute("upuser", userinfo);
118                 return SUCCESS;
119
120             }else{
121                 System.out.println("根据id没有查到");
122                 return ERROR;
123             }
124         }else{
125             System.out.println("id没有接到...");
126           return ERROR;
127         }
128
129     }
130     /**
131      * 4.注册
132      * @return
133      */
134     public String register(){
135         if(user!=null){
136             System.out.println("参数接到了..");
137             Integer num=service.saveUser(user);
138             if(num>0){
139                 System.out.println("注册成功...");
140                 return SUCCESS;
141             }else{
142                 System.out.println("注册失败...");
143                 return ERROR;
144             }
145         }else{
146             System.out.println("参数没有接到..");
147
148             return ERROR;
149         }
150     }
151     /**
152      * 5.修改
153      * @return
154      */
155     public String update(){
156         if(user!=null){
157             System.out.println("参数接到了..");
158             Integer num=service.updateUser(user);
159             if(num>0){
160                 System.out.println("修改成功");
161                 return SUCCESS;
162             }else{
163                 System.out.println("修改失败");
164                 return ERROR;
165             }
166         }else{
167             System.out.println("参数没有接到..");
168             return ERROR;
169         }
170     }
171
172     /**
173      * 6.删除
174      * @return
175      */
176     public String delete(){
177         if(user.getId()!=null){
178            System.out.println("id接到了");
179            int num=service.deleteUser(user.getId());
180            if(num>0){
181                System.out.println("删除成功");
182                return SUCCESS;
183            }else{
184                System.out.println("删除失败");
185                return ERROR;
186            }
187         }else{
188             System.out.println("id没有接到");
189             return ERROR;
190         }
191     }
192     public UserInfo getUser() {
193         return user;
194     }
195
196     public void setUser(UserInfo user) {
197         this.user = user;
198     }
199
200     public Page getPage() {
201         return page;
202     }
203
204     public void setPage(Page page) {
205         this.page = page;
206     }
207
208
209 }

UserInfoAction.java

16.在src下创建struts.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" >
 3 <struts>
 4    <!-- 处理中文乱码 -->
 5    <constant name="struts.i18n.encoding" value="UTF-8"/>
 6
 7    <package name="default" namespace="/" extends="struts-default">
 8
 9     <!--
10             配置全局action节点的result,reuslt是公用的,
11             全局配置不能和默认配置一起使用
12     -->
13     <global-results>
14        <result name="error">error.jsp</result>
15     </global-results>
16
17     <!-- 登录,修改,删除,注册 形成一个动态调用=通配符使用 -->
18     <action name="*" class="com.action.UserInfoAction" method="{1}">
19         <result name="success" type="redirectAction">findAll</result>
20     </action>
21
22      <!-- 查询所有  -->
23      <action name="findAll" class="com.action.UserInfoAction" method="findAll">
24         <result name="success">index.jsp</result>
25      </action>
26
27       <!-- 查单条 -->
28       <action name="findById" class="com.action.UserInfoAction" method="findById">
29         <result name="success">update.jsp</result>
30      </action>
31
32
33
34
35
36      <!-- 登陆
37      <action name="login" class="com.action.UserInfoAction" method="login">
38         <result name="success" type="redirectAction">findAll</result>
39      </action>
40      -->
41
42      <!-- 修改
43      <action name="update" class="com.action.UserInfoAction" method="update">
44         <result name="success" type="redirectAction">findAll</result>
45      </action>
46      -->
47      <!-- 添加
48       <action name="register" class="com.action.UserInfoAction" method="register">
49         <result name="success">login.jsp</result>
50      </action>
51       -->
52
53        <!-- 删除
54       <action name="delete" class="com.action.UserInfoAction" method="delete">
55         <result name="success" type="redirectAction">findAll</result>
56      </action>
57       -->
58
59   </package>
60 </struts>

struts.xml

17.编辑WebRoot下WEB-INF下的web.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <welcome-file-list>
 8     <welcome-file>login.jsp</welcome-file>
 9   </welcome-file-list>
10   <filter>
11     <filter-name>struts2</filter-name>
12     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
13   </filter>
14   <filter-mapping>
15     <filter-name>struts2</filter-name>
16     <url-pattern>*.action</url-pattern>
17   </filter-mapping>
18 </web-app>

web.xml

18.在WebRoot下创建js文件夹加入jquery-1.8.3.js文件

19.在WebRoot下创建login.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
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘index.jsp‘ starting page</title>
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   </head>
22
23   <body>
24     <center>
25       <fieldset style="width:300px">
26         <legend>登录</legend>
27         <form action="login.action" method="post">
28           <table>
29             <tr>
30               <td>用户名:</td>
31               <td><input type="text" name="user.uname"/></td>
32             </tr>
33             <tr>
34               <td>密码:</td>
35               <td><input type="password" name="user.password"/></td>
36             </tr>
37             <tr>
38               <td><input type="submit" value="登录"/></td>
39             </tr>
40           </table>
41         </form>
42       </fieldset>
43     </center>
44   </body>
45 </html>

login.jsp

20.在WebRoot下创建index.jsp首页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12
13     <title>My JSP ‘index.jsp‘ starting page</title>
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     <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
20     <script type="text/javascript">
21       $(function(){
22         $("tr:odd").css("background-color","#ccc");
23       });
24     </script>
25   </head>
26
27   <body>
28     <center>
29      <h1>欢迎${uname}登录成功!</h1>
30       <table>
31         <tr><td colspan="2"><a href="register.jsp">注册</a></td></tr>
32         <tr><td>编号</td><td>姓名</td><td>密码</td><td>操作</td></tr>
33         <c:forEach var="i" items="${list}">
34         <tr><td>${i.id}</td><td>${i.uname}</td><td>${i.password}</td>
35         <td><a href="findById.action?user.id=${i.id}">修改</a>&nbsp;|&nbsp;<a href="delete.action?user.id=${i.id}">删除</a></td></tr>
36         </c:forEach>
37       </table>
38       当前第${page.pageno}/${page.totalpage }页 &nbsp;&nbsp;
39       <a href="findAll.action?page.pageno=1">首页</a> &nbsp;&nbsp;
40       <c:choose>
41         <c:when test="${page.pageno > 1}">
42           <a href="findAll.action?page.pageno=${page.pageno-1}">上一页</a> &nbsp;&nbsp;
43
44         </c:when>
45         <c:otherwise>
46          <a href="javascript:alert(‘已经是第一页!‘);">上一页</a> &nbsp;&nbsp;
47         </c:otherwise>
48       </c:choose>
49       <c:choose>
50         <c:when test="${page.pageno<page.totalpage}">
51         <a href="findAll.action?page.pageno=${page.pageno+1}">下一页</a> &nbsp;&nbsp;
52
53         </c:when>
54         <c:otherwise>
55           <a href="javascript:alert(‘已经是最后一页!‘);">上一页</a> &nbsp;&nbsp;
56
57         </c:otherwise>
58       </c:choose>
59
60       <a href="findAll.action?page.pageno=${page.totalpage}">末页</a>
61     </center>
62   </body>
63 </html>

index.jsp

21.在WebRoot下创建register.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
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘index.jsp‘ starting page</title>
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   </head>
22
23   <body>
24     <center>
25       <fieldset style="width:300px">
26         <legend>注册</legend>
27         <form action="register.action" method="post">
28           <table>
29             <tr>
30               <td>用户名:</td>
31               <td><input type="text" name="user.uname"/></td>
32             </tr>
33             <tr>
34               <td>密码:</td>
35               <td><input type="password" name="user.password"/></td>
36             </tr>
37             <tr>
38               <td><input type="submit" value="注册"/></td>
39             </tr>
40           </table>
41         </form>
42       </fieldset>
43     </center>
44   </body>
45 </html>

register.jsp

22.在WebRoot下创建update.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
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘index.jsp‘ starting page</title>
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   </head>
22
23   <body>
24     <center>
25       <fieldset style="width:300px">
26         <legend>修改用户信息</legend>
27         <form action="update.action?user.id=${upuser.id}" method="post">
28           <table>
29             <tr>
30               <td>用户名:</td>
31               <td><input type="text" name="user.uname" value="${upuser.uname}"/></td>
32             </tr>
33             <tr>
34               <td>密码:</td>
35               <td><input type="password" name="user.password" value="${upuser.password}"/></td>
36             </tr>
37             <tr>
38               <td><input type="submit" value="注册"/></td>
39             </tr>
40           </table>
41         </form>
42       </fieldset>
43     </center>
44   </body>
45 </html>

update.jsp

23.在error.jsp下创建error.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
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘index.jsp‘ starting page</title>
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   </head>
22
23   <body>
24        业务处理失败!!
25   </body>
26 </html>

error.jsp

24.运行结果如下

时间: 2024-10-10 16:18:27

3、mybatis动态sql+struts2(通配符+全局配置+分页)的相关文章

MyBatis动态SQL————MyBatis动态SQL标签的用法

1.MyBatis动态SQL MyBatis 的强大特性之一便是它的动态 SQL,即拼接SQL字符串.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号.利用动态 SQL 这一特性可以彻底摆脱这种痛苦. 通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意的 SQL 映射语句中. 动态 SQL 元素和

用Groovy模板写MyBatis动态SQL

MyBatis动态SQL简介 MyBatis有个强大的功能,动态SQL.有了这个功能,定义在Mapper里的SQL语句,就不必是静止不变的了,而是可以根据传入的参数,动态调整.下面是MyBatis官方文档里的一个if语句的例子: <select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <if test=

mybatis动态sql中的两个内置参数(_parameter和_databaseId)

<!-- mybatis动态sql的两个内置参数           不只是方法传递过来的参数可以被用来判断,取值       mybatis默认还有两个内置参数           _parameter:代表整个参数                                      单个参数:_parameter就是这个参数                                      多个参数:参数会被封装为一个map:_parameter就是代表这个map       

MyBatis动态sql和分页

MyBatis动态sql 在接口中定义方法 然后alt加回车在xml中如图: 1.if 语句 (简单的条件判断) 2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似 3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀) 4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误). 5. set (主要用于更新时)

mybatis动态sql以及分页

1.mybatis动态sql 2.模糊查询 3.查询返回结果集的处理 4.分页查询 5.特殊字符处理 1.mybatis动态sql If.trim.foreach If 标签判断某一字段是否为空 <select id="list4" resultType="java.util.Map" parameterType="java.util.Map"> select * from t_mvc_book <where> <i

Mybaits(7) Mybatis动态 SQL

1.概述 我们在使用JDBC或者类似Hibernate的其他框架时,需要根据需求去拼装sql,这是很烦的一件事情.有时一个查询有许多查询条件,有时需要控制有点条件为空的情况,我们使用其他框架进行大量的Java代码进行判断,可读性差,而Mybatis框架提供了对sql语句动态组装能力,使用xml的几个简单元素便可完成sql相应的功能.大量的判断可以MyBatis的映射配置文件xml中进行配置,大大减少了代码量,同时也可以在注解中配置sql,但由于注解功能受限,对复杂sql可读性差,所以很少使用.

MyBatis动态SQL小结

p.MsoNormal,li.MsoNormal,div.MsoNormal { margin: 0cm; margin-bottom: .0001pt; text-align: justify; font-size: 10.5pt; font-family: 等线 } .MsoChpDefault { font-family: 等线 } div.WordSection1 { } ol { margin-bottom: 0cm } ul { margin-bottom: 0cm } Mybati

mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 a

struts2 通配符简化配置

在struts映射中重复出现的模式 动作方法 描述 下一个动作方法 add 为save准备网页 save save 提交INSERT list edit 为update准备网页 update update 提交UPDATE list destroy 为remove准备网页 remove remove 提交DELETE list show 为详细展示准备网页 list list 为列表展示准备网页 list print 为打印准备网页 list 一个动作类的DEMO: package com.ba