I am new to Spring MVC and Servlets. I am trying to run home() method in controller class SearchController but the output is only from home.jsp file. Statement:
out.println("<h1> this is my response block</h1>");
in not included in the result on browser.
Is there anything that can be done to print the out object statement in the browser with home.jsp file?
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1> this is my response block</h1>");
return "home";
}
}
This is home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
</body>
</html>
This is the output on the browser:
out.println() is used in jsp file. So you can edit your home.jsp as follows
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<%
out.println("<h1> this is my response block</h1>");
%>
</body>
</html>
If you want to add something for home.jsp via the controller class, you can change your controller class as follows.
package springmvcsearch;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SearchController {
#RequestMapping("/home")
public String home(HttpServletRequest req,HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String message = "this is my response block";
req.setAttribute("message", message);
return "home";
}
}
Then change your jsp file as follows.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href="<c:url value='/resources/css/style.css' />"
rel="stylesheet">
<script src="<c:url value='/resources/js/sample.css' /> "></script>
</head>
<body>
This is home view
<h1>${message}</h1>
</body>
</html>
For further explanation, go through this link how to message from servlet and display in jsp
Related
My controller does not replace tags.
My controller has two endpoints URLs "/" and "/login"
#Controller
#RequestMapping(value={"/"})
public class Index {
#GetMapping("/")
public ModelAndView getLoginPageId() {
return new ModelAndView("login");
}
#GetMapping("/index")
public ModelAndView getLoginPageId(
#RequestParam("login") String login,
#RequestParam("password") String password
) {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("message", "123");
return modelAndView;
}
}
login.jsp
<html>
<head>
<title>login</title>
</head>
<body>
<form name="newUser" action="/index" method="get">
Login:<br>
<input type="text" name="login"><br>
Password:<br>
<input type="text" name="password"><br>
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
index.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
</head>
<body>
<h1>My message ${message}</h1>
</body>
</html>
The Chrome browser gives response
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>
The ${message} is not replaced. I'm expecting ${message} should be replaced to 123.
What do I need to change?
Try to add <%# page isELIgnored="false" %> it will enable EL:
Have a look at:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<%# page isELIgnored="false" %>
<meta charset="UTF-8"/>
<title>My Message ${message}</title>
</head>
<body>
<h1>HOA v ${message}</h1>
</body>
</html>
Alternatively you could add <el-ignored>false</el-ignored> to web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</web-app>
I'm using SpringToolSuite with Java and I'm trying to render an index.jsp page onto my localhost:8080, but my Localhost is only going to the Whitelabel error page again & again. I guess it doesn't seem to be recognizing my Homecontroller.java file. The servers are running and have been refreshed. My files are correct. I see no issues anywhere else. What could be wrong that I'm not seeing? How can I render my page?
HomeController.java :
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/your_server")
public class HomeController {
#RequestMapping("")
public String index(HttpSession session) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
Integer count = (Integer) session.getAttribute("counter");
count += 1;
session.setAttribute("counter", count);
return "index.jsp";
}
#RequestMapping("/counter")
public String showCounter(HttpSession session, Model model) {
if (session.isNew()) {
session.setAttribute("counter", 0);
}
model.addAttribute("counter", session.getAttribute("counter"));
return "counter.jsp";
}
#RequestMapping("/reset")
public String resetCounter(HttpSession session) {
session.invalidate();
return "forward:/";
}
}
CounterApplication.java:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class CounterApplication {
public static void main(String[] args) {
SpringApplication.run(CounterApplication.class, args);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome! Want to count some stuff?</title>
</head>
<body>
How many times has this page been visited?
<p>Oh, hi.</p>
</body>
</html>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<c:out value="${2+2}"/>
counter.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>How many times are we going to go through this?!</title>
</head>
<body>
<c:out value="${ counter }" />
Go back.
Reset the counter.
</body>
</html>
I am trying to print some data from my database in Mysql using some classes in java and jsp. It's my first time doing this. I googled a lot but nothing helped me. Here is my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form action="DB_results.jsp">
<input type = "submit" value = "Database">
</form>
</body>
</html>
Draw.java
package DB_draw;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Draw {
ResultSet myRs;
public ResultSet getMyRs() {
return myRs;
}
public void setMyRs() {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tst","root","");
Statement myStmt = myConn.createStatement();
this.myRs = myStmt.executeQuery("select * from tst.people");
while (this.myRs.next())
{
System.out.println(this.myRs.getString("onoma") + " " + this.myRs.getString("epitheto") + " " + this.myRs.getInt("id"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DB_results.jsp
<%#page import="java.sql.ResultSet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# page import="DB_draw.*" %>
<jsp:useBean id="DB_draw" class="DB_draw.Draw" scope="session" />
<jsp:setProperty name="DB_draw" property="*"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Database</title>
</head>
<body style="background-color:black">
<div style = "color:yellow; font-family:fantasy; font-size:30px">
<%
ResultSet myRs = DB_draw.getMyRs();
if(myRs == null) out.println("Problem");
else
while(myRs.next())
{
out.println(myRs.getString("onoma") + " " + myRs.getString("epitheto") + " " + myRs.getInt("id"));
}
%>
</div>
</body>
</html>
The Problem is that when i try to print the results in DB_results.jsp using variable myRs, myRs == NULL. Why is this happening? I'm using Tomcat-Apache 8.0.
You never call setMyRS(). And even if you did, setMyRS() iterates through the resultset, so myRs.next() would always return false in the JSP.
I am new to Struts 2 and trying to do use fileUpload interceptor. I am attaching all my code layers
Action Class (FileUploadAction):
package com.caveofprogramming.actions;
import java.io.File;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport{
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
public String getFileUploadContentType() {
return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
this.fileUploadFileName = fileUploadFileName;
}
public File getFileUpload() {
return fileUpload;
}
public void setFileUpload(File fileUpload) {
this.fileUpload = fileUpload;
}
#Action( value = "/fileUpload",
results={#Result(name="success",location="/success.jsp"),
#Result(name="error",location="/error.jsp"),
#Result(name="input",location="/error.jsp")
},
interceptorRefs={
#InterceptorRef(
params={"allowedTypes","image/jpeg,image/jpg,application/zip",
"maximumSize","1024000"},
value="fileUpload"
),
#InterceptorRef("defaultStack"),
#InterceptorRef("validation")
}
)
public String execute(){
try{
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
public String display() {
return NONE;
}
}
error.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
<s:fielderror/>
</body>
</html>
Success.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Success
</body>
</html>
fileUpload.jsp:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 <s:file> file upload example</h1>
<s:form method="post" enctype="multipart/form-data" action="fileUpload">
<s:file label="File One" name="fileUpload" />
<s:submit />
</s:form>
</body>
</html>
I am not understanding why I am getting this error
"Content-Type not allowed: fileUpload "photography-104a.jpg" "upload_37fbf440_169b_4687_af65_93c8c967256c_00000000.tmp" image/pjpeg"
Although my uploading file format is .jpg.
You are getting this error probably because you don't allow files with content type image/pjpeg. Use parameter of fileUpload interceptor to define allowed MIME types
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/pjpeg</param>
</interceptor-ref>
However I try to get double quotes into my view spring somehow replaces them, here is what I've tried :
#RequestMapping(value="test", method = RequestMethod.GET)
public ModelAndView test(){
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
Wrapper wp = new Wrapper();
wp.setTestField("$(function() { alert(\"test\"); });");
mav.addObject("testObject", wp);
return mav;
}
Wrapper is custom object with one field testField.
#RequestMapping(value="test", method = RequestMethod.GET)
public ModelAndView test(){
ModelAndView mav = new ModelAndView();
mav.setViewName("test");
mav.addObject("testObject", "$(function() { alert(\"test\"); });");
return mav;
}
And jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
<c:out value="${requestScope.testObject.testField}"></c:out>
</script>
</body>
</html>
Result is :
<script type="text/javascript">
alert('test');
</script>
I want to get :
<script type="text/javascript">
alert("test");
</script>
That's because <c:out> automatically escapes your content.
To stop it doing that, use
<c:out escapeXml="false" value="${requestScope.testObject.testField}"/>