2023年2.22软工日报

今天上课困死,上的计算机网络课程还有那个毛概。很无聊又枯燥,困死阿。

下午没有课,然后去玩玩。

晚上,我继续搞那个VUE+axois 还有filter。最后完成了增删改查。

以后就是拿这个直接写就行。

首先是UserMApper:

 1 package com.mapper;
 2 
 3 import com.pojo.User;
 4 import org.apache.ibatis.annotations.Param;
 5 import org.apache.ibatis.annotations.Select;
 6 
 7 public interface UserMapper {
 8     @Select("select * from user")
 9     User select(@Param("username")String username, @Param("password")String password);
10 }

xiewenMapper:

 1 package com.mapper;
 2 
 3 import com.pojo.xiewen;
 4 import org.apache.ibatis.annotations.*;
 5 
 6 import java.util.List;
 7 
 8 public interface xiewenMapper {
 9     @Select("select * from xiewen")
10     List<xiewen> selectall();
11 @Insert("insert into xiewen values(#{xinwen},#{lanmu})")
12   void add(xiewen xiewen1);
13 @Delete("delete  from xiewen where xinwen = #{xinwen}")
14 void deleteById(@Param("xinwen")String xinwen);
15 @Update("update xiewen set xinwen=#{xinwen}where lanmu=#{lanmu}")
16 void updateById(xiewen xiewen);
17 List<xiewen> tiaocha(xiewen xiewen1);
18 
19 }

MD5加密文件

 1 package com.MD5;
 2 import java.math.BigInteger;
 3 import java.security.MessageDigest;
 4 import java.security.NoSuchAlgorithmException;
 5 /**
 6  *
 7  * @author wjxing
 8  *
 9  */
10 public class MD5{
11     /**
12      * 使用md5的算法进行加密
13      */
14     public static String md5(String plainText) {
15         byte[] secretBytes = null;
16         try {
17             secretBytes = MessageDigest.getInstance("md5").digest(
18                     plainText.getBytes());
19         } catch (NoSuchAlgorithmException e) {
20             throw new RuntimeException("没有md5这个算法!");
21         }
22         String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
23         // 如果生成数字未满32位,需要前面补0
24         for (int i = 0; i < 32 - md5code.length(); i++) {
25             md5code = "0" + md5code;
26         }
27         return md5code;
28     }
29 
30     /**
31      * 可逆的的加密解密方法;两次是解密,一次是加密
32      * @param inStr
33      * @return
34      */
35     public static String convertMD5(String inStr){
36 
37         char[] a = inStr.toCharArray();
38         for (int i = 0; i < a.length; i++){
39             a[i] = (char) (a[i] ^ 't');
40         }
41         String s = new String(a);
42         return s;
43 
44     }
45 
46   
47 }

User.java

 1 package com.pojo;
 2 
 3 public class User {
 4     private String username;
 5     private String password;
 6     public String getUsername() {
 7         return username;
 8     }
 9     public void setUsername(String username) {
10         this.username = username;
11     }
12     public String getPassword() {
13         return password;
14     }
15     public void setPassword(String password) {
16         this.password = password;
17     }
18     @Override
19     public String toString() {
20         return "User{" +
21                 "username='" + username + '\'' +
22                 ", password='" + password + '\'' +
23                 '}';
24     }
25 
26   /*  public static void main(String[] args) {
27         System.out.println("k");
28     }*/
29 }

xiewen.java

 1 package com.pojo;
 2 
 3 public class xiewen {
 4     private  String xinwen;
 5     private  String lanmu;
 6 
 7     public xiewen(String xinwen, String lanmu) {
 8         this.xinwen = xinwen;
 9         this.lanmu = lanmu;
10     }
11 
12     public String getXinwen() {
13         return xinwen;
14     }
15 
16     public void setXinwen(String xinwen) {
17         this.xinwen = xinwen;
18     }
19 
20     public String getLanmu() {
21         return lanmu;
22     }
23 
24     public void setLanmu(String lanmu) {
25         this.lanmu = lanmu;
26     }
27     @Override
28     public String toString() {
29         return "xiewen{" +
30                 "xinwen='" + xinwen + '\'' +
31                 ", lanmu='" + lanmu + '\'' +
32                 '}';
33     }
34 }

UserService:

 1 package com.service;
 2 
 3 import com.pojo.User;
 4 
 5 public interface UserService {
 6     /**
 7      * 登录方法
 8      * @param username
 9      * @param password
10      * @return
11      */
12 
13     User login(String username, String password);
14 
15 }

xiexinService:

package com.service;

import com.pojo.xiewen;

import java.util.List;

public interface xiewenService {
    List<xiewen> selectall();
    void add(xiewen xiewen1);
    void deleteById(String xinwen);
    void updateById(xiewen xiewen);
    List<xiewen>tiaocha(xiewen xiewen1);

}
UserServiceImpl.java:
 1 package com.service.impl;
 2 
 3 import com.mapper.UserMapper;
 4 import com.pojo.User;
 5 import com.service.UserService;
 6 import com.util.SqlSessionFactoryUtils;
 7 import com.service.UserService;
 8 import org.apache.ibatis.session.SqlSession;
 9 import org.apache.ibatis.session.SqlSessionFactory;
10 
11 public class UserServiceImpl implements UserService {
12     SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
13 
14     /**
15      * 登录方法
16      * @param username
17      * @param password
18      * @return
19      */
20 
21     public User login(String username, String password){
22         //2. 获取SqlSession
23         SqlSession sqlSession = factory.openSession();
24         //3. 获取UserMapper
25         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
26         //4. 调用方法
27         User user = mapper.select(username, password);
28 
29         //释放资源
30         sqlSession.close();
31 
32         return  user;
33     }
34 
35 
36 
37 }
iewenImpl.java
  1 package com.service.impl;
  2 
  3 import com.mapper.xiewenMapper;
  4 import com.pojo.xiewen;
  5 import com.service.xiewenService;
  6 import com.util.SqlSessionFactoryUtils;
  7 import org.apache.ibatis.session.SqlSession;
  8 import org.apache.ibatis.session.SqlSessionFactory;
  9 
 10 import java.util.List;
 11 
 12 public class xiewenImpl implements xiewenService {
 13     SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
 14     @Override
 15     public List<xiewen> selectall() {
 16         //2. 获取SqlSession对象
 17         SqlSession sqlSession = factory.openSession();
 18         //3. 获取BrandMapper
 19         xiewenMapper mapper = sqlSession.getMapper(xiewenMapper.class);
 20 
 21         //4. 调用方法
 22         List<xiewen> xiewens = mapper.selectall();
 23 
 24         //5. 释放资源
 25         sqlSession.close();
 26 
 27         return xiewens;
 28     }
 29 
 30     @Override
 31     public void add(xiewen xiewen1) {
 32         //2. 获取SqlSession对象
 33         SqlSession sqlSession = factory.openSession();
 34         //3. 获取BrandMapper
 35         xiewenMapper mapper = sqlSession.getMapper(xiewenMapper.class);
 36 
 37         //4. 调用方法
 38          mapper.add(xiewen1);
 39         sqlSession.commit();//提交事务
 40         //5. 释放资源
 41         sqlSession.close();
 42     }
 43 
 44     @Override
 45     public void deleteById(String xinwen) {
 46         SqlSession sqlSession = factory.openSession();
 47         //3. 获取BrandMapper
 48         xiewenMapper mapper = sqlSession.getMapper(xiewenMapper.class);
 49 
 50         //4. 调用方法
 51         mapper.deleteById(xinwen);
 52         sqlSession.commit();//提交事务
 53 
 54         //5. 释放资源
 55         sqlSession.close();
 56     }
 57 
 58     @Override
 59     public void updateById(xiewen xiewen) {
 60         //2. 获取SqlSession对象
 61         SqlSession sqlSession = factory.openSession();
 62         //3. 获取BrandMapper
 63         xiewenMapper mapper = sqlSession.getMapper(xiewenMapper.class);
 64 
 65         //4. 调用方法
 66         mapper.updateById(xiewen);
 67 
 68         sqlSession.commit();//提交事务
 69 
 70         //5. 释放资源
 71         sqlSession.close();
 72     }
 73 
 74     @Override
 75     public List<xiewen> tiaocha(xiewen xiewen1) {
 76         SqlSession sqlSession = factory.openSession();
 77         //3. 获取BrandMapper
 78         xiewenMapper mapper = sqlSession.getMapper(xiewenMapper.class);
 79         String xinwen = xiewen1.getXinwen();
 80         if (xinwen != null && xinwen.length() > 0) {
 81             xiewen1.setXinwen("%" + xinwen + "%");
 82         }
 83 
 84 
 85         String lanmu = xiewen1.getLanmu();
 86         if (lanmu != null && lanmu.length() > 0) {
 87             xiewen1.setLanmu("%" + lanmu + "%");
 88         }
 89 
 90         //4. 调用方法
 91         List<xiewen> tiaocha = mapper.tiaocha(xiewen1);
 92 
 93 
 94         /*  sqlSession.commit();//提交事务*/
 95 
 96         //5. 释放资源
 97         sqlSession.close();
 98         return tiaocha;
 99     }
100 }

 

CheckCodeUtil.java

  1 package com.util;
  2 
  3 import javax.imageio.ImageIO;
  4 import java.awt.*;
  5 import java.awt.geom.AffineTransform;
  6 import java.awt.image.BufferedImage;
  7 import java.io.File;
  8 import java.io.FileOutputStream;
  9 import java.io.IOException;
 10 import java.io.OutputStream;
 11 import java.util.Arrays;
 12 import java.util.Random;
 13 
 14 /**
 15  * 生成验证码工具类
 16  */
 17 public class CheckCodeUtil {
 18 
 19     public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 20     private static Random random = new Random();
 21 
 22 
 23     public static void main(String[] args) throws IOException {
 24         OutputStream fos = new FileOutputStream("d://a.jpg");
 25         String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
 26 
 27         System.out.println(checkCode);
 28     }
 29 
 30 
 31     /**
 32      * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
 33      *
 34      * @param width 图片宽度
 35      * @param height 图片高度
 36      * @param os  输出流
 37      * @param verifySize 数据长度
 38      * @return 验证码数据
 39      * @throws IOException
 40      */
 41     public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
 42         String verifyCode = generateVerifyCode(verifySize);
 43         outputImage(width, height, os, verifyCode);
 44         return verifyCode;
 45     }
 46 
 47     /**
 48      * 使用系统默认字符源生成验证码
 49      *
 50      * @param verifySize 验证码长度
 51      * @return
 52      */
 53     public static String generateVerifyCode(int verifySize) {
 54         return generateVerifyCode(verifySize, VERIFY_CODES);
 55     }
 56 
 57     /**
 58      * 使用指定源生成验证码
 59      *
 60      * @param verifySize 验证码长度
 61      * @param sources    验证码字符源
 62      * @return
 63      */
 64     public static String generateVerifyCode(int verifySize, String sources) {
 65         // 未设定展示源的字码,赋默认值大写字母+数字
 66         if (sources == null || sources.length() == 0) {
 67             sources = VERIFY_CODES;
 68         }
 69         int codesLen = sources.length();
 70         Random rand = new Random(System.currentTimeMillis());
 71         StringBuilder verifyCode = new StringBuilder(verifySize);
 72         for (int i = 0; i < verifySize; i++) {
 73             verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
 74         }
 75         return verifyCode.toString();
 76     }
 77 
 78     /**
 79      * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
 80      *
 81      * @param w
 82      * @param h
 83      * @param outputFile
 84      * @param verifySize
 85      * @return
 86      * @throws IOException
 87      */
 88     public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
 89         String verifyCode = generateVerifyCode(verifySize);
 90         outputImage(w, h, outputFile, verifyCode);
 91         return verifyCode;
 92     }
 93 
 94 
 95 
 96     /**
 97      * 生成指定验证码图像文件
 98      *
 99      * @param w
100      * @param h
101      * @param outputFile
102      * @param code
103      * @throws IOException
104      */
105     public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
106         if (outputFile == null) {
107             return;
108         }
109         File dir = outputFile.getParentFile();
110         //文件不存在
111         if (!dir.exists()) {
112             //创建
113             dir.mkdirs();
114         }
115         try {
116             outputFile.createNewFile();
117             FileOutputStream fos = new FileOutputStream(outputFile);
118             outputImage(w, h, fos, code);
119             fos.close();
120         } catch (IOException e) {
121             throw e;
122         }
123     }
124 
125     /**
126      * 输出指定验证码图片流
127      *
128      * @param w
129      * @param h
130      * @param os
131      * @param code
132      * @throws IOException
133      */
134     public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
135         int verifySize = code.length();
136         BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
137         Random rand = new Random();
138         Graphics2D g2 = image.createGraphics();
139         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
140 
141         // 创建颜色集合,使用java.awt包下的类
142         Color[] colors = new Color[5];
143         Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
144                 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
145                 Color.PINK, Color.YELLOW};
146         float[] fractions = new float[colors.length];
147         for (int i = 0; i < colors.length; i++) {
148             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
149             fractions[i] = rand.nextFloat();
150         }
151         Arrays.sort(fractions);
152         // 设置边框色
153         g2.setColor(Color.GRAY);
154         g2.fillRect(0, 0, w, h);
155 
156         Color c = getRandColor(200, 250);
157         // 设置背景色
158         g2.setColor(c);
159         g2.fillRect(0, 2, w, h - 4);
160 
161         // 绘制干扰线
162         Random random = new Random();
163         // 设置线条的颜色
164         g2.setColor(getRandColor(160, 200));
165         for (int i = 0; i < 20; i++) {
166             int x = random.nextInt(w - 1);
167             int y = random.nextInt(h - 1);
168             int xl = random.nextInt(6) + 1;
169             int yl = random.nextInt(12) + 1;
170             g2.drawLine(x, y, x + xl + 40, y + yl + 20);
171         }
172 
173         // 添加噪点
174         // 噪声率
175         float yawpRate = 0.05f;
176         int area = (int) (yawpRate * w * h);
177         for (int i = 0; i < area; i++) {
178             int x = random.nextInt(w);
179             int y = random.nextInt(h);
180             // 获取随机颜色
181             int rgb = getRandomIntColor();
182             image.setRGB(x, y, rgb);
183         }
184         // 添加图片扭曲
185         shear(g2, w, h, c);
186 
187         g2.setColor(getRandColor(100, 160));
188         int fontSize = h - 4;
189         Font font = new Font("Algerian", Font.ITALIC, fontSize);
190         g2.setFont(font);
191         char[] chars = code.toCharArray();
192         for (int i = 0; i < verifySize; i++) {
193             AffineTransform affine = new AffineTransform();
194             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
195             g2.setTransform(affine);
196             g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
197         }
198 
199         g2.dispose();
200         ImageIO.write(image, "jpg", os);
201     }
202 
203     /**
204      * 随机颜色
205      *
206      * @param fc
207      * @param bc
208      * @return
209      */
210     private static Color getRandColor(int fc, int bc) {
211         if (fc > 255) {
212             fc = 255;
213         }
214         if (bc > 255) {
215             bc = 255;
216         }
217         int r = fc + random.nextInt(bc - fc);
218         int g = fc + random.nextInt(bc - fc);
219         int b = fc + random.nextInt(bc - fc);
220         return new Color(r, g, b);
221     }
222 
223     private static int getRandomIntColor() {
224         int[] rgb = getRandomRgb();
225         int color = 0;
226         for (int c : rgb) {
227             color = color << 8;
228             color = color | c;
229         }
230         return color;
231     }
232 
233     private static int[] getRandomRgb() {
234         int[] rgb = new int[3];
235         for (int i = 0; i < 3; i++) {
236             rgb[i] = random.nextInt(255);
237         }
238         return rgb;
239     }
240 
241     private static void shear(Graphics g, int w1, int h1, Color color) {
242         shearX(g, w1, h1, color);
243         shearY(g, w1, h1, color);
244     }
245 
246     private static void shearX(Graphics g, int w1, int h1, Color color) {
247 
248         int period = random.nextInt(2);
249 
250         boolean borderGap = true;
251         int frames = 1;
252         int phase = random.nextInt(2);
253 
254         for (int i = 0; i < h1; i++) {
255             double d = (double) (period >> 1)
256                     * Math.sin((double) i / (double) period
257                     + (6.2831853071795862D * (double) phase)
258                     / (double) frames);
259             g.copyArea(0, i, w1, 1, (int) d, 0);
260             if (borderGap) {
261                 g.setColor(color);
262                 g.drawLine((int) d, i, 0, i);
263                 g.drawLine((int) d + w1, i, w1, i);
264             }
265         }
266 
267     }
268 
269     private static void shearY(Graphics g, int w1, int h1, Color color) {
270 
271         int period = random.nextInt(40) + 10; // 50;
272 
273         boolean borderGap = true;
274         int frames = 20;
275         int phase = 7;
276         for (int i = 0; i < w1; i++) {
277             double d = (double) (period >> 1)
278                     * Math.sin((double) i / (double) period
279                     + (6.2831853071795862D * (double) phase)
280                     / (double) frames);
281             g.copyArea(i, 0, 1, h1, 0, (int) d);
282             if (borderGap) {
283                 g.setColor(color);
284                 g.drawLine(i, (int) d, i, 0);
285                 g.drawLine(i, (int) d + h1, i, h1);
286             }
287 
288         }
289 
290     }
291 }
SqlSessionFactoryUtils.java
 1 package com.util;
 2 
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 6 
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 
10 public class SqlSessionFactoryUtils {
11 
12     private static SqlSessionFactory sqlSessionFactory;
13 
14     static {
15         //静态代码块会随着类的加载而自动执行,且只执行一次
16         try {
17             String resource = "mybatis-config.xml";
18             InputStream inputStream = Resources.getResourceAsStream(resource);
19             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23     }
24 
25 
26     public static SqlSessionFactory getSqlSessionFactory(){
27         return sqlSessionFactory;
28     }
29 }
LoginFilter.java(拦截器)
 1 package com.web.filter;
 2 
 3 import javax.servlet.*;
 4 import javax.servlet.annotation.WebFilter;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpSession;
 7 import java.io.IOException;
 8 
 9 /**
10  * 登录验证的过滤器
11  */
12 @WebFilter("/*")
13 public class LoginFilter implements Filter {
14     @Override
15     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
16         HttpServletRequest req = (HttpServletRequest) request;
17         //判断访问资源路径是否和登录注册相关
18         String[] urls = {"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};
19         // 获取当前访问的资源路径
20         String url = req.getRequestURL().toString();
21 
22         //循环判断
23         for (String u : urls) {
24             if(url.contains(u)){
25                 //找到了
26                 //放行
27                 chain.doFilter(request, response);
28                 //break;
29                 return;
30             }
31         }
32         //1. 判断session中是否有user
33         HttpSession session = req.getSession();
34         Object user = session.getAttribute("user");
35 
36         //2. 判断user是否为null
37         if(user != null){
38             // 登录过了
39             //放行
40             chain.doFilter(request, response);
41         }else {
42             // 没有登陆,存储提示信息,跳转到登录页面
43 
44             req.setAttribute("login_msg","您尚未登陆!");
45             req.getRequestDispatcher("/login.jsp").forward(req,response);
46         }
47 
48     }
49     public void init(FilterConfig config) throws ServletException {
50     }
51     public void destroy() {
52     }
53 }
CheckCodeServlet.java
 1 package com.web.servlet;
 2 
 3 import com.util.CheckCodeUtil;
 4 import com.util.CheckCodeUtil;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.ServletOutputStream;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 import java.io.IOException;
14 
15 @WebServlet("/checkCodeServlet")
16 public class CheckCodeServlet extends HttpServlet {
17     @Override
18     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19 
20         // 生成验证码
21         ServletOutputStream os = response.getOutputStream();
22         String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
23 
24 
25         // 存入Session
26         HttpSession session = request.getSession();
27         session.setAttribute("checkCodeGen",checkCode);
28 
29 
30     }
31 
32     @Override
33     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34         this.doGet(request, response);
35     }
36 }
LoginServlet.java
package com.web.servlet;

import com.MD5.MD5;
import com.pojo.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.ResultType;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        MD5 md51=new MD5();
        String s1 = MD5.convertMD5(password);
        //String s = DigestUtils.md5Hex(password.getBytes());
        System.out.println(s1);
        //获取复选框数据
        String remember = request.getParameter("remember");

        //2. 调用service查询
        User user = service.login(username, s1);
        // 获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");

        // 程序生成的验证码,从Session获取
        HttpSession session1 = request.getSession();
        String checkCodeGen = (String) session1.getAttribute("checkCodeGen");

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){

            request.setAttribute("register_msg","验证码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            // 不允许注册
            return;
        }

        //3. 判断
        if(user != null){
            //登录成功,跳转到查询所有的BrandServlet

            //判断用户是否勾选记住我
            if("1".equals(remember)){
                //勾选了,发送Cookie

                //1. 创建Cookie对象
                Cookie c_username = new Cookie("username",username);
                Cookie c_password = new Cookie("password",password);
                // 设置Cookie的存活时间
                c_username.setMaxAge( 60 * 60 * 24 * 7);
                c_password.setMaxAge( 60 * 60 * 24 * 7);
                //2. 发送
                response.addCookie(c_username);
                response.addCookie(c_password);
            }

            //将登陆成功后的user对象,存储到session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/brand.html");
        }else {
            // 登录失败,

            // 存储错误信息到request
            request.setAttribute("login_msg","用户名或密码错误");

            // 跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

servlet.java

 1 package com.web.servlet;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.IOException;
 8 import java.lang.reflect.InvocationTargetException;
 9 import java.lang.reflect.Method;
10 public class servlet extends HttpServlet {
11     //根据请求的最后一段路径来进行方法分发
12     @Override
13     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
14         //1. 获取请求路径
15         String uri = req.getRequestURI(); // /brand-case/brand/selectAll
16 
17         //2. 获取最后一段路径,方法名
18         int index = uri.lastIndexOf('/');
19         String methodName = uri.substring(index + 1); //  /selectAll? selectAll?
20 
21         //2. 执行方法
22         //2.1 获取BrandServlet /UserServlet 字节码对象 Class
23 
24         Class<? extends servlet> cls = this.getClass();
25         //2.2 获取方法 Method对象
26         try {
27             Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
28             //2.3 执行方法
29             method.invoke(this,req,resp);
30         } catch (NoSuchMethodException e) {
31             e.printStackTrace();
32         } catch (IllegalAccessException e) {
33             e.printStackTrace();
34         } catch (InvocationTargetException e) {
35             e.printStackTrace();
36         }
37 
38 
39     }
40 }

xiewen.java

 1 package com.web.servlet;
 2 import com.alibaba.fastjson.JSON;
 3 import com.service.impl.xiewenImpl;
 4 import com.service.xiewenService;
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 import java.io.BufferedReader;
10 import java.io.IOException;
11 import java.net.URLEncoder;
12 import java.util.List;
13 @WebServlet("/xiewen/*")
14 public class xiewen extends servlet{
15     private xiewenService xiewenServices= new xiewenImpl();
16     public void all(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         //1. 调用service查询
18         List<com.pojo.xiewen> xiewens = xiewenServices.selectall();
19         //2. 转为JSON
20         String jsonString = JSON.toJSONString(xiewens);
21         //3. 写数据
22         response.setContentType("text/json;charset=utf-8");
23         response.getWriter().write(jsonString);
24     }
25     public  void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26         //1. 接收品牌数据
27         BufferedReader br = request.getReader();
28         String params = br.readLine();//json字符串
29         //转为Brand对象
30         com.pojo.xiewen xiewen = JSON.parseObject(params, com.pojo.xiewen.class);
31         //2. 调用service添加
32          xiewenServices.add(xiewen);
33         //3. 响应成功的标识*/
34         response.getWriter().write("success");
35     }
36     public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
37         request.setCharacterEncoding("utf-8");
38        BufferedReader br = request.getReader();
39         String params = br.readLine();//json字符串
40         xiewenServices.deleteById(params);
41         //3. 响应成功的标识
42         response.getWriter().write("success");
43     }
44     public  void updateById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
45 
46         //1. 接收数据
47         BufferedReader br = request.getReader();
48         String params = br.readLine();//json字符串
49 
50         //转为 int
51         com.pojo.xiewen xiewen = JSON.parseObject(params, com.pojo.xiewen.class);
52 
53 
54         //2. 调用service添加
55         xiewenServices.updateById(xiewen);
56 
57         //3. 响应成功的标识
58         response.getWriter().write("success");
59     }
60     public void tiaocha(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
61         BufferedReader br = request.getReader();
62         String params = br.readLine();//json字符串
63         com.pojo.xiewen xiewen1 = JSON.parseObject(params, com.pojo.xiewen.class);
64         List<com.pojo.xiewen> tiaocha = xiewenServices.tiaocha(xiewen1);
65         String s = JSON.toJSONString(tiaocha);
66         System.out.println(s);
67         response.setContentType("text/json;charset=utf-8");
68         response.getWriter().write(s);
69     }
70 }

brand.html

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <style>
  7         .el-table .warning-row {
  8             background: oldlace;
  9         }
 10         .el-table .success-row {
 11             background: #f0f9eb;
 12         }
 13     </style>
 14 </head>
 15 <body>
 16 <button onclick="location.href='h.html'">点我</button>
 17 <div id="app">
 18     <!--搜索表单-->
 19     <el-form :inline="true" :model="xin" class="demo-form-inline">
 20         <el-form-item label="新闻">
 21             <el-input v-model="xin.xinwen" placeholder="企业名称"></el-input>
 22         </el-form-item>
 23 
 24         <el-form-item label="栏目">
 25             <el-input v-model="xin.lanmu" placeholder="品牌名称"></el-input>
 26         </el-form-item>
 27 
 28         <el-form-item>
 29             <el-button type="primary" @click="onSubmit">查询</el-button>
 30         </el-form-item>
 31 
 32     </el-form>
 33     <!--按钮-->
 34     <el-row>
 35 
 36         <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
 37         <el-button type="primary" plain @click="dialogVisible = true">新增</el-button>
 38     </el-row>
 39     <!--添加数据对话框表单-->
 40     <el-dialog
 41             title="编辑"
 42             :visible.sync="dialogVisible"
 43             width="30%"
 44     >
 45         <el-form ref="form" :model="xin" label-width="80px">
 46             <el-form-item label="新闻">
 47                 <el-input v-model="xin.xinwen"></el-input>
 48             </el-form-item>
 49 
 50             <el-form-item label="栏目">
 51                 <el-input v-model="xin.lanmu"></el-input>
 52             </el-form-item>
 53             <el-form-item>
 54                 <el-button type="primary" @click="addxin">提交</el-button>
 55                 <el-button @click="dialogVisible = false">取消</el-button>
 56             </el-form-item>
 57         </el-form>
 58 
 59     </el-dialog>
 60     <!--表格-->
 61     <template>
 62         <el-table
 63                 :data="tableData"
 64                 style="width: 100%"
 65                 :row-class-name="tableRowClassName"
 66                 @selection-change="handleSelectionChange">
 67             <el-table-column
 68                     type="selection"
 69                     width="55">
 70             </el-table-column>
 71             <el-table-column
 72                     type="index"
 73                     width="50">
 74             </el-table-column>
 75 
 76             <el-table-column
 77                     prop="xinwen"
 78                     label="新闻"
 79                     align="center"
 80             >
 81             </el-table-column>
 82             <el-table-column
 83                     prop="lanmu"
 84                     label="栏目"
 85                     align="center"
 86             >
 87             </el-table-column>
 88             <el-table-column
 89                     align="center"
 90                     label="操作">
 91                 <template slot-scope="scope">
 92                         <el-button type="primary" plain @click="updateById(scope.$index, scope.row)">修改</el-button>
 93                         <el-button type="danger" plain @click="deleteById(scope.$index, scope.row)">删除</el-button>
 94                     <!--修改数据的对话框表单-->
 95                     <el-dialog
 96                             title="修改信息"
 97                             :visible.sync="centerVisible"
 98                             width="30%"
 99                     >
100                         <el-form ref="form" :model=" xin" label-width="80px">
101                             <el-form-item label="新闻">
102                                 <el-input v-model="xin.xinwen"></el-input>
103                             </el-form-item>
104                             <el-form-item label="栏目">
105                                 <el-input v-model="xin.lanmu"></el-input>
106                             </el-form-item>
107                             <el-form-item>
108                                 <el-button type="primary" @click="edit">提交</el-button>
109                                 <el-button @click="centerVisible =false">取消</el-button>
110                             </el-form-item>
111                         </el-form>
112                     </el-dialog>
113                 </template>
114             </el-table-column>
115         </el-table>
116     </template>
117     <!--&lt;!&ndash;分页工具条&ndash;&gt;
118     <el-pagination
119             @size-change="handleSizeChange"
120             @current-change="handleCurrentChange"
121             :current-page="currentPage"
122             :page-sizes="[5, 10, 15, 20]"
123             :page-size="5"
124             layout="total, sizes, prev, pager, next, jumper"
125             :total="totalCount">
126     </el-pagination>-->
127 </div>
128 <script src="js/vue.js"></script>
129 <script src="element-ui/lib/index.js"></script>
130 <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
131 
132 <script src="js/axios-0.18.0.js"></script>
133 <script>
134     new Vue({
135         el: "#app",
136 
137         mounted(){
138             //当页面加载完成后,发送异步请求,获取数据
139 
140             this.selectAll();
141 
142         },
143 
144         methods: {
145 
146             // 查询分页数据
147             selectAll(){
148                 var _this=this;
149                 axios({
150                     method:"get",
151                     url:"http://localhost:8080/xinwen/xiewen/all"
152 
153                 }).then(function (resp)
154                 {
155                     _this.tableData=resp.data;
156                 })
157 
158 
159             },
160 
161             tableRowClassName({row, rowIndex}) {
162                 if (rowIndex === 1) {
163                     return 'warning-row';
164                 } else if (rowIndex === 3) {
165                     return 'success-row';
166                 }
167                 return '';
168             },
169             // 复选框选中后执行的方法
170             handleSelectionChange(val) {
171                 this.multipleSelection = val;
172 
173             },
174             // 查询方法
175             onSubmit() {
176                 var _this = this;
177 
178                 // 发送ajax请求,添加数据
179                 axios({
180                     method:"post",
181                     url:"http://localhost:8080/xinwen/xiewen/tiaocha",
182                     data:_this.xin
183                 }).then(function (resp) {
184 
185                         //添加成功
186 
187                         //关闭窗口
188 
189 
190                         // 重新查询数据
191                       /*  _this.selectAll();*/
192                         _this.tableData=resp.data;
193 
194 
195                 })
196 
197             },
198             // 添加数据
199             addxin() {
200                 var _this = this;
201 
202                 // 发送ajax请求,添加数据
203                 axios({
204                     method:"post",
205                     url:"http://localhost:8080/xinwen/xiewen/add",
206                     data:_this.xin
207                 }).then(function (resp) {
208                     if(resp.data == "success"){
209                         //添加成功
210 
211                         //关闭窗口
212                         _this.dialogVisible = false;
213 
214                         // 重新查询数据
215                         _this.selectAll();
216                         // 弹出消息提示
217                         _this.$message({
218                             message: '恭喜你,添加成功',
219                             type: 'success'
220                         });
221 
222                     }
223                 })
224 
225             },
226 
227           /*  //分页
228             handleSizeChange(val) {
229 
230             },
231             handleCurrentChange(val) {
232 
233             },*/
234             // 删除
235             deleteById(index, row){
236 
237                 // 弹出确认提示框
238 
239                 this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
240                     confirmButtonText: '确定',
241                     cancelButtonText: '取消',
242                     type: 'warning'
243                 }).then(() => {
244                     //用户点击确认按钮
245 
246                     //2. 发送AJAX请求
247                     var _this = this;
248 
249                     // 发送ajax请求,添加数据
250                     axios({
251                         method:"post",
252                         url:"http://localhost:8080/xinwen/xiewen/deleteById",
253                         data:row.xinwen
254                     }).then(function (resp) {
255                         if(resp.data == "success"){
256                             //删除成功
257 
258                             // 重新查询数据
259                             _this.selectAll();
260                             // 弹出消息提示
261                             _this.$message({
262                                 message: '恭喜你,删除成功',
263                                 type: 'success'
264                             });
265 
266                         }
267                     })
268                 }).catch(() => {
269                     //用户点击取消按钮
270 
271                     this.$message({
272                         type: 'info',
273                         message: '已取消删除'
274                     });
275                 });
276 
277             },
278             updateById(index, row) {
279                 this.xin.xinwen=row.xinwen;
280                 this.xin.lanmu=row.lanmu;
281                 this.centerVisible = true;
282 
283             },
284             //修改数据的部分内容
285             edit() {
286                 var _this = this;
287                 //发送ajax异步请求,添加数据
288                 axios({
289                     method: "post",
290                     url: "http://localhost:8080/xinwen/xiewen/updateById",
291                     data: _this.xin
292                 }).then(function (resp) {
293                     if (resp.data == "success") {
294                         //关闭窗口
295                         _this.centerVisible = false;
296                         //查询一次
297                         _this.selectAll();
298                         _this.$message({
299                             message: '恭喜你,修改数据成功',
300                             type: 'success'
301                         });
302                     } else {
303                         _this.$message.error('修改数据失败');
304                     }
305                 })
306             },
307             // 批量删除
308             deleteByIds(){}
309         },
310         data() {
311             return {
312                 // 每页显示的条数
313                 pageSize:5,
314                 // 总记录数
315                 totalCount:100,
316                 // 当前页码
317                 currentPage: 1,
318                 // 添加数据对话框是否展示的标记
319                 dialogVisible: false,
320                 centerVisible:false,
321                 // 品牌模型数据
322                 xin: {
323                     xinwen: '',
324                     lanmu: ''
325                 },
326                 // 被选中的id数组
327                 selectedIds:[],
328                 // 复选框选中数据集合
329                 multipleSelection: [],
330                 // 表格数据
331                 tableData: [{
332                     xinwen: '',
333                     lanmu: ''
334                 }, {
335                     xinwen: '',
336                     lanmu: ''
337                 }]
338             }
339         }
340     })
341 </script>
342 </body>
343 </html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
    <form action="/xinwen/loginServlet" method="post" id="form">
        <h1 id="loginMsg">LOGIN IN</h1>
        <div id="errorMsg">${login_msg} ${register_msg}</div>
        <p>Username:<input id="username" name="username" value="${cookie.username.value}" type="text"></p>
        <p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>
        <p> 验证码
            <input name="checkCode" type="text" id="checkCode">
            <img id="checkCodeImg" src="/xinwen/checkCodeServlet">
            <a href="#" id="changeImg" >看不清?</a>
        </p>
        <p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
        <div id="subDiv">
            <input type="submit" class="button" value="login up">
            <input type="reset" class="button" value="reset">&nbsp;&nbsp;&nbsp;
            <a href="register.jsp">没有账号?</a>
        </div>
    </form>
</div>
<script>
    document.getElementById("changeImg").onclick = function () {
        document.getElementById("checkCodeImg").src = "/xinwen/checkCodeServlet?"+new Date().getMilliseconds();
    }
</script>
</body>
</html>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>org.example</groupId>
  <artifactId>xinwen</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>xinwen Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!--Servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>


    <!--MyBatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <!--MySQL-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>


    <!--fastjson-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.62</version>
    </dependency>

    <!--jsp-->

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>

    <!--jstl-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.6</version>
    </dependency>
  </dependencies>


  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
      </plugin>
    </plugins>
  </build>
</project>

 

 

 

 

 

 

 

posted @ 2023-02-22 21:58  阿飞藏泪  阅读(169)  评论(0编辑  收藏  举报
1 2 3
4