当前位置: 首页> 文旅> 艺术 > 天元集团建设有限公司简介_科技为了上大学上交可控核聚变笔趣阁_单页面网站如何优化_推广平台哪儿有怎么做

天元集团建设有限公司简介_科技为了上大学上交可控核聚变笔趣阁_单页面网站如何优化_推广平台哪儿有怎么做

时间:2025/7/12 19:54:09来源:https://blog.csdn.net/m0_74217128/article/details/147124053 浏览次数:0次
天元集团建设有限公司简介_科技为了上大学上交可控核聚变笔趣阁_单页面网站如何优化_推广平台哪儿有怎么做

创建工程

        新建项目,选择maven工程,原型(Archetype)选择maven的webapp,注意名称头尾。会使用到tomcat(因为是javaWeb)。

         新建的项目结构目录如下,如果没有java目录,需要自己手动创建,创建之后,记得将其标记为源代码目录。

 

 创建配置类

        使用配置类来替代xml配置。我们有两个配置文件需要使用配置类来进行替代:一个是spring的Bean配置xml文件,一个是web.xml。

springBean:

        使用两个注解@Configuration、@ComponentScan

package config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration//声明该类为配置类
@ComponentScan({"config","controller","entity"})//启用扫描,扫描指定包下的所有注解
public class SpringConf {
}

web.xml:

        继承AbstractDispatcherServletInitializer 类,实现里面的三个抽象方法。

createServletApplicationContext():

        注册用于管理DispatcherServlet 的专用子应用上下文,即web组件的上下文,如controller层

getServletMappings():

        定义 DispatcherServlet 的 URL 映射,DispatcherServlet 是 Spring MVC 的核心,负责处理所有 HTTP 请求。

createRootApplicationContext:

        创建根应用上下文,即父级上下文(web资源通常在次一级目录里,可以看前面创建项目时的目录结构),通常用于管理服务层(@Service)、数据层(@Repository)、数据源、事务等非 Web 组件。这里因为我不对其他的层做演示,所以该方法为空。

package config;import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;public class WebConfig extends AbstractDispatcherServletInitializer {@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext a =new AnnotationConfigWebApplicationContext();a.register(SpringConfig.class);return a;}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}@Overrideprotected WebApplicationContext createRootApplicationContext() {return null;}
}

 

创建控制器类

        使用注解@Controller声明MVC的控制器类,告诉Spring容器该类负责处理HTTP请求。再使用@RequestMapping来绑定url。

示例:

package controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;@Controller
//给该controller类设置一个专属url,避免和其他控制器类里的方法的url冲突
@RequestMapping("/text")
public class Text {@RequestMapping("/test1")public String test1(@RequestParam("username") String username, @RequestParam("password") String password) {if(username.equals("liu") && password.equals("123")) {System.out.println("登录成功");return "success";}return "failure";}
}

关键字:天元集团建设有限公司简介_科技为了上大学上交可控核聚变笔趣阁_单页面网站如何优化_推广平台哪儿有怎么做

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: