该demo是下链接demo的加上登录(记住我、已登录用户名回显)和注册(图片验证码):MVC分层开发模式小Demo——Servlet+JSP+Mybatis_阳光明媚UPUP的博客-CSDN博客
项目结构
pom文件
<?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>MvcModule</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<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>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/MvcModule</path><!--虚拟目录-->
</configuration>
</plugin>
</plugins>
</build>
</project>
数据层pojo
@Data//包括get、set、equals、hashCode、canEqual、toString、无参构造,没有有参构造
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String password;
private String email;
private Date birthday;
private String infoId;
private String englishTeacher;
public User(Integer id, String name, String password, String email, Date birthday, String infoId, String englishTeacher) {
this.id = id;
this.name = name;
this.password = password;
this.email = email;
this.birthday = birthday;
this.infoId = infoId;
this.englishTeacher = englishTeacher;
}
}
resource的mybatis核心配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.kdy.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development"><!--环境development、test,可以配置多个数据库连接的环境信息,将来通过default属性切换-->
<transactionManager type="JDBC"/><!--事务管理器,spring可接管-->
<dataSource type="POOLED"><!--数据源-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///jdbc?useSSL=false"/>
<!--如果mysqlurl中有&符号需要进行转义为&,如useSSL=false&useServerPrepStmts=true
127.0.0.1:3306本机默认端口可省略不写,直接为///-->
<property name="username" value="root"/>
<property name="password" value="root123"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.kdy.mapper"/>
</mappers>
</configuration>
数据层:mapper接口
public interface UserMapper {
@Select("select * from users where name = #{name} and password = #{password}")
@ResultMap("userResultMap")
User selectByNameAndPwd(@Param("name")String name, @Param("password")String password);
@Select("select * from users where name = #{name}")
@ResultMap("userResultMap")
User selectByName(@Param("name") String name);
@Insert("insert into users(name,password,email,birthday,infoId,english_teacher)" +
" values(#{name},#{password},#{email},#{birthday},#{infoId},#{englishTeacher});")
int insert(User user);
@Select("select * from users")
@ResultMap("userResultMap")
List<User> selectAll();
@Delete("delete from users where id = #{id}")
int delete(int id);
@Select("select * from users where id = #{id}")
@ResultMap("userResultMap")
User selectById(@Param("id") int id);
@Update("update users set name=#{name},password=#{password},email=#{email},birthday=#{birthday}," +
"infoId=#{infoId},english_teacher=#{englishTeacher} where id = #{id}")
int update(User user);
}
sql映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kdy.mapper.UserMapper">
<resultMap id="userResultMap" type="user">
<result column="english_teacher" property="englishTeacher"/>
<!--其他需要映射的字段接着上行格式往下写即可-->
</resultMap>
</mapper>
SqlSessionFactoryUtils
/**
* 通过静态代码块使得该类再被JVM加载时仅执行唯一一次静态代码块中的内容,生成一个sqlSessionFactory对象保存在该类变量中
* 后续直接通过public的getSqlSessionFactory方法拿到这个对象即可。避免重复频繁创建sqlSessionFactory对象的问题。
*/
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
图片验证码生成器VerifyCodeUtil
package com.kdy.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* 验证码生成器
* 可生成数字、大写、小写字母及三者混合类型的验证码
* 支持自定义验证码字符数量,支持自定义验证码图片的大小,支持自定义需排除的特殊字符,支持自定义干扰线的数量,支持自定义验证码图文颜色
*/
public class VerifyCodeUtil {
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
private static Random random = new Random();
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
}
public static BufferedImage getImage(int w,int h,String code){
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
return image;
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
BufferedImage image = getImage(w,h,code);
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public static void main(String[] args) throws IOException{
File dir = new File("F:/verifies");
int w = 45, h = 80;
for(int i = 0; i < 50; i++){
String verifyCode = generateVerifyCode(5);
File file = new File(dir, verifyCode + ".jpg");
outputImage(w*verifyCode.length(), h, file, verifyCode);
}
}
}
业务层:userService
public class UserService {
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
public User login(String username,String password){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectByNameAndPwd(username, password);
sqlSession.close();
return user;
}
public List<User> selectAll(){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectAll();
sqlSession.close();
return userList;
}
public int addUser(User user){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.insert(user);
if (count>0){
sqlSession.commit();
}
sqlSession.close();
return count;
}
public User selectByName(String name){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectByName(name);
return user;
}
public User selectById(int id){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectById(id);
return user;
}
public int updateUser(User user){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.update(user);
if (count>0){
sqlSession.commit();
}
sqlSession.close();
return count;
}
public int delete(int id){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.delete(id);
if (count>0){
sqlSession.commit();
}
sqlSession.close();
return count;
}
}
表现层登录界面jsp/login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/MvcModule/loginServlet" id="form" method="post">
<h1>LOGIN IN</h1>
<div id="loginSuccess">${registerMsg}</div><br>
<div id="errorMsg">${loginMsg}</div>
<p>UserName:<input name="name" type="text" value="${cookie.name.value}"></p><!--记住我功能,cookie回填-->
<p>Password:<input name="password" type="password" value="${cookie.password.value}"></p>
<p>Remember:<input name="remember" type="checkbox" value="1"></p>
<input type="submit" value="login up">
<input type="reset" value="reset">
<a href="/MvcModule/jsp/register.jsp">没有账号?</a>
</form>
</body>
</html>
表现层loginServlet
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");//POST请求的参数的中文乱码解决方式
String name = req.getParameter("name");
String password = req.getParameter("password");
String remember = req.getParameter("remember");
User user = userService.login(name, password);
if (user!= null){
if ("1".equals(remember)){//记住我
Cookie nameCookie = new Cookie("name", name);
Cookie passwordCookie = new Cookie("password", password);
nameCookie.setMaxAge(60*60*24*7);
passwordCookie.setMaxAge(60*60*24*7);
resp.addCookie(nameCookie);
resp.addCookie(passwordCookie);
}
HttpSession session = req.getSession();
session.setAttribute("user",user);
String contextPath = req.getContextPath();//重定向发给浏览器地址去重新发请求,所以需要contextPath
resp.sendRedirect(contextPath+"/selectAllServlet");
}else {
req.setAttribute("loginMsg","用户名或密码错误");
req.getRequestDispatcher("/jsp/login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表现层注册界面jsp/register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>register</title>
</head>
<body>
<form action="/MvcModule/registerServlet" method="post">
<p>${registerMsg}</p>
用户名: <input name="name" type="text"/><br/>
密码: <input name="password" type="text"><br/>
验证码:<input name="checkCode" type="text"><img id="checkCodeImg" src="/MvcModule/checkCodeServlet">
<a href="#" id="changeImg">看不清</a><br/>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
<script>
document.getElementById("changeImg").onclick = function () {
document.getElementById("checkCodeImg").src = "/MvcModule/checkCodeServlet?"+new Date().getMilliseconds();
}
</script>
</body>
</html>
表现层registerServlet
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
private UserService userService = new UserService();
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");//POST请求的参数的中文乱码解决方式
String name = req.getParameter("name");
String password = req.getParameter("password");
String checkCode = req.getParameter("checkCode");
HttpSession session = req.getSession();
String checkCodeGen = (String)session.getAttribute("checkCodeGen");
if (!checkCodeGen.equalsIgnoreCase(checkCode)){
req.setAttribute("registerMsg","验证码错误");
req.getRequestDispatcher("/jsp/register.jsp").forward(req,resp);
return;
}
User user = new User();
user.setName(name);
user.setPassword(password);
User existUser = userService.selectByName(name);
if (existUser == null) {
int count = userService.addUser(user);
if (count > 0) {
req.setAttribute("registerMsg", "注册成功,请登录");
req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
}
}else{
req.setAttribute("registerMsg","用户名已存在");
req.getRequestDispatcher("jsp/register.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
表现层checkCodeServlet
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream os = resp.getOutputStream();
String checkCode = VerifyCodeUtil.outputVerifyImage(100, 50, os, 4);
HttpSession session = req.getSession();
session.setAttribute("checkCodeGen",checkCode);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表现层selectAllServlet
@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> users = userService.selectAll();
req.setAttribute("users",users);
req.getRequestDispatcher("/jsp/user.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表现层列表页jsp/user.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!--引入jstl标签库URI-->
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>User</title>
</head>
<body>
<p>当前登录的账号用户名为${user.name}</p><a href="/MvcModule/logoutServlet">退出登录</a><br/>
<input type="button" value="新增" id="add"><br/>
<table border="1px">
<tr align="center">
<td>jstl序号</td>
<td>ID</td>
<td>name</td>
<td>密码></td>
<td>email</td>
<td>生日</td>
<td>infoId</td>
<td>englishTeacher</td>
<td>操作</td>
</tr>
<c:forEach items="${users}" var="user" varStatus="order">
<tr align="center">
<td>${order.index}</td>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.password}</td>
<td>${user.email}</td>
<td><fmt:formatDate value="${user.birthday}" pattern="yyyy-MM-dd"/></td>
<td>${user.infoId}</td>
<td>${user.englishTeacher}</td>
<td><a href="/MvcModule/selectByIdServlet?id=${user.id}">修改</a>&<a href="/MvcModule/deleteByIdServlet?id=${user.id}">删除</a></td>
</tr>
</c:forEach>
</table>
<h3>分页</h3>
<c:forEach begin="1" end="10" step="1" var="i">
<a href="#">${i}</a>
</c:forEach>
</body>
<script>
document.getElementById("add").onclick = function () {
location.href = "addUser.jsp";
}
</script>
</html>
表现logoutServlet
@WebServlet("/logoutServlet")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();
String contextPath = req.getContextPath();
resp.sendRedirect(contextPath+"/jsp/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表现层:新增
addUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>addUser</title>
</head>
<body>
<form action="/MvcModule/AddServlet" method="post">
用户名: <input name="name" type="text"/><br/>
密码: <input name="password" type="text"><br/>
邮箱: <input name="email" type="text"><br/>
生日: <input name="birthday" type="date"><br/>
infoId: <input name="infoId" type="text"><br/>
英语老师:<input name="englishTeacher" type="text">
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private UserService userService = new UserService();
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");//POST请求的参数的中文乱码解决方式
String name = req.getParameter("name");
String password = req.getParameter("password");
String email = req.getParameter("email");
String birthday = req.getParameter("birthday");
String infoId = req.getParameter("infoId");
String englishTeacher = req.getParameter("englishTeacher");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateBirthday = sdf.parse(birthday);
User user = new User(null, name, password, email, dateBirthday, infoId, englishTeacher);
int count = userService.addUser(user);
if (count>0){
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}else{
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("新增失败");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
表现层:修改
@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
User user = userService.selectById(Integer.parseInt(id));
req.setAttribute("user",user);
req.getRequestDispatcher("/jsp/update.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>UpdateUser</title>
</head>
<body>
<h3>修改</h3>
<form action="/MvcModule/updateServlet" method="post">
<input style="display:none;" name="id" value="${user.id}">
用户名: <input name="name" type="text" value="${user.name}"><br/>
密码: <input name="password" type="text" value="${user.password}"><br/>
邮箱: <input name="email" type="text" value="${user.email}"><br/>
生日:<input name="birthday" type="date" value="<fmt:formatDate value="${user.birthday}" pattern="yyyy-MM-dd"/>" required="required"><br/>
infoId: <input name="infoId" type="text" value="${user.infoId}"><br/>
英语老师:<input name="englishTeacher" type="text" value="${user.englishTeacher}">
<input type="submit" value="提交">
</form>
</body>
</html>
@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
UserService userService = new UserService();
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");//POST请求的参数的中文乱码解决方式
String id = req.getParameter("id");
String name = req.getParameter("name");
String password = req.getParameter("password");
String email = req.getParameter("email");
String birthday = req.getParameter("birthday");
String infoId = req.getParameter("infoId");
String englishTeacher = req.getParameter("englishTeacher");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateBirthday = sdf.parse(birthday);
User user = new User(Integer.valueOf(id), name, password, email, dateBirthday, infoId, englishTeacher);
int count = userService.updateUser(user);
if (count > 0) {
req.getRequestDispatcher("/selectAllServlet").forward(req, resp);
} else {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("修改失败");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
表现层:删除
@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
int count = userService.delete(Integer.valueOf(id));
if (count > 0) {
req.getRequestDispatcher("/selectAllServlet").forward(req, resp);
} else {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("删除失败");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}