I am trying to upload a file into mysql database using struts1.But unable to doso,I am getting the error:FileNotFoundException.Here is my code...
1.JSP Page:
<%# taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<body>
<html:form action="upload" enctype="multipart/form-data">
Select a File :<html:file property="file"/>
<html:submit/>
</html:form>
</body>
</html:html>
2.My Action Form
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm{
private FormFile file;
public FormFile getFile(){
return this.file;
}
public void setFile(FormFile file){
this.file=file;
}
}
3.Action Class
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.sql.*;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
public class UploadAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{
UploadForm file=(UploadForm)form;
System.out.print("Executed");
FormFile formFile=file.getFile();
System.out.print("Executed1");
String fileName=formFile.getFileName();
System.out.print(fileName);
File file1=new File(formFile.getFileName());
System.out.print(">>>>");
FileInputStream fin=new FileInputStream(file1);
System.out.print("*****");
Integer fileSize=formFile.getFileSize();
int insert=0;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded.");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
System.out.println("Connection Opened.");
PreparedStatement pst=con.prepareStatement("insert into upload values(?)");
pst.setBinaryStream(1,fin,fileSize);
insert=pst.executeUpdate();
System.out.print("File Uploaded.");
}
catch(Exception e){System.out.println(e);}
if(insert!=0){
return mapping.findForward("success");
}
else{
return mapping.findForward("error");
}
}
}
I am getting error at this line in my Action Class:FileInputStream fin=new FileInputStream(file1);
Please help me to resolve this problem.
Related
the spring boot REST app with MySQL
I am trying to add record to DB and expect the record added and postman got it as output instead of the output "status":404,"error":"Not Found","path":"/api/employees" following is the classes
package com.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.service.EmployeeService;
import com.model.Employee;
#RestController
#RequestMapping("/api")
public class EmployeeController {
private EmployeeService employeeservice;
public EmployeeController(EmployeeService employeeservice) {
super();
this.employeeservice = employeeservice;
}
//build create Employee REST API
#PostMapping("/employees")
public ResponseEntity<Employee> saveEmployee(#RequestBody Employee employee)
{
return new ResponseEntity<Employee>(employeeservice.saveEmployee(employee), HttpStatus.CREATED);
}
}
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#EnableJpaRepositories(
basePackages = {"com.model"})
#SpringBootApplication(scanBasePackages = {"service.impl"})
public class RestapimysqlApplication {
public static void main(String[] args) {
SpringApplication.run(RestapimysqlApplication.class, args);
}
}
It doesn't look like you're scanning the package that contains your REST controller (i.e. com.controller), seems like you're only scanning the service.impl package on your RestapimysqlApplication class.
You should probably add the com.controller to the list of packages being scanned by Spring here:
#EnableJpaRepositories(basePackages = {"com.repository"})
#SpringBootApplication(scanBasePackages = {"service.impl", "com"})
#EntityScan({"com.model"})
public class RestapimysqlApplication {
...
}
Since i am new to Mockito and AEM model java. I have a gone through some docs and wrote my first Mockito file for AEM Model java. In my code i've not see any errors, but while running i am not getting success and can't complete the code coverage 100%. Can anyone correct/help me to fix my code[given sample java with respective mockito file]
Java File:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#Model(adaptables = SlingHttpServletRequest.class)
public class AccordionModel {
private final static Logger log = LoggerFactory.getLogger(AccordionModel.class);
#SlingObject
private SlingHttpServletRequest request;
#Inject
public ResourceResolverService resolverService;
private Resource resource;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
#PostConstruct
protected void init() throws LoginException, JSONException {
log.info("AccordionModel init method Start");
resource = request.getResource();
final ValueMap configurationOptionProperties = resource.getValueMap();
log.debug("iconfigurationOptionProperties is " + configurationOptionProperties);
String count = configurationOptionProperties.get("count", String.class);
if (count != null) {
for (int i = 1; i <= Integer.valueOf(count); i++) {
Accordion accordion = new Accordion();
String title = configurationOptionProperties.get("title" + i, String.class);
String rte = configurationOptionProperties.get("rte" + i, String.class);
accordion.setTitle(title);
accordion.setRte(rte);
accordionList.add(accordion);
}
}
log.info("AccordionModel init method End");
}
public List < Accordion > getAccordionList() {
return accordionList;
}
}
Mockito code
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.abc.cc.ddd.ResourceResolverService;
import com.abc.cc.ddd.services.models.bean.Accordion;
#RunWith(MockitoJUnitRunner.class)
public class AccordionModelTest {
#InjectMocks
private AccordionModel accordionModel;
#Mock
Resource resource;
#Mock
SlingHttpServletRequest request;
#Mock
ResourceResolverService resourceResolverService;
#Mock
ValueMap valuemap;
public List < Accordion > accordionList = new ArrayList < Accordion > ();
String count = "6";
//max count, based on this count loop execute and get/set into the list
#Before
public void setUp() throws Exception {
when(request.getResource()).thenReturn(resource);
when(resource.getValueMap()).thenReturn(valuemap);
}
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), null);
}
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn("count");
accordionModel.init();
assertEquals(accordionModel.getAccordionList(), count);
}
}
Errors in program its showing line--> accordionModel.init();
java.lang.NumberFormatException: For input string: "count"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at com..services.sling.models.AccordionModel.init(AccordionModel.java:44) at
com..services.sling.models.AccordionModelTest.
shouldReturnWhenPropertyNotNull(AccordionModelTest.java:55)
java.lang.AssertionError: expected:<[]> but was:<null>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com..services.sling.models.AccordionModelTest.
shouldReturnNullWhenPropertyIsNull(AccordionModelTest.java:53)
java.lang.AssertionError: expected:<[]> but was:<null>
If you return null your list is empty. So adjust your test.
Consider renaming the method name as well.
If thats not what you want, you'll need to change your implementation.
#Test
public void shouldReturnNullWhenPropertyIsNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(null);
accordionModel.init();
assertTrue(accordionModel.getAccordionList().isEmpty());
}
java.lang.NumberFormatException: For input string: "count"
"count" can not be converted into an Integer. Try using your count variable ("6") instead.
You should check the content of the list, for now I adjusted it to check that the list has the correct size.
#Test
public void shouldReturnWhenPropertyNotNull() throws LoginException, JSONException {
when(valuemap.get("count", String.class)).thenReturn(count);
accordionModel.init();
assertEquals(Integer.valueOf(count), accordionModel.getAccordionList().size());
}
Note that generally the parameter order for assert's should be expected vs actual.
I am receving a blocker when i tried to run a simple spring boot mysql crud operation.To give you a gist I have a simple jsp home page where i have a register button which navigates to Register page which has a form with one text box and one button called submit.. On click of submit button the values from the form should be pushed to the database. The issue that i'm facing is and error when i tried to click on submit button in register page. Please take alook on the code to have better understanding.
I was doing postmapping and tried to save the data using repository.save() crud operation using #requestbody annotation to create the object.. but doing so gave me the following error
"There was an unexpected error (type=Unsupported Media Type, status=415).
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported".
Controller :
package com.kaushik.Megamart.Controllers;
import java.awt.PageAttributes.MediaType;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.kaushik.Megamart.model.Register;
import com.kaushik.Megamart.repository.RegisterRepository;
#Controller
public class HomeController {
#Autowired
private RegisterRepository repository;
#GetMapping("/")
public String homepage()
{
System.out.println("In Home page");
return "home.jsp";
}
#GetMapping("/register")
public String registerpage()
{
System.out.println("In register page");
return "regist.jsp";
}
#RequestMapping(path ="/regi")
public String savedata(#Valid Register ex) {
repository.save(ex);
System.out.println("Entered function");
return "success.jsp";
}
}
POJO(Register.java):
package com.kaushik.Megamart.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
#Entity
#Table(name="account")
public class Register {
#Id
#NotEmpty
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
regist.jsp :
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<form action="/regi" method="post">
<table>
<tr>
<td>User Name :</td>
<td><input type="text" name="name"/></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</html>
RegisterRepository.java :
package com.kaushik.Megamart.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import com.kaushik.Megamart.model.Register;
public interface RegisterRepository extends JpaRepository<Register, String> {
}
Expected : I want the data from the register form to be pushed to the database.
Actual : Reciving error on clicking submit button in register page.
Error :There was an unexpected error (type=Internal Server Error, status=500).
could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement
I've been trying to figure the code out for quite a while now, however have had no success. Everytime the App crashes by throwing some random exception.
I learnt this code off a tutorial on youtube and despite that, the code doesn't work for me.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Button b1;
TextView t1;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.bthhit);
t1=(TextView)findViewById(R.id.tvJSONitem);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpsURLConnection connection = null;
BufferedReader reader = null;
#Override
protected String doInBackground(String... params) {
try {
URL url=new URL(params[0]);
connection= (HttpsURLConnection)url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuffer buffer= new StringBuffer();
while((line=reader.readLine())!=null){
buffer.append(line);
}
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection!=null) {
connection.disconnect();
}
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
t1.setText(result);
}
}
}
Logcat shows this:
01-05 00:46:09.018 5573-5580/? E/art: Failed sending reply to debugger: Broken pipe
01-05 00:46:17.852 5573-5706/com.example.test.jsonparser E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.test.jsonparser, PID: 5573
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast to javax.net.ssl.HttpsURLConnection
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:58)
at com.example.test.jsonparser.MainActivity$JSONTask.doInBackground(MainActivity.java:49)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
01-05 00:46:19.104 5573-5587/com.example.test.jsonparser E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab792110
Please note that your URL protocol is HTTP and not HTTPS. Try either using a java.net.HttpURLConnection object or a "https://..." URL.
If some specific methods like .getResponseCode() or,... are not needed in your app, then you can use the generic URLConnection class as well, which will refrain from introducing this kind of exceptions, since it is the parent class for both HttpURLConnection and Https... classes somehow.
I was watching tutorial and i created user-login and verifying the user, when i created addGoal, my goal was not entering in my mysql database, since i am able to login so my database connection are correct, and i am using thymeleaf with javaconfig for my annotations, please help me with this i am new to this. I think there is error in my addGoal.html, as i am using thymeleaf i think i am not doing in correctly, please can someone help me to fix it, i think i am not handling #modelattribute correctly
Goal class is :
package com.pluralsight.model;
import hello.User;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Range;
import org.springframework.web.bind.annotation.ModelAttribute;
#Entity
#Table(name="goals")
public class Goal {
public static final String FIND_ALL_GOALS = "findALLGoals";
public static final String FIND_GOAL_REPORTS = "findGoalReports";
#Id
#GeneratedValue
#Column(name="GOAL_ID")
private Long id;
#Range(min = 1, max = 120)
#Column(name="MINUTES")
private int minutes;
// #OneToMany(mappedBy="goal",cascade=CascadeType.ALL, fetch=FetchType.LAZY)
// private List<Exercise> exercises = new ArrayList<Exercise>();
#ManyToOne
#JoinColumn(name="USER_NAME")
private User user;
//
// public List<Exercise> getExercises() {
// return exercises;
// }
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return id;
}
public int getMinutes() {
return minutes;
}
// public void setExercises(List<Exercise> exercises) {
// this.exercises = exercises;
// }
public void setId(Long id) {
this.id = id;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
}
This is my goalcontroller.java
package com.pluralsight.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.pluralsight.model.Goal;
import com.pluralsight.model.GoalReport;
import com.pluralsight.model.User;
import com.pluralsight.service.GoalService;
#Controller
#SessionAttributes("goal")
public class GoalController {
#Autowired
private GoalService goalService;
#RequestMapping(value = "addGoal", method = RequestMethod.GET)
public String addGoal(Model model, HttpSession session ) {
//Goal goal = new Goal();
Goal goal = (Goal)session.getAttribute("goal");
if(goal == null){
goal = new Goal();
goal.setMinutes(10);
}
model.addAttribute("goal", goal);
return "addGoal";
}
#RequestMapping(value = "addGoal", method = RequestMethod.POST)
public String updateGoal(#Valid #ModelAttribute Goal goal, BindingResult result) {
System.out.println("result has errors: " + result.hasErrors());
System.out.println("Goal set: " + goal.getMinutes());
if(result.hasErrors()) {
return "addGoal";
}else{
goalService.save(goal);
}
return "redirect:index.jsp";
}
#RequestMapping(value="getGoals", method= RequestMethod.GET)
public String getGoals(Model model){
List<Goal> goals = goalService.findAllGoals();
model.addAttribute("goals", goals);
return "getGoals";
}
#RequestMapping(value="getGoalReports", method= RequestMethod.GET)
public String getGoalReports(Model model){
List<GoalReport> goalReports = goalService.findAllGoalReports();
model.addAttribute("goalReports", goalReports);
return "getGoalReports";
}
}
Here is my GoalRepository
package com.pluralsight.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.pluralsight.model.Goal;
#Repository("goalRepository")
public interface GoalRepository extends JpaRepository<Goal, Long>{
}
And here is my GoalServiceImpl.java
package com.pluralsight.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.pluralsight.model.Goal;
import com.pluralsight.model.GoalReport;
import com.pluralsight.repository.GoalRepository;
#Service("goalService")
public class GoalServiceImpl implements GoalService {
#Autowired
private GoalRepository goalRepository;
#Transactional
public Goal save(Goal goal) {
return goalRepository.save(goal);
}
public List<Goal> findAllGoals() {
return (List<Goal>) goalRepository.findAll();
}
public List<GoalReport> findAllGoalReports() {
return null;
// return goalRepository.findAllGoalReports();
}
}
And here is my addGoal.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
</head>
<body>
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#"> Add Goal </a>
<ul class="nav"></ul>
</div>
</div>
</div>
<div class="container">
<div>
<h1>Add Goal</h1>
<p>Add your workout goal in minutes for the day.</p>
</div>
<form th:action="#{/addGoal}" method="post">
<div>
<label> Enter Minutes : <input type="text" name="minutes" />
</label>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<div class="control-group"></div>
</div>
</body>
</html>
When i am changing my form in addGoal.html as
<form action="#" th:action="#{/addGoal}" th:object="${goal}" method="post">
<p> enter Minutes: <input type="text" th:field="*{goal.minutes}"/></p>
<p><input type="submit" value="enter goal minutes"/></p>
</form>
Then i am getting error as : Neither BindingResult nor plain target object for bean name 'goal' available as request attribute
Lets take a step back focus on restless state first.
For your form use this:
<form th:object="${goal}" th:action="#{/addGoal}" method="post">
<div>
<label> Enter Minutes : <input type="text" th:field="*{minutes}" />
</label>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Next change:
#RequestMapping(value = "addGoal", method = RequestMethod.GET)
public String addGoal(Model model, HttpSession session ) {
Goal goal = new Goal();
Goal sessionGoal = (Goal)session.getAttribute("goal");
if(sessionGoal == null && sessionGoal.getMinutes() == 0){
goal.setMinutes(10);
}
else {
goal.setMinutes(sessionGoal.getMinutes());
}
model.addAttribute("goal", goal);
return "addGoal";
}
Also you are doing return "redirect:index.jsp"; yet you are using Thymeleaf. This ain't going to work.
You need to "redirect:/index" or "redirect:/" depending on your home parameter.
EDIT 1:
change the following lines in your POST method of addGoal:
#RequestMapping(value = "addGoal", method = RequestMethod.POST)
public String updateGoal(#Valid #ModelAttribute("goal") Goal goal, BindingResult result) {