Java Web项目开发灵感和知识点总结

Java Web项目开发灵感和知识点总结,第1张

关于项目开发技术方案 基本骨架:

A:DB(Mysql、Oracle)+ JDBC +javaBean+JSP (M1模型:视图与控制层混合) 打单

B:JSP(JSTL/EL)(AJAX) + servlet(原生框架) + JavaBean +(连接池)+DB(Mysql、Oracle) M2

C: html+jQuery +|+servlet +javaBean +DB ( M2前后端分离架构) 承担架构风险

D: html+jQuery +|+Springmvc +Spring+service+spring+ DAO (Mybatis\JPA\spring-JDBC) +DB

(基于开源框架M2前后端分离)

E:thymeleaf + +springboot (springMVC+spring+mybatis)+DB 替换B方案

F: html(Jquery/angular/vue/react) +springboot (springMVC+spring+mybatis)+DB

(H5+android+IOS+harmonyOS) +springboot (springMVC+spring+mybatis)+DB

分布式微服务:

G:SpringCloud(Eureka、ribbon、feign、hystrix、zuul、config) 微服务

H:基于alibaba (nacos、gateway、feign、setinel) 微服务

I:基于doubbo+zookeeper 微服务

锦上添花 redis 权限系统 基于Filter的拦截的权限验证 A、B、C、D、E、F、基于Interceptor 拦截器的权限系统 A、B、C、D、E、F、G、H基于shiro安全框架的权限系统 a、b、D、E基于security 安全框架的权限系统(仅用于基于spring技术体系)基于单点登陆的权限系统 (分布式、微服务) 报表系统 自定义报表系统(完美级)基于Excel (POI) 图形化(统计) ECharts(直方图、饼图、折线、热力图、雷达) 地理信息(百度)日志系统(非常成熟的产品中) 高并发 redis实现短时间多次读取重复的数据云端数据库实现静态资源的 git设计

分三个分支,

​ 一个主支(普通开发者没有权限向master上推代码,管理员才可以),

​ 一个测试分支从主支拉出来的(往这个上合调试),

​ 一个本地开发分支从主分支拉出来,开发完成上测试调试,通过再上主支

前端框架的选择 VUE----html

1.解释


2.复制


Servlet—jsp

1.解释


2.复制


layui—html

1.解释


2.复制


servlet 方法反射工具类

1.解释

private static final long serialVersionUID = 1L;
public BaseServlet() {
        super();
    }

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Class<? extends BaseController> clazz = this.getClass();
        String op = req.getParameter("op");
        try {
            Method m = clazz.getDeclaredMethod(op,HttpServletRequest.class,HttpServletResponse.class);
            m.setAccessible(true);
            m.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        
    }

2.复制

private static final long serialVersionUID = 1L;
public BaseServlet() {
        super();
    }

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Class<? extends BaseController> clazz = this.getClass();
        String op = req.getParameter("op");
        try {
            Method m = clazz.getDeclaredMethod(op,HttpServletRequest.class,HttpServletResponse.class);
            m.setAccessible(true);
            m.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        
    }

同步响应
1.请求转发
login.jsp-->/user-->登录失败-->服务将结果转发到login.jsp,在此期间客户端只发了一次请求,最终服务器请求到了login.jsp
request.setAttribute("err","错误信息")
request.getRequestDispatcher(url).forward(request,response);
请求转发发生在服务器端,服务器将请求的结果发往另一请求;login.jsp-->/user-->登录失败-->服务将结果转发到login.jsp,在此期间客户端只发了一次请求,最终服务器请求到了login.jsp

1.1复制

request.setAttribute("err","错误信息")
request.getRequestDispatcher(url).forward(request,response);
2.重定向
login.jsp-->/user-->登录成功-->服务器将下一个资源通知客户端,再由客户端发起二次请求到达 index.jsp页面;
response.sendRedirect(url);
请求转发发生在客户端,服务器将请求的结果返回到客户端,客户端再次发请求,到达最终资源处

2.1 复制

response.sendRedirect(url);
异步响应

1.解释


2.复制

  PrintWriter pw = response.getWriter();
  pw.write(message);
  pw.flush();
  pw.close();
接受请求

1.解释


2.复制

String  string = request.getParameter("name");
文件上传

方法1

 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建上传对象
        FileItemFactory fileItemFactory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(fileItemFactory);
        Goods goods=new Goods();//
        Class clazz=goods.getClass();
        //根据请求request获得上传数据
        try {
            List<FileItem> fileItems = upload.parseRequest(req);
            for(FileItem items:fileItems){
                String fieldName=items.getFieldName();//setGname()// method--modify
                //区分是否是普通表单元素/上传IO流
                if(items.isFormField()){
                    //普通字段  值=request.getParameter(字段名)
                    String value=items.getString();
                    Class<?> type = clazz.getDeclaredField(fieldName).getType();
                    if(type== Date.class){
                        BeanUtils.setProperty(goods,fieldName,new SimpleDateFormat("yyyy-MM-dd").parse(value));
                        continue;
                    }
                    BeanUtils.setProperty(goods,fieldName,value);
                    /*Class type=clazz.getDeclaredField(fieldName).getType();//获得属性的类型的类对象 String name;  setName(String name)
                    Method method=clazz.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1),type);
                    method.invoke(goods,value);*/
                }else{
                    //上传文件
                    String filename=items.getName();//上传文件名-->后缀
                    if(filename.length()>0) {
                        //上传文件的存放位置/将存放文件的地址存入到数据库
                        String path = this.getServletContext().getRealPath("/");//服务器的根路径
                        File file = new File(path + "/upload");//准备存放上传文件的位置
                        if (!file.exists()) {
                            file.mkdir();//创建目录
                        }

                        filename = filename.substring(filename.lastIndexOf("."));//aaaa.png
                        filename = UUID.randomUUID().toString() + filename;
                        file = new File(file + "/" + filename);

                        items.write(file);//将文件写出  /upload/dfdsf89sfdsfdsf-dfdfdf.jpg
                        BeanUtils.setProperty(goods, fieldName, "/upload/" + filename);//将地址写入数据库的字段中
                    }
                }
            }
            //将goods传给业务层
            int res=0
            ;
            if(goods.getGid()==null) {
                res=goodsService.add(goods);//update(goods)
            }else {
                res=goodsService.update(goods);
            }

            if(res==1){
                resp.sendRedirect("list.html");
            }else{
                resp.sendRedirect("err.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

方法2

Map<String,String> map = new HashMap<>();
//		1.	创建DiskFileItemFactory对象
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			
			//	2.	使用DiskFileItemFactory对象作为参数创建ServletFileUpload对象
			ServletFileUpload sfu = new ServletFileUpload(dfif);
			try {
				List<FileItem> list = sfu.parseRequest(request);
				for (FileItem fi : list) {
					if(fi.isFormField()) {
						map.put(fi.getFieldName(), fi.getString());
					}else {
						String path = getServletContext().getRealPath("picture");
						System.out.println(path);
						File f = new File(path);
						if(!f.exists()) {
							f.mkdirs();
						}
						String name = fi.getName();
//						System.out.println(name);
						name = name.substring(name.lastIndexOf(File.separator) + 1);
//						System.out.println(name);
						File file = new File(path, name);
						fi.write(file);
					}
					
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			String stid = map.get("tid");
			int tid = stid==null?0:Integer.parseInt(stid);
			String pid = map.get("pid");
			System.out.println(pid);
			String pname = map.get("pname");
			String soprice = map.get("oprice");
			double oprice =soprice==null?0:Double.parseDouble(soprice);
			String snprice = map.get("nprice");
			Double nprice =soprice==null?0:Double.parseDouble(snprice);
			String head = map.get("head");
			
			
			String gname1 = map.get("gname1");
			String gdesc1 = map.get("gdesc1");
			Imgs imgs1 = new Imgs();
			imgs1.setGdesc(gdesc1);
			imgs1.setGname(gname1);
			imgs1.setPid(pid);
			String gname2 = map.get("gname2");
			String gdesc2 = map.get("gdesc2");
			Imgs imgs2 = new Imgs();
			imgs2.setGdesc(gdesc2);
			imgs2.setGname(gname2);
			imgs2.setPid(pid);
			String gname3 = map.get("gname3");
			String gdesc3 = map.get("gdesc3");
			Imgs imgs3 = new Imgs();
			imgs3.setGdesc(gdesc3);
			imgs3.setGname(gname3);
			imgs3.setPid(pid);
			
			
			List<Imgs> list =new ArrayList<>();
			if(imgs1!=null|gdesc1!=null) {
				list.add(imgs1);
			}
			
			if(imgs2!=null|gdesc2!=null) {
				list.add(imgs2);
			}
			
			if(imgs3!=null|gdesc3!=null) {
				list.add(imgs3);
			}
			
			for (Imgs imgs : list) {
				System.out.println(imgs.toString());
			}

		Product product = new Product(pid,tid,  pname, oprice,  nprice, list,head);
		
		boolean bl = ips.insertProduct(product);
		if (bl) {
				response.getWriter().write("新增成功");
			}else {
				response.getWriter().write("新增失败");
			}
	}

日志 log4J
log4j.rootLogger=debug, abc, F 

log4j.logger.com.james.dao=TRACE

log4j.appender.abc=org.apache.log4j.ConsoleAppender
log4j.appender.abc.layout=org.apache.log4j.PatternLayout
log4j.appender.abc.layout.ConversionPattern=%-7p [%t] - %m%n

log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =mybatis.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = DEBUG
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L]  %m%n
mysql 数据库连接信息

1.解释

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xiaomi1?characterEncoding=utf8
		//jdbc:mysql://localhost:3306/xiaomi1?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8
username=root
password=19980719

2.复制

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/#?characterEncoding=utf8
username=root
password=19980719
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/car?characterEncoding=utf8
jdbc.username=root
jdbc.password=19980719

时间转换工具类

1.解释

public class DateUtil {

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 将指定格式表示日期的字符串转换为日期对象
	 * @param dateStr 表示指定格式的日期字符串
	 * @return 该字符串对应的日期对象
	 */
	public static java.util.Date str2Date(String dateStr){
		try {
			return sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 将日期对象转换为指定格式的字符串
	 * @param d 要转换的日期对象
	 * @return 表示日期的字符串
	 */
	public static String date2Str(java.util.Date d) {
		return sdf.format(d);
	}
	
	/**
	 * 将util包下的日期对象转换为sql包下的日期对象
	 * 
	 * @param d
	 * @return
	 */
	public static java.sql.Date util2SQLDate(java.util.Date d){
		return new java.sql.Date(d.getTime());
	}
}

2.复制

public class DateUtil {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	public static java.util.Date str2Date(String dateStr){
		try {
			return sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String date2Str(java.util.Date d) {
		return sdf.format(d);
	}
	public static java.sql.Date util2SQLDate(java.util.Date d){
		return new java.sql.Date(d.getTime());
	}
}
JDBC原生六步

1.解释


2.复制


druid-API封装

1.解释

public class DBUtil {
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<>();
	private static DruidDataSource dds = null;
	
	static {
		try {
			dds =  (DruidDataSource) DruidDataSourceFactory.createDataSource(Env.getInstance());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static DataSource getDataSource() {
		DataSource createDataSource = DruidDataSourceFactory.createDataSource(Env.getInstance());
		DruidDataSource ds = (DruidDataSource) createDataSource;
		return ds;
	}
	/**
	 * 获取数据库连接对象
	 * @return 数据库连接对象
	 * 进一步修改
	 */
	public static Connection getConn() {
		Connection conn =null;
		conn = tl.get();
		try {
			conn = dds.getConnection();
			tl.set(conn);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	
	//开启事务
	public static void begin() {
		Connection conn = getConn();
		try {
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//提交事务
	public static void commit() {
		Connection conn = getConn();
		try {
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//回滚事务
	public static void rollback() {
		Connection conn = getConn();
		try {
			conn.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

2.复制

public class DBtools {
    private static DruidDataSource dataSource;
    static{
        Properties properties=new Properties();
        try {
        properties.load(DBtools.class.getClassLoader().getResourceAsStream("db.properties"));
            dataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static DataSource getDataSource(){
        return dataSource;
    }
}
mybatis-API封装

1.解释

public class SqlSessionTools {
   	
   }

2.复制

public class SqlSessionTools {
 private static SqlSessionFactory build;
 private static SqlSession sqlSession;
static {
     try {
      build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
     } catch (IOException e) {
         e.printStackTrace();
     }
}
 public static SqlSession getSession() {
     sqlSession = build.openSession();
     return sqlSession;
 }
public static void commit() {
  sqlSession.commit();
 sqlSession.close();
}
}
Spring内置

1.解释


2.复制


MyBatis XML配置

1.解释

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
     PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

   1. //添加配置文件
    <properties resource="db.properties"/>

    2. //日志设置---mybatis自带的日志,打印持久层的SQL语句
    <settings>
    	<settings name="logImg" value="STDOUT_LOGGING"/>
    <settings>

    3. //给类型添加别名
    <typeAliases>
    	//一次添加一个别名
        <typeAlias type="com.qf.pojo.Goods" alias="good"/>
    	//添加一个包下的别名
        <package name="com.qf.pojo" />
    </typeAliases>

   //基本配置
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    //管理映射元文件:mapper --idea工程中定义在resources目录下
    <mappers>
    
        <!--添加Mapper.xml的管理-->
        <mapper resource="mapper/GoodsMapper.xml"/>
        <!--<mapper resource="mapper/OrderrMapper.xml"/>-->
    
        <!--添加接口的管理-->
    //直接在接口中使用注解方式实现SQL语句,无需对应的Mapper.xml,所以注册接口文件
        <package name="com.qf.mapper"/>
    </mappers>
</configuration>

2.复制

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="#"/>
    </mappers>
</configuration>
映射元文件(mapper)

1.解释

1.一般采用接口和xml的形式实现

-idea工程中定义在resources目录下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="#"> ---//接口全路径
    ------------ORM映射关系--->一对一----------
    <resultMap id=" " type="">
      
    </resultMap>
    
    <select id="" ></select>	
    
   
    </mapper>

2.复制

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="#">

</mapper>
Spring XML配置

1.解释


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    
    
    <bean id="orderService" class="com.qf.service.impl.OrderServiceImpl"/>
    <bean id="orderService2" class="com.qf.service.impl.OrderServiceImpl"/>

    
    


beans>



1.1 核心类
  ClassPathXmlApplicationContext application = new ClassPathXmlApplicationContext("spring.xml");
  orderService=(OrderService)application.getBean("orderService");
2.复制

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">



beans>

SpringMVC 目录结构

依赖目录
lombok  1.18.2   --需要sroce标签
junit   4.11
jstl   1.2  --使用jsp时导入
    
Spring-webmvc  4.3.6
Spring-jdbc    4.3.6
mybatis      3.4.4
mybatis-Spring  1.3.2
druid           1.1.10
mysql-connector  5.1.41
Servlet-api    --需要sroce标签
XMl配置 service_mybatis 3

1.解释

步骤


    <context:property-placeholder location="classpath:res/db.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
          
        <property name="dataSource" ref="dataSource"/>  
         
        <property name="typeAliasesPackage" value="com.hf.pojo"/>
         
        <property name="mapperLocations" value="classpath:mapping/*.xml"/>
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         
        <property name="basePackage" value="com.hf.mapper"/>
         
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>
beans>

2.复制


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:res/db.properties"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.hf.pojo"/>
        <property name="mapperLocations" value="classpath:mapping/*.xml"/>
    bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hf.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>
beans>
service_service 1

1.解释

 
<context:component-scan base-package="com.hf.service"/>

2.复制


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.hf.service"/>
beans>
springmvc 5

1.解释


 <content:component-scan base-package="com.hf.controller"/>
  
  
 <mvc:annotation-driven/>


<mvc:default-servlet-handler />

 
    <mvc:interceptors>
        <mvc:interceptor>
            <!配置拦截路径>
            <mvc:mapping path="/actor/*"/>
            <bean class="com.lyc.interceotors.MyAuthInterceptor"/>
        mvc:interceptor>
    mvc:interceptors>



 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/views/"/>
     <property name="suffix" value=".jsp"/>
 bean>


 <mvc:resources mapping="/js/**" location="/WEB-INF/static/js/"/>
 <mvc:resources mapping="/css/**" location="/WEB-INF/static/css/"/>
 <mvc:resources mapping="/images/**" location="/WEB-INF/static/images/"/>
 <mvc:resources mapping="/picture/**" location="/WEB-INF/static/picture/"/>


    
   <import resource="classpath:spring-mybatis.xml"/>

2.复制


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:content="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 <content:component-scan base-package="com.hf.controller"/>
 <mvc:annotation-driven/>
 <mvc:default-servlet-handler/>
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/views/"/>
     <property name="suffix" value=".jsp"/>
 bean>
 <mvc:resources mapping="/js/**" location="/WEB-INF/static/js/"/>
 <mvc:resources mapping="/css/**" location="/WEB-INF/static/css/"/>
 <mvc:resources mapping="/images/**" location="/WEB-INF/static/images/"/>
 <mvc:resources mapping="/picture/**" location="/WEB-INF/static/picture/"/>
beans>
web.xml 4

1.解释


<web-app>

<context-param>
 <param-name>contextConfigLocationparam-name>
 <param-value>classpath:spring-*.xmlparam-value>
context-param>
    

<filter>
<filter-name>characterFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    
<init-param>
 <param-name>encodingparam-name>
 <param-value>UTF-8param-value>
init-param>
       
 <init-param>
   <param-name>forceEncodingparam-name>
    <param-value>trueparam-value>
 init-param>
filter>
     
<filter-mapping>
 <filter-name>characterFilterfilter-name>
 <url-pattern>/*url-pattern>
filter-mapping>
    
    
 
<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

   
<servlet>
 <servlet-name>springmvcservlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
      
 <init-param>
   <param-name>contextConfigLocationparam-name>
   <param-value>classpath:springmvc.xmlparam-value>
 init-param>
     
 <load-on-startup>1load-on-startup>
servlet>
      
<servlet-mapping>
 <servlet-name>springmvcservlet-name>
      
 <url-pattern>/url-pattern>
servlet-mapping>
web-app>

2.复制

DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<context-param>
 <param-name>contextConfigLocationparam-name>
 <param-value>classpath:spring-*.xmlparam-value>
context-param>

<filter>
<filter-name>characterFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
 <param-name>encodingparam-name>
 <param-value>UTF-8param-value>
init-param>
 <init-param>
   <param-name>forceEncodingparam-name>
    <param-value>trueparam-value>
 init-param>
filter>
<filter-mapping>
 <filter-name>characterFilterfilter-name>
 <url-pattern>/*url-pattern>
filter-mapping>

<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
    
<servlet>
 <servlet-name>springmvcservlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
 <init-param>
   <param-name>contextConfigLocationparam-name>
   <param-value>classpath:springmvc.xmlparam-value>
 init-param>
 <load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
 <servlet-name>springmvcservlet-name>
 <url-pattern>/url-pattern>
servlet-mapping>

web-app>

核心注解 service层

1.解释

//扫描service层
@Service(value="IProductImgsService")

//Bean的注入 ---Dao的实现类
@Resource
 ProductImgsMapper pim;

2.复制

@Service(value="#")
@Resource
controller层

1.解释

//扫描controller层  
1.   @Controller  ---->返回的是视图
2.   @ResController   ----->返回的json字符串//自动将对象转换为字符串  
    //二者选其一
    

//  Bean的注入--service的实现类  
1.  @Qualifier(value="IProductService")
2.   @Autowired
 private IProductService ips;

//方法地址的映射路径
1. @RequestMapping(value="/list",method= RequestMethod.GET)
2. @GetMapping(value="/list")

返回视图
ModelAndView

 public ModelAndView show1(){
     //获取数据列表
     List<Product> list = new ArrayList<Product>();
     list= productService.getProductList();
     //定义返回对象
     ModelAndView modelAndView = new ModelAndView();
     //设置返回数据
     modelAndView.addObject("productList",list);
     //设置返回页面
     //两种构造器 
     1.setViewName(String)  
          modelAndView.setViewName("/static/productList.jsp");
     2.SetViewName(View)
          View view = new InternalResourceVIew("/static/productList.jsp");
			modelAndView.setVIewName(view)		
     return modelAndView;
 }




Model
@Controller  // 加入到IOC容器
//@RequestMapping(value="/topic")
public class TopicAction 
 @Resource(name = "topicServiceImpl")
 private TopicService topicService;

 @RequestMapping(value="/index")
 public String show2(Model model){
     List<Topic> topicList = topicService.getAllTopicList();
     model.addAttribute("topics", topicList);
     return "index.jsp";
 }
}

转发方式
 // 转发一
 @RequestMapping("/test")
 public String test(Model model){
     model.addAttribute("msg","ModelTest1");
     return "WEB-INF/views/test.jsp";
 }

 // 转发二
 @RequestMapping("/test1")
 public String test1(Model model){
     model.addAttribute("msg","ModelTest1");
     return "forward:/WEB-INF/views/test.jsp";
 }

 // 重定向
 @RequestMapping("/test2")
 public String test2(Model model){
     model.addAttribute("msg","ModelTest2");
     return "redirect:/index.jsp";
 }

Map
public String show2 (Map map){
	map.put("key",value)

}

Void

public void show4(HttpServletRequest,HttpServletResponse){

request.setAttribute("key",value);	
request.getSession();
    
request.getRequestDispatcher(" ").forward(request,response);
response.sendRedirect(" ");


}
返回JSON字符串
@RestController
public class CarController {
    @Autowired
    ICarService ics;
    @GetMapping(value = "/findAllCars")
    public List<Car> findAllCar() {
        List<Car> allCar = ics.findAllCar();
        return allCar;
    }
SpringBoot 目录结构


Maven 依赖解释
<----->Web项目<----->
<packaging>warpackaging>
<dependencies>
    
dependencies>
    
    
Tomcat配置文件
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <version>2.2version>
                <configuration>
                    <port>8080port>
                    <path>/path>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.6.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <compilerVersion>1.8compilerVersion>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
        plugins>
    build>
log4j
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>
分页插件
<dependency>
  <groupId>com.github.pagehelpergroupId>
  <artifactId>pagehelperartifactId>
  <version>5.1.10version>
dependency>
Spring依赖

1 解释

  

2.复制

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>4.3.6.RELEASEversion>
 dependency>
SpringMVC依赖

1 解释


2.复制

  <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>4.3.6.RELEASEversion>
    dependency>
Mybatis-Spring依赖

1 解释


2.复制


    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.2version>
    dependency>
Spring-jdbc依赖

1 解释


2.复制

     <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>4.3.6.RELEASEversion>
    dependency>
Mybatis依赖
 <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.6version>
  dependency>
 
MYSQL依赖
  <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.47version>
  dependency>
 
lombok依赖

1 解释

@Data   ///get、set方法   
@NoArgsConstructor            //无参构造器
@AllArgsConstructor			//全参构造器
@RequiredArgsConstructor   
//对对象的读入--反序列化/写出--序列化;要实现序列化和反序列化的对象,必须实现序列化接口;
public class User implements Serializable {
    private Integer uid;
    @NonNull  //选定构造器
    private String uname;
    private String upass;
    private Date birth;
    private String sex;
    private String tel;
    private String email;

    private List<Orders> olist;

2.复制

<dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
        dependency>
Druid依赖
 <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.24version>
  dependency>
 
JUnit依赖
生命周期

@Before
    public void before(){
       
    }

    @After
    public void after(){
      
    }
2.复制
<dependency>
   <groupId>junitgroupId>
   <artifactId>junitartifactId>
   <version>4.12version>
dependency>

jsp标签库依赖
  <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
  dependency>
 
Servlet依赖
  <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.0.1version>
  dependency>
  
JSON依赖

1.解释

@JSONField(format = "yyyy-MM-dd")
 private Date pubdate;

复制

<dependency>
   <groupId>com.alibabagroupId>
   <artifactId>fastjsonartifactId>
   <version>1.2.58version>
dependency>

    
    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.9.0version>
    dependency>

依赖

<dependency>
      <groupId>commons-dbutilsgroupId>
      <artifactId>commons-dbutilsartifactId>
      <version>1.6version>
  dependency>
 

反射依赖

1.解释

 BeanUtils.setProperty(goods,fieldName,value);
/*Class type=clazz.getDeclaredField(fieldName).getType();
//获得属性的类型的类对象 String name; setName(String name) 
Method   method =
clazz.getDeclaredMethod("set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1),type);
                    method.invoke(goods,value);*/

2.复制

  <dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.9.3version>
   dependency>
文件上传依赖

1.解释

   FileItemFactory fileItemFactory=new DiskFileItemFactory();

2.复制

   <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.4version>
  dependency>  
Servlet项目依赖导入
<packaging>warpackaging>
<dependencies>
  <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.6version>
  dependency>
  <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.47version>
  dependency>
  <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
  dependency>
  <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
  dependency>
  <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.0.1version>
  dependency>
  <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>fastjsonartifactId>
      <version>1.2.58version>
  dependency>
  <dependency>
      <groupId>commons-dbutilsgroupId>
      <artifactId>commons-dbutilsartifactId>
      <version>1.6version>
  dependency>
  <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.4version>
  dependency>
dependencies>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/940074.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-17
下一篇 2022-05-17

发表评论

登录后才能评论

评论列表(0条)

保存