您可以自由使用任何标准的Spring Framework技术来定义您的bean及其注入的依赖关系。为了简单起见,我们经常发现使用@ComponentScan 查找你的bean,结合@Autowired构造函数注入效果很好。
如果您按上述建议构建代码(将应用程序类定位到根包中),则可以添加@ComponentScan任何参数。您的所有应用程序组件(的@Component,@Service,@Repository,@Controller等)将自动注册为bean。
示例:
public interface ProjectService {
//这里是简单实例,简单返回一个bean吧
Project findOneProject();
}
@Service
public class ProjectServiceImpl implements ProjectService{
@Autowired
private Project project;
//这里只简单展示注入
@Override
public Project findOneProject() {
return project;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
@RestController
public class HelloController {
//==============以下是依赖注入的简单示例=======================================
@Autowired
private ProjectService projectService;
@RequestMapping("/handleBean")
public String handleBean() {
return projectService.findOneProject().getAuthor();
}
}
访问http://localhost:8080/handleBean显示:cc
既然做到前台项目springMVC肯定要考虑到跳转到页面上传值过去,熟悉的就是jsp但是
页面上一直显示这个错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
。。。
很无语。去网上查了资料终于调通可以用jsp,el表达式获取值了—-
下面的解决参考了以下网址:
http://www.cnblogs.com/shijiaoyun/p/5841867.html
https://www.oschina.net/question/347227_250528
http://www.cnblogs.com/huzi007/p/7087570.html
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
<scope>providedscope>
dependency>
spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp
@RestController
@RequestMapping("/hello")
public class HelloController {
//==============以下是springmvc相关知识==============================
@RequestMapping("/handleMVC")
public ModelAndView handleMVC() {
ModelAndView mav = new ModelAndView();
Student student = new Student();
student.setName("cc");
student.setSex(1);
student.setTelephone("18800000000");
mav.setViewName("hello/hello1");
mav.addObject("student",student);
return mav;
}
}
Student:
type="text" value="${student.name }"/>
type="text" value="${student.sex }"/>
type="text" value="${student.telephone }"/>
@SpringBootApplication
public class SpringbootDemoApplication extends SpringBootServletInitializer {
/*
* 如果要使用tomcat来加载jsp的话就必须继承springbootServletInitializer类重写其中的configure方法
* @see org.springframework.boot.web.support.SpringBootServletInitializer#configure(org.springframework.boot.builder.SpringApplicationBuilder)
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringbootDemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
访问http://localhost:8080/hello/handleMVC,显示:
到此,我们的web项目就可以正常跳转前后台传值等操作了。
But!!!!!!前面说了springboot对于jsp的支持并不是很好,我们构建成maven的jar包,启动:
$ java –jar springbootDemo-0.0.1-SNAPSHOT.jar
访问http://localhost:8080/hello/handleMVC,显示:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
这是因为。。。webapp这个包标准用在war包中,用在jar包里面,很多构建工具根本不会去识别它,会忽略它。很可怕吧。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
所以,springboot并不鼓励我们用jsp,它鼓励我们静态页面资源使用模板,哈哈哈哈哈哈哈哈哈,所以下面我们找出其中一个模板来学习一下。
注意啦springboot1.5版本不在支持velocity模板啦,所以我把pom中的依赖包换成了1.4.2之后看的
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>1.4.2.RELEASEversion>
<relativePath/>
parent>
参考:
http://www.jianshu.com/p/a9e695a2f3f6使用
http://www.360doc.com/content/12/0105/16/1007797_177482053.shtml语法
http://velocity.apache.org/ 官网
http://blog.csdn.net/zhangxing52077/article/details/73194948 访问静态域动态不同
spring boot会自动配置 FreeMarker,Thymeleaf,Velocity,只需要在pom中加入相应的依赖即可:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-velocityartifactId>
dependency>
默认配置下spring boot会从src/main/resources/templates目录中去找模板
# velocityAutoConfiguration
spring.velocity.charset = UTF-8
spring.velocity.properties.input.encoding=UTF-8
spring.velocity.properties.output.encoding=UTF-8
spring.velocity.suffix = .html
spring.velocity.toolbox-config-location=/WEB-INF/toolbox.xml
这样,SB会从src/main/resources/templates目录中去找以.html后缀的模板文件.
我承认我一直在用同一个bean…
@Component//把普通pojo实例化到spring容器中,相当于配置文件中的 )
public class Student implements java.io.Serializable{
private static final long serialVersionUID = 1L;
//名称
private String name;
//性别
private Integer sex;
//电话
private String telephone;
//生日
private Date birthday;
public Student() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
@RestController
@RequestMapping("/hello")
public class HelloController {
//==============以下是springmvc相关知识==============================
@RequestMapping("/handleMVC")
public ModelAndView handleMVC() {
ModelAndView mav = new ModelAndView();
Student student = new Student();
student.setName("cc");
student.setSex(1);
student.setTelephone("18800000000");
student.setBirthday(new Date());
mav.setViewName("hello1");
mav.addObject("student",student);
return mav;
}
}
<toolbox>
<tool>
<key>DateToolkey>
<scope>applicationscope>
<class>org.apache.velocity.tools.generic.DateToolclass>
tool>
toolbox>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
<style type="text/css">
#tb{width:300px;height:400px;border:1px solid black;}
td{width:100%;height:100%;border:1px solid black;}
style>
head>
<body>
<h1>Student:h1>
<table id="tb">
<thead>
<td>姓名td>
<td>性别td>
<td>电话td>
<td>生日td>
thead>
<tbody>
<td>$!student.nametd>
<td>$!student.sextd>
<td>$!student.telephonetd>
<td>$!DateTool.format('yyyy-MM-dd HH:mm:ss',$!student.birthday)td>
tbody>
table>
<!—生日用的DateTool就是toolbox里面引用的工具 -->
body>
html>
访问:http://localhost:8080/hello/handleMVC显示
以上是通过controller跳转的,如果直接访问此html是找不到的,404
查了下官方文档:
默认情况下, Spring Boot从classpath下一个叫/static提供静态资源
如果我们把hello1.html写在static下面
访问http://localhost:8080/hello1.html,显示:
一般放一些静态资源js,css等文件。。。
因为springboot最新版本不支持了嘛,所以我们学了也有点囧,木有啥意义,网上推荐了FreeMarker,我们来简单学下这个
参考:
http://blog.csdn.net/songhaifengshuaige/article/details/54136984
http://blog.csdn.net/z69183787/article/details/73850417 使用
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
我这里都是使用的默认的,模板默认找templates包,模板默认ftl结尾等
可以自行去设置
# freemarker
# define the ftl location
#spring.freemarker.template-loader-path = classpath:/templates
# static location: js,css
#spring.mvc.static-path-pattern = /static/**
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/handleMVC2")
public ModelAndView handleMVC2() {
ModelAndView mav = new ModelAndView();
Student student = new Student();
student.setName("cc");
student.setSex(1);
student.setTelephone("18800000000");
student.setBirthday(new Date());
mav.setViewName("hello3");
mav.addObject("student",student);
return mav;
}
}
welcome ${student.name} to freemarker!
访问http://localhost:8080/hello/handleMVC2,显示:
welcome cc to freemarker!
如果想学习相关语法可以参考以下:
http://blog.csdn.net/fhx007/article/details/7902040/
http://freemarker.org/docs/官网文档
我们发现返回json的时候ie老是提示要下载,呵呵。
因为之前写过,解决这个问题是通过拦截来实现的,写在了xml中,在springboot中有点不好看,不太合适,也没必要非要返回project对不对,哈哈哈哈哈,返回json到时候去取也好啊,嘿嘿,曲线救国:
Controller:
@RequestMapping(value="/handleBean5")//防止到页面上乱码
public String handleBean5(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
Project pro1 = projectService.findOneProject();
//规避代理类不能转化为json的错误
Project pro = new Project();
pro.setAuthor(pro1.getAuthor());
pro.setName(pro1.getName());
//WebUtil.writeJson(response, data); spring4
//WebUtils.writeHtml(response, pro); // 返回text/html格式的数据
//jackson2转化对象为json
ObjectMapper mapper = new ObjectMapper();
// Convert object to JSON string
String json = mapper.writeValueAsString(pro);
return json;
}
访问http://localhost:8080/project/handleBean5,显示:
至于怎么在springboot里面解决ie返回json提示下载的问题,欢迎有朋友来告诉我一下~