南京音乐推荐联合社

C.Servlet中文乱码处理、重定向及分页

JavaStudyNotes 2020-05-22 15:11:23



Servlet中文乱码处理

1.post请求提交中文  get请求请不要提交中文(也可以提交,不提倡)

     request.setCharacterEncoding(项目的编码); post请求中的

2.响应

  response设置响应头

  response.setContentType("text/html;charset=项目的编码")




Servlet好像做了页面的工作,将来Servlet主要做控制,业务调用。不做页面,页面交给jsp,现在不讨论jsp,拿Servlet即做业务逻辑处理,有做页面。Servlet最终作为控制器使用,响应去另外的页面如何处理。

重定向、分页

重定向  response.sendRedirect(url);   相当于发送了新的请求跳转的方式


欢迎页 :web.xml文件进行配置

1<welcome-file-list>
2      <welcome-file>login.html</welcome-file>
3</welcome-file-list>

Servleg实例的创建

a. web容器创建,只创建一次(单例模式)

b. 我们之前看到的servlet是在向其发送请求,Servlet实例才会被创建。Servlet实例也可以在项目启动的时候直接创建,将来用于加载项目中的一些准备数据

c. 在web.xml文件中的Servlet配置中配置如下

1<load-on-startup>数字</load-on-startup>
1    <servlet>
2        <description>
3        </description>
4        <display-name>ServletInstance</display-name>
5        <servlet-name>ServletInstance</servlet-name>
6        <servlet-class>servlet.ServletInstance</servlet-class>
7        <load-on-startup>1</load-on-startup>
8    </servlet>

具体代码实现


数据库

 1权限表
2CREATE TABLE `wyzc_systemprivilege` (
3  `id_` varchar(255) NOT NULL,
4  `name_` varchar(255) DEFAULT NULL,
5  `action_` varchar(64) DEFAULT NULL,
6  `resource_` varchar(64) DEFAULT NULL,
7  PRIMARY KEY (`id_`)
8)
9都有哪些权限,都定义好
10插入数据
11INSERT INTO `wyzc_systemprivilege` VALUES ('297e0592448b4e7201448b4ee117001e','发表主题','Create','Topic'),
12('297e0592448b4e7201448b4ee117001f','查看主题','Retrieval','Topic'),
13('297e0592448b4e7201448b4ee1170020','修改主题','Update','Topic'),
14('297e0592448b4e7201448b4ee1170021','删除主题','Delete','Topic'),
15('297e0592448b4e7201448b4ee1170022','移动主题','Move','Topic'),
16('297e0592448b4e7201448b4ee1170023','发表回复','Create','Reply'),
17('297e0592448b4e7201448b4ee1170024','查看回复','Retrieval','Reply'),
18('297e0592448b4e7201448b4ee1170025','修改回复','Update','Reply'),
19('297e0592448b4e7201448b4ee1170026','删除回复','Delete','Reply'),
20('297e0592448b4e7201448b4ee1170027','发表附件','Create','Attachment'),
21('297e0592448b4e7201448b4ee1170028','查看附件','Retrieval','Attachment'),
22('297e0592448b4e7201448b4ee1170029','更新附件','Update','Attachment'),
23('297e0592448b4e7201448b4ee117002a','删除附件','Delete','Attachment'),
24('297e0592448b4e7201448b4ee117002b','下载附件','Download','Attachment'),
25('297e0592448b4e7201448b4ee117002c','发表投票','Create','Poll'),
26('297e0592448b4e7201448b4ee117002d','查看投票','Retrieval','Poll'),
27('297e0592448b4e7201448b4ee117002e','修改投票','Update','Poll'),
28('297e0592448b4e7201448b4ee117002f','删除投票','Delete','Poll'),
29('297e0592448b4e7201448b4ee1170030','参与投票','Vote','Poll'),
30('297e0592448b4e7201448b4ee1170031','管理系统','Manage','System');

Dao接口用于编写要使用的方法(有些方法暂且用不到)

 1package dao;
2import java.util.List;
3public interface Dao<T> {
4    T findById(String id,String sql,RowMapper<T> rm);
5    List<T> findByPage(int pageSize,int page,String sql,RowMapper<T> rm,Object...obj);
6    List<T> findAll(String sql,RowMapper<T> rm,Object ...objs);
7    //select roleid_ from wycz_user_role where userid_=?
8    int saveOrUpdate(String sql,Object...obj);
9    int deleteById(String id,String sql);
10}

DaoSupport对Dao接口的方法进行实现(封装数据操作)

1package dao;
 2import java.sql.Connection;
 3import java.sql.PreparedStatement;
 4import java.sql.ResultSet;
 5import java.util.ArrayList;
 6import java.util.List;
 7public class DaoSupport<T> implements Dao<T>{
 8    public T findById(String id, String sql, RowMapper<T> rm) {
 9        Connection con = null;
10        PreparedStatement pstmt = null;
11        ResultSet rs = null;
12        T t = null;
13        try {
14            con = JdbcUtil.getConn();
15            pstmt = con.prepareStatement(sql);
16            pstmt.setString(1, id);
17            rs = pstmt.executeQuery();
18            if(rs.next()){
19                t = rm.getRow(rs);
20            }
21        } catch (Exception e) {
22            e.printStackTrace();
23        }finally{
24            JdbcUtil.close(pstmt, rs);
25        }
26        return t;
27    }
28   //select * from aa where ...?...?  limit ?,?;
29    public List<T> findByPage(int pageSize, int page,String sql, RowMapper<T> rm,
30            Object... obj)
{
31        List<T> ts = new ArrayList<T>();
32        Connection con = null;
33        PreparedStatement pstmt = null;
34        ResultSet rs = null;
35        int begin = (page-1)*pageSize+1;
36    //  int end = pageSize*page;
37        try {
38            con = JdbcUtil.getConn();
39            pstmt = con.prepareStatement(sql);
40            int i = 0;
41            for(i = 0; i < obj.length;i++){
42                pstmt.setObject(i+1,obj[i]);
43            }
44            pstmt.setInt(++i,begin);
45            pstmt.setInt(++i, pageSize);
46            rs = pstmt.executeQuery();
47            while(rs.next()){
48                T t = rm.getRow(rs);
49                ts.add(t);
50            }
51        } catch (Exception e) {
52            e.printStackTrace();
53        }finally{
54            JdbcUtil.close(pstmt, rs);
55        }
56        return ts;
57    }
58    public int saveOrUpdate(String sql, Object... obj) {
59        Connection con = null;
60        PreparedStatement pstmt = null;
61        int n = 0;
62        try {
63            con = JdbcUtil.getConn();
64            pstmt = con.prepareStatement(sql);
65            for(int i = 0 ; i< obj.length;i++){
66                pstmt.setObject(i+1, obj[i]);
67            }
68            n = pstmt.executeUpdate();
69        } catch (Exception e) {
70            e.printStackTrace();
71        }finally{
72            JdbcUtil.close(pstmt, null);
73        }
74        return n;
75    }
76    public int deleteById(String id, String sql) {
77        Connection con = null;
78        PreparedStatement pstmt = null;
79        int n = 0;
80        try {
81            con = JdbcUtil.getConn();
82            pstmt = con.prepareStatement(sql);
83            pstmt.setString(1, id);
84            n = pstmt.executeUpdate();
85        } catch (Exception e) {
86            e.printStackTrace();
87        }finally{
88            JdbcUtil.close(pstmt, null);
89        }
90        return n;
91    }
92    public List<T> findAll(String sql, RowMapper<T> rm, Object... objs) {
93        List<T> ts = new ArrayList<T>();
94        Connection con = null;
95        PreparedStatement pstmt = null;
96        ResultSet rs = null;
97        try {
98            con = JdbcUtil.getConn();
99            pstmt = con.prepareStatement(sql);
100            int i = 0;
101            for(i = 0; i < objs.length;i++){
102                pstmt.setObject(i+1,objs[i]);
103            }
104            rs = pstmt.executeQuery();
105            while(rs.next()){
106                T t = rm.getRow(rs);
107                ts.add(t);
108            }
109        } catch (Exception e) {
110            e.printStackTrace();
111        }finally{
112            JdbcUtil.close(pstmt, rs);
113        }
114        return ts;
115    }
116}

JdbcUtil对数据库连接进行封装

 1package dao;
2import java.io.IOException;
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.ResultSet;
6import java.sql.SQLException;
7import java.sql.Statement;
8import java.util.Properties;
9public class JdbcUtil {
10    private static Properties prop = new Properties();
11    static {
12        try {
13            prop.load(JdbcUtil.class
14                    .getResourceAsStream("/database.properties"));
15        } catch (IOException e) {
16            // TODO Auto-generated catch block
17            e.printStackTrace();
18        }
19    }
20    public static Connection getConn(){
21        try {
22            Class.forName(prop.getProperty("driver"));
23            Connection con = DriverManager.getConnection(prop.getProperty("url"),
24                    prop.getProperty("name"),
25                    prop.getProperty("pass"));
26            return con;
27        } catch (Exception e) {
28           e.printStackTrace();
29           return null;
30        }
31    }
32    public static void close(Statement stmt ,ResultSet rs){
33        if(stmt!=null){
34            try {
35                stmt.close();
36            } catch (SQLException e) {
37                // TODO Auto-generated catch block
38                e.printStackTrace();
39            }
40         }
41          if(rs!=null){
42                try {
43                    rs.close();
44                } catch (SQLException e) {
45                    // TODO Auto-generated catch block
46                    e.printStackTrace();
47                }
48        }
49    }
50}

data.properties文件用于存放连接数据库所需要的变量

1url=jdbc:mysql://localhost:3306/wyzcbbs
2name=root
3pass=123456
4driver=com.mysql.jdbc.Driver


RowMapper接口



1package dao;
2import java.sql.ResultSet;
3import java.sql.SQLException;
4public interface RowMapper<T> {
5    public T getRow(ResultSet rs)throws SQLException;
6}

Systemprivilege类权限实体类

 1package dao;
2import java.io.Serializable;
3public class Systemprivilege implements Serializable{
4    private String id;
5    private String name;
6    private String action;
7    private String resource;
8    public String getId() {
9        return id;
10    }
11    public void setId(String id) {
12        this.id = id;
13    }
14    public String getName() {
15        return name;
16    }
17    public void setName(String name) {
18        this.name = name;
19    }
20    public String getAction() {
21        return action;
22    }
23    public void setAction(String action) {
24        this.action = action;
25    }
26    public String getResource() {
27        return resource;
28    }
29    public void setResource(String resource) {
30        this.resource = resource;
31    }
32}

SystemprivilegeService类 业务的具体实现

 1package service;
2import java.sql.ResultSet;
3import java.sql.SQLException;
4import java.util.List;
5import dao.DaoSupport;
6import dao.RowMapper;
7import dao.Systemprivilege;
8public class SystemprivilegeService {
9    DaoSupport<Systemprivilege> sd = new DaoSupport<Systemprivilege>();
10    public List<Systemprivilege> findByPage(int pageSize,int page){
11        List<Systemprivilege> ss = sd.findByPage(pageSize, page, "select * from wyzc_systemprivilege limit ?,?", new RowMapper<Systemprivilege>() {
12            public Systemprivilege getRow(ResultSet rs)
13                    throws SQLException
{
14                // TODO Auto-generated method stub
15                Systemprivilege s = new Systemprivilege();
16                s.setId(rs.getString("id_"));
17                s.setName(rs.getString("name_"));
18                s.setResource(rs.getString("resource_"));
19                s.setAction(rs.getString("action_"));
20                return s;
21            }
22        });
23        return ss;
24    }
25}


LoginServlet类登录所用的Servlet类

 1package servlet;
2import java.io.IOException;
3import javax.servlet.ServletException;
4import javax.servlet.http.HttpServlet;
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpServletResponse;
7/**
8 * Servlet implementation class LoginServlet
9 */

10public class LoginServlet extends HttpServlet {
11    private static final long serialVersionUID = 1L;
12    /**
13     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
14     */

15    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
16        doPost(request, response);
17    }
18    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19          request.setCharacterEncoding("utf-8");
20          String username = request.getParameter("username");
21          String password = request.getParameter("password");
22          if("张三".equals(username)&&"123".equals(password))
23              response.sendRedirect("ListServlet?page=1");
24          else
25              response.sendRedirect("login.html");
26    }
27}


ListServlet类分页的Servlet类

 1package servlet;
2import java.io.IOException;
3import java.io.PrintWriter;
4import java.sql.ResultSet;
5import java.sql.SQLException;
6import java.util.List;
7import javax.servlet.ServletException;
8import javax.servlet.http.HttpServlet;
9import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11import service.SystemprivilegeService;
12import dao.DaoSupport;
13import dao.RowMapper;
14import dao.Systemprivilege;
15/**
16 * Servlet implementation class ListServlet
17 */

18public class ListServlet extends HttpServlet {
19    private static final long serialVersionUID = 1L;
20    /**
21     * @see HttpServlet#HttpServlet()
22     */

23    public ListServlet() {
24        super();
25        // TODO Auto-generated constructor stub
26    }
27    /**
28     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
29     *      response)
30     */

31    protected void doGet(HttpServletRequest request,
32            HttpServletResponse response) throws ServletException, IOException {
33        doPost(request, response);
34    }
35    /**
36     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
37     *      response)
38     */

39    protected void doPost(HttpServletRequest request,
40            HttpServletResponse response) throws ServletException, IOException {
41        response.setContentType("text/html;charset=utf-8");
42        PrintWriter out = response.getWriter();
43        int page = Integer.parseInt(request.getParameter("page"));
44        /*DaoSupport<Systemprivilege> ds = new DaoSupport<Systemprivilege>();
45        List<Systemprivilege> ss = ds.findAll(
46                "select * from wyzc_systemprivilege",
47                new RowMapper<Systemprivilege>() {
48                    @Override
49                    public Systemprivilege getRow(ResultSet rs)
50                            throws SQLException {
51                        // TODO Auto-generated method stub
52                        Systemprivilege s = new Systemprivilege();
53                        s.setId(rs.getString("id_"));
54                        s.setName(rs.getString("name_"));
55                        s.setResource(rs.getString("resource_"));
56                        s.setAction(rs.getString("action_"));
57                        return s;
58                    }
59                });
60                */

61        SystemprivilegeService ps = new SystemprivilegeService();
62        List<Systemprivilege> ss = ps.findByPage(5,page);
63        out.println("<table border=1 align=center width=400>");
64        out.println("<tr><th>name</th><th>resource</th><th>action</th></tr>");
65        for (Systemprivilege systemprivilege : ss) {
66            out.println("<tr>");
67            out.println("<td>"+systemprivilege.getName()+"</td>");
68            out.println("<td>"+systemprivilege.getResource()+"</td>");
69            out.println("<td>"+systemprivilege.getAction()+"</td>");
70            out.println("</tr>");
71        }
72        out.println("<tr>");
73        out.println("<td colspan=3>");
74        out.println("<a href='ListServlet?page="+(page-1)+"'>上一页</a>&nbsp;&nbsp;");
75        out.println("<a href='ListServlet?page="+(page+1)+"'>下一页</a/>&nbsp;&nbsp;");
76        out.println("</td></tr>");
77        out.println("</table>");
78        out.println("<br/>");
79    }
80}


login.html


 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml">
3    <head>
4        <title>注册页面</title>
5        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
6   </head>
7   <body>
8      <form action="LoginServlet" method="post">
9         姓名:<input type="text" name="username"/><br/>
10         密码:<input type="password" name="password"/><br/>
11         <input type="submit" value="登陆"/><br/>
12      </form>
13      <br/>
14      <a href="regist.html">如未注册请注册</a>
15   </body>
16</html>


regist.html

 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml">
3    <head>
4        <title>注册页面</title>
5        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
6   </head>
7   <body>
8      <form action="/Servlet/RegisterServlet" method="post">
9         姓名:<input type="text" name="username"/><br/>
10         密码:<input type="password" name="password"/><br/>
11         水果:<input type="checkbox" name="fruit" value="苹果"/>Apple
12                <input type="checkbox" name="fruit" value="香蕉"/>Banana
13                <input type="checkbox" name="fruit" value="葡萄"/>Grape
14                <br/>
15         <input type="submit" value="注册"/><br/>
16      </form>
17      <br/>
18      <a href="HrefServlet?name=hello&page=2">请求数据测试</a>
19   </body>
20</html>


web.xml文件在这里自己配置不做展示。

运行项目  进入欢迎页(姓名:张三  密码:123)点击登陆

登陆进入分页(点击上一页,下一页)实现简单分页功能

下方查看历史文章

B.Servlet配置信息及请求数据

基本概念及容器的打印

泛型和类型安全的容器

使用内部类的原因


▲向上滑动


JavaStudyNotes公众号

only-you-sh


          本公众号纯属于个人公益公众号,在这里有免费的各种IT资源

更多技术分享请加我微信,我拉你进群进行交流

长按右方二维码

关注我们







Copyright © 南京音乐推荐联合社@2017